matlabplotoctavematlab-figurelinestyle

How to cycle through line styles in Octave while keeping same color?


My goal is to plot 2 different main functions on the same figure, but also be able to plot on top of those similar functions that relate to how those original 2 functions evolve. For example, the 1st function will be red and solid, its subsequent similar functions will be the same color but cycle through different line styles, similarly for the 2nd function they will all be blue but also will cycle through line styles. Here is some sample code:

lstyle = {" '-' ", " '--' ", " ':' ", " '-.' "};
i=1;

%Plot:
for n=1:3
  choose_lstyle = lstyle{i};
  y1 = (z.*n).^2;
  y2 = (z.*n).^3;
  plot(z,y1,'r','linestyle',choose_lstyle);
  plot(z,y2,'b','linestyle',choose_lstyle);
  n++;
  if i < length(lstyle) %cycle through line styles
    i = i+1;
    else
    i = 1;
  end
  hold on;
end

I am trying to place '-' or ':' quotes and all right where my choose_lstyle is. Basically it's exactly like how you would have if you had only one line style where it is in quotes, except I am trying to cycle through the line styles.

The error I get when running this is:

error: set: invalid value for radio property "linestyle" (value =  '-' )
error: called from
__line__ at line 120 column 16
line at line 56 column 8
__plt__>__plt2vv__ at line 500 column 10
__plt__>__plt2__ at line 246 column 14
__plt__ at line 113 column 17
plot at line 220 column 10
PROGRAM_NAME at line 37 column 3
enter code here

Solution

  • You had several mistakes there, here is a working code:

    lstyle = {'-','--',':','-.'};
    z = 1:100;
    
    %Plot:
    k = 1;
    for n = 1:10
        y1 = (z.*n).^2;
        y2 = (z.*n).^2.1; % I changed it from 3 so you can see the red lines
        plot(z,y1,'r',z,y2,'b','linestyle',lstyle{k});
        if k < length(lstyle) %cycle through line styles
            k = k+1;
        else
            k = 1;
        end
        hold on;
    end
    

    line_style

    Feel free to ask for any unclear part in the comments.


    This code will give you similar results, but it's more compact and efficient:

    lstyle = {'-','--',':','-.'};
    z = 1:10;
    by = bsxfun(@times,z.',1:10).^2;
    ry = bsxfun(@times,z.',1:10).^2.1;
    p = plot(z,ry,'r',z,by,'b');
    k = 1;
    for n = 1:numel(p)
        p(n).LineStyle = lstyle{k};
        k = k+1;
        if k > numel(lstyle)
            k = 1;
        end   
    end
    

    If youre version of MATLAB is erlier then 2014, or you just look for a compact code, you can also write:

    lstyle = {'-','--',':','-.'};
    z = 1:10;
    by = bsxfun(@times,z.',1:10).^2;
    br = bsxfun(@times,z.',1:10).^2.1;
    p = plot(z,br,'r',z,by,'b');
    lineStyles = repmat(lstyle,1,ceil(numel(p)/numel(lstyle)));
    set(p,{'LineStyle'},lineStyles(1:numel(p)).');