How can I create a matrix of linestyles for plot to loop through?

18 views (last 30 days)
So, I have this:
linedex={'-','--','-.',':'};
x=[-2;-3;-4];
for i=1:4
mmm= [0.0803 0.1912 0.1245
0.0239 0.3246 0.1581
0.0164 0.5584 0.2294]; %%%For each loop it gets a different set of values, this is and example one, with the columns being min,max,mean
hold on
plt=plot(x,mmm)
plt.LineStyle(i)=linedex(i);
end
I've also tried plotting them individually, where its the same linedex and loop replacing mmm with three vectors instead.
x=[-2 -3 -4]
min=[0.0803 0.0239 0.0164]
max=[0.1912 0.3246 0.5584]
mean=[0.1245 0.1581 0.2294]
plot(x,min,x,max,x,mean)
but then how would I call to those specific lines, to have them all be one style, while the next set of min,max, and mean are in a new style/and then colors eventually?

Accepted Answer

Stephen23
Stephen23 on 26 Jul 2018
Edited: Stephen23 on 26 Jul 2018
You were almost there, you just need to use the right kind of cell array indexing:
C = {'-','--','-.',':'};
x = [-2;-3;-4];
for k = 1:numel(C)
% Simpler:
mmm = k+[0.0803,0.1912,0.1245;0.0239,0.3246,0.1581;0.0164,0.5584,0.2294];
plot(x,mmm,C{k})
% OR alternatively
%plt = plot(x,mmm);
%plt.LineStyle = C{k};
hold on
end
Which produces this:

More Answers (1)

Sushant Mahajan
Sushant Mahajan on 25 Jul 2018
Edited: Sushant Mahajan on 25 Jul 2018
You can use a combination of eval and sprintf. Here I am plotting successive powers of sin(x).
linestyles={'-','--','.-'};
x=linspace(0,90,100);
for i=1:3
eval(sprintf('plot(x,sind(x).^%d,''%s'')',i,cell2mat(linestyles(i))))
hold on
end
Hope this helps!
  2 Comments
Stephen23
Stephen23 on 26 Jul 2018
Edited: Stephen23 on 26 Jul 2018
Why on earth do you use eval for this? This is bad advice: eval is totally unnecessary, and pointlessly teaches bad habits to other beginners: using eval for trivial code like this is how beginners force themselves into writing slow, complex, buggy code that is hard to debug. Avoid using this code. Read this to know why:
The code is simpler, neater, and more efficient without eval:
C = {'-','--','.-'};
x = 0:90;
for k = 1:numel(C)
plot(x,sind(x).^k,C{k})
hold on
end

Sign in to comment.

Categories

Find more on Graphics Performance in Help Center and File Exchange

Products


Release

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!