问题
I have a matrix 'capacity' and I want to plot its row and for that I have used a loop, my code is
for j_1=1:8
plotStyle = {'k -','r +','g *','b.','y o','r--','b d','g s'};
hold on;
plot(x_1,capacity(j_1,:),plotStyle(j_1));
end
hold off;
x_1 is just the x axis, the number of elements in x_1 is equal to the number of columns of capacity.But I am getting error as:
Error using plot
Invalid first data argument
Error in varyingDiffusioncofficient (line 124)
plot(x_1,capacity(j_1,:),plotStyle)
回答1:
Edit: all you need to do is replace the round braces by curly braces in the call to plot, i.e.
plot(x_1,capacity(j_1,:),plotStyle{j_1});
Alternatively, you could separate the color and linestyle and make the call this way. This might be convenient when you make even larger plots and want to loop in different ways through the combinations of colors and linestyles.
capacity = rand(8,8); % test data for a workable example
x_1 = 1:8;
for j_1=1:8
linestyle = {'-','+','*','.','o','--','d','s'};
color = {'k','r','g','b','y','r','b','g'};
hold on;
plot(x_1,capacity(j_1,:),'color',color{j_1},'linestyle',linestyle{j_1});
end
hold off;
回答2:
Your issue is accessing a cell array with normal parentheses ()
, you should be using curly braces {}
.
plotStyle = {'k -','r +','g *','b.','y o','r--','b d','g s'};
% plotStyle(1) = {'k -'} : cell
% plotStyle{1} = 'k -' : string
So
hold on; % Move the hold and style assignment outside the loop for efficiency
plotStyle = {'k -','r +','g *','b.','y o','r--','b d','g s'};
for j_1=1:8
plot(x_1,capacity(j_1,:),plotStyle{j_1});
end
hold off;
Documentation link for accessing data in a cell array
来源:https://stackoverflow.com/questions/44151168/why-my-plot-is-not-working-in-loop-for-different-graph-representations