MATLAB: Problems with legend function for plotting figure

indexinglegendloops

Hi,
Below is a copy of my script for graphing a figure that has 22 inputs of data. Each input of data comes from a different variable, and I have assigned each variable a name in the legend. I would like to make a loop for the list names instead of having to input the name manually. Plus, each time I have different number of variables I'm plotting, I have to either add or remove names from the legend.
Write loops aren't a problem for me, what the problem is getting the right amount of names for the legend function. I've tried making a variable that has a list of the names, then tried to index the variable while inside the legend function, but I can't seem to get that to work either.
Any help is appreciated

Best Answer

  • Perhaps this would be a good area to use the eval().
    here is an example:
    bird_id = '123';pix_size = '10';stim_dir = 'N'; bdistance = '12';
    legend_text = [];
    for bnum = 1:3
    legend_text = [ legend_text '[''Bird' bird_id ' with ' pix_size stim_dir ' at ' bdistance '''],'];
    end
    legend_text = [legend_text '''location'',''NorthWest'''];
    What the for loop does is creates the text for what goes inside the legend (location pasted at the end.
    ['Bird123 with 10N at 12'],['Bird123 with 10N at 12'],['Bird123 with 10N at 12'],'location','NorthWest'
    so when i call it in
    eval(['legend(' legend_text ')'])
    it should do everything inside of your long legend callout.