How to dynamically create and update a legend ?

Hi to all,
I have a simple script that:
  1. loads a *.mat file with a specific name and which is placed in the project directory
  2. plots a figure according to data/variables within the same *.mat file
the above two steps are cycled (inside a "for") and repeated 5 times. I use "hold on" so as to plot the 5 different figures inside the same window/plot.
At the end of my script I get a single window with 5 overlayed plots...which are unfortunately quite tricky to identify one from the other.
Script demo as follows:
for h=1:5;
filename = sprintf('file_%03d.mat', h);
load(filename);
cdfplot (file_gnd);
hold on;
So, I would like to add a legend and give a name to the different curves. The name in the legend should be simply the name of the *.mat file I load before and I am getting data from. So, in my example I should have a legend with labels "file_001.mat", "file_002.mat" and so on (according to 'h' range). My idea would be to create the legend inside the cycle and then populate it for each run of the cycle but it is not working since I am not able to give "legend" a dynamic parameter which is a function of 'filename' (and thus 'h' in my case).
Any idea ?

 採用された回答

Majid Farzaneh
Majid Farzaneh 2018 年 5 月 24 日
編集済み: Majid Farzaneh 2018 年 5 月 24 日

2 投票

Hi, You don't have to create legend dynamically, Do it out of loop like this:
for h=1:5;
filename = sprintf('file_%03d.mat', h);
load(filename);
cdfplot (file_gnd);
hold on;
end
legend('file_001.mat', 'file_001.mat', 'file_001.mat', 'file_001.mat', 'file_001.mat');
legend assigns labels respectively. If you are not sure about this, you can test this code:
x=0:0.01:2*pi;
plot(sin(x));
hold on
plot(cos(x));
hold on
plot(sqrt(x))
legend('sin','cos','sqrt')

4 件のコメント

Majid Farzaneh
Majid Farzaneh 2018 年 5 月 24 日
編集済み: Majid Farzaneh 2018 年 5 月 24 日
But if you persist to do it dynamically you can store every string of the loop in a cell array and then out of loop call legend with the cell array:
for h=1:5;
filename = sprintf('file_%03d.mat', h);
M{h}=filename;
load(filename);
cdfplot (file_gnd);
hold on;
end
legend(M);
Maximilian Arpaio
Maximilian Arpaio 2018 年 5 月 27 日
Storing every string in a cell array is the answer that fits my need. I had to adapt the idea to my script since the loop does not go exactly from 1 to 5 but it depends on a specific situation ( i.e even from 50 to 179 with 2.5 steps) but now it works. Thanks man !
Majid Farzaneh
Majid Farzaneh 2018 年 5 月 28 日
You're welcome
Hari Krishnan K P
Hari Krishnan K P 2020 年 7 月 22 日
Great idea..!!!! @Majid Farzaneh

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating, Deleting, and Querying Graphics Objects についてさらに検索

製品

リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by