Using Variable in Legend in for loop
1 view (last 30 days)
Show older comments
I want to use variable in legend in a scatter plot. I found similar questions about variable in legend. However, they are not in a for loop. I need it in a for loop. How can I do this? My code is :
close all;clear all; clc;
x=-20:5:20;
y=-20:5:20;
z=40:5:80;
[X,Y,Z]=meshgrid(x,y,z)
h=0;
for i=1:1:length(x)
for j=1:1:length(y)
for k=1:1:length(z)
h=h+1
M(h,:)=[X(i,j,k), Y(i,j,k), Z(i,j,k)];
N(h)=bul_poz_real_cozum_sayisi([M(h,1); M(h,2); M(h,3) ],[0;0;0]);
end
end
end
NN = unique(N); NN_length=length(NN);
BB = unique(B); BB_length=length(BB);
S=[10 10 20 20 30 ];
figure; hold on;
for i = 1:NN_length
NNN = (N == NN(i)); % Without FIND: faster logical indexing
scatter3(M(NNN, 1), M(NNN, 2), M(NNN, 3), S(i),'filled');hold on;
str = {strcat( num2str(NN(i)), 'Solutions')};
legend(str{:})
end
xlim([x(1),x(end)]);ylim([y(1),y(end)]);zlim([z(1),z(end)]);
axis equal; grid on;rotate3d;view(3);
It only writes the last legend, and deletes the preious legend. NN=[4 6 8 10 12]. So the legend should be like this:
- 4 Solutions
- 6 Solutions
- 8 Solutions
- 10 Solutions
- 12 Solutions
0 Comments
Answers (1)
Srivardhan Gadila
on 10 Feb 2021
You can make use of the 'DisplayName' name value pair argument as follows:
x = 1:4;
figure
hold on
for i=1:4
z = linspace(0,4*pi,250)/i;
x = 2*cos(z) + rand(1,250);
y = 2*sin(z) + rand(1,250);
scatter3(x,y,z,'filled','DisplayName',num2str(i))
end
legend
0 Comments
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!