Problems with legend function for plotting figure

1 view (last 30 days)
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

Accepted Answer

Joseph Cheng
Joseph Cheng on 25 Jun 2014
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.
  2 Comments
Tyee
Tyee on 25 Jun 2014
This works beautifully, thanks a lot!
I've never used the eval() function, thanks for showing it to me.
Tyee
Joseph Cheng
Joseph Cheng on 26 Jun 2014
use it sparingly and with caution. I lost the links saying why you shouldn't default to it. But it boils down to its harder to debug.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!