Search code examples
matlabplotmatlab-figure

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


I have written this loop to plot each line of results and I get the error message

Error using plot. Invalid first data argument.

So far it looks like this

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

If I use plot(xint,test(ii,:),'-y','linewidth',2) then it works. But how can I avoid the error when looping through line styles?


Solution

  • You should write:

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

    LineSpec is a cell array, so LineSpec(ii) returns a cell, while plot asks for a character array as line properties.

    you can see the difference when you call LineSpec:

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

    When the output is a cell then the answer is indented and has the single-quote marks.