1
votes

i have searched a lot but i did not manage to create a for-loop, or something similar in order to add an extra entry in the legend area in every loop. For example: 1st loop- 1 entry in the legend 2nd loop- 2 entries in the legend... i have tried the legappend function but i get errors, even with examples that are provided. Below you can see a section of my code:

    Eb_N0_dB = [-10:25];        
    k_dB=[-inf 10 20];             
    figure(1)
    hold on
    semilogy(Eb_N0_dB,simBer);
    legend(sprintf('sim (nTx=2, nRx=2 k=%d, Alamouti)',k_dB(1)))
    legend boxoff

    for qq=2:length(k_dB)
    legappend(sprintf('sim (nTx=2, nRx=2 k=%d, Alamouti)',k_dB(qq)))
    end

   %%simBer is a {length(k_dB),length(Eb_N0_dB)} matrix

i get the error below

    Error using legend (line 120)
    Invalid argument. Type 'help legend' for more information.

    Error in legappend (line 74)
    [legend_h,object_h,plot_h,text_strings] = legend(h,allDatah,str);

Any suggestions? Regards

1
This problem only affects matlab 2014b or later.Daniel
It may be worth noting that legappend is not part of the standard MATLAB library and you have to get it through FEX: mathworks.com/matlabcentral/fileexchange/47228-legappendrayryeng

1 Answers

4
votes

I create an empty variable and then add cell array elements of strings for each legend entry. Appending a legend entry at the point in code where you add a plot is a convenient way to keep things organized - otherwise you may have blank or doubled legend entires:

x = 1:4;
figure
hold all

L ='';
%L = cell(1,N);

for j = 1:length(x)

    scatter(j,x(j),60,'filled');
    L = [L,{num2str(j)}];

end

%additional plots are easily added or taken out, leaving the legend in tact:
scatter(rand,rand,90,'x','linewidth',3);
L = [L,'optional data a'];

scatter(rand,rand,90,'x','linewidth',3);
L = [L,'optional data b'];

legend(L);