0

I want to plot four straight lines with different slopes given by a vector $A$:

A=[1.1,2.3,7.9];
k=0;
x=-1:0.01:1;
for n=1:3
    plot(x,A(n)*x)
    hold on
end

However, it turns out that all lines are of the same color (blue). How do I plot them in different colors, but still using for-end command? (this is necessary when the vector $A$ is huge...)

No One
  • 121
  • 4

3 Answers3

1

Actually it can be solved by putting a "hold all" before for-end loop:

A=[1.1,2.3,7.9];
k=0;
x=-1:0.01:1;
hold all
for n=1:3
    plot(x,A(n)*x)
end

I am using 2013a. Not sure other versions of Matlab have the same issue and solution.

No One
  • 121
  • 4
  • 2
    `hold all` will be removed in a future release and is same as `hold on`. – Sardar Usama Jan 09 '19 at 17:23
  • 2
    A) `hold on` needs to be provided only once (so the change from your question to here), B) it's better to say `figure;hold on`, such that you're sure that you're in the right figure. C) Stack Overflow does not have MathJax, so TeX codes do not work; use simple code formatting instead. BTB: Welcome to Stack Overflow as well! – Adriaan Jan 09 '19 at 17:30
1

You could make a colormap (e.g. lines) to specify the colors for all the different lines. By using set on the handle to the lines, you don't have to use a for loop.

A=[1.1,2.3,7.9];
x=-1:0.01:1;

cmap = lines(numel(A));
p = plot(x,A.'*x);

set(p, {'color'}, num2cell(cmap,2));

Alternatively, if you do want to use a for loop, you can set the color using the same colormap, on each loop iteration:

figure()
axes;
hold on;

cmap = lines(numel(A));

for n = 1:numel(A)
    plot(x,A(n)*x, 'Color', cmap(n,:));
end
rinkert
  • 6,593
  • 2
  • 12
  • 31
0

Use the following

A=[1.1 2.3 7.9];
x=[-1 1]; % use this instead of x=-1:0.01:1
line(x,A'*x);

result:

enter image description here

Also, if you wish to manipulate the colors manually, use the following code:

A=[1.1 2.3 7.9];
L=length(A);
col_mat=rand(L,3); % define an arbitrary color matrix in RGB format
x=[-1 1]; % use this instead of x=-1:0.01:1
p=line(x,A'*x);
%% apply the colors
for i=1:L
    p(i).Color=col_mat(i,:);
end
Mostafa Ayaz
  • 480
  • 1
  • 7
  • 16