在 Matlab 中绘制多条线(在元胞数组中循环线型)

Plot several lines (looping through line styles in cell array) in Matlab

我已经编写了这个循环来绘制每一行结果,但我收到了错误消息

Error using plot. Invalid first data argument.

到目前为止看起来像这样

test=rand(5,6);
xint=[1:1:6];
LineSpec = {'-y', '--m', ':c', '-r.', '-b', ':s'};

for ii=1:5,
    plot(xint,test(ii,:),LineSpec(ii),'linewidth',2);
    hold on;
    legend_str{ii} = num2str(ii);
end

如果我使用 plot(xint,test(ii,:),'-y','linewidth',2) 就可以了。但是如何在循环线型时避免错误?

你应该写:

plot(xint,test(ii,:),...
        LineSpec{ii},...
        'linewidth',2);

LineSpec 是一个元胞数组,所以 LineSpec(ii) returns 是一个元胞,而 plot 要求一个字符数组作为行属性。

调用LineSpec可以看到区别:

>> LineSpec{1}
ans =
-y
>> LineSpec(1)
ans = 
    '-y'

当输出为单元格时,答案会缩进并带有单引号。