MATLAB legend iteration - ntuzxy/blog GitHub Wiki

Welcome to the blog wiki!

To plot figures using for loop and generate legend spontaneously.

%% plot
x=1:9;
str = strings(1,15);
str_num = 1;
figure; 
for i= 1:2
    for j = 3:4
        y = x.*(i*j);
        hold on
        plot(1:9, y,'-o');
    str(str_num) = strcat('i=', num2str(i), ',j=', num2str(j));
    str_num = str_num + 1;
    end
end
legend(str)

You can also plot separately and save in .fig format.

%% plot and save
x=1:9;
str = strings(1,15);
str_num = 1;
figure; 
for i= 1:2
    for j = 3:4
        y = x.*(i*j);
%         hold on
        plot(1:9, y,'-o');
        str(str_num) = strcat('i=', num2str(i), ',j=', num2str(j));
        savefig(strcat(str(str_num),'.fig'))
        str_num = str_num + 1;
    end
end
legend(str)