Is it possible to identify data in a for loop?

I have a code in which I pull files from '.txt' files and run them in a for loop in order to plot them all together. I was wondering if there was a way for me to identify each line separately in the plot. Here is the code and an example file,
myFolder = 'C:\Users\administrador\Desktop\Curves';
d=dir(fullfile(myFolder, '*.txt'))
figure, hold on
for k = 1:numel(d)
data=dlmread(fullfile(myFolder,d(k).name));
plot(data(:,4),data(:,5),'LineWidth',3);
xlim([0 7])
ylim([0 4])
end

 採用された回答

jonas
jonas 2020 年 8 月 1 日

0 投票

I would probably collect the data in the loop instead and then call plot outside of the loop. Could use something like this:
d=dir(fullfile(myFolder, '*.txt'))
for k = 1:numel(d)
data=dlmread(fullfile(myFolder,d(k).name));
x{k} = data(:,4);
y{k} = data(:,5);
end
figure;hold on
h = cellfun(@plot,x,y,'uniformoutput',1);
xlim([0 7])
ylim([0 4])
legend(h,{d.name})
If you really want to label the data inside the loop then you can set the displayname:
d=dir(fullfile(myFolder, '*.txt'))
figure, hold on
for k = 1:numel(d)
data=dlmread(fullfile(myFolder,d(k).name));
h(k) = plot(data(:,4),data(:,5),'LineWidth',3,'displayname',d(k).name);
xlim([0 7])
ylim([0 4])
end
legend

6 件のコメント

Feliciano Döring
Feliciano Döring 2020 年 8 月 1 日
編集済み: Feliciano Döring 2020 年 8 月 1 日
With the first alternative I get:
%Error using cellfun
%matlab.graphics.chart.primitive.Line output type is not supported. Set
%'UniformOutput' to false.
But the second one works fine, so thank you!
Edit.
I was wondering, why would you assign the plot to a variable?
jonas
jonas 2020 年 8 月 1 日
Odd, cellfun outputs a set of line handles here with my own test files. Could possibly fail if more than one line is stored in the same cell. You could try setting uniformoutput to false and see what is being stored in the variable h.
Feliciano Döring
Feliciano Döring 2020 年 8 月 1 日
I changed it and it's a 1x21 cell with 1x1 line in each
Feliciano Döring
Feliciano Döring 2020 年 8 月 2 日
By the way, is there a way to not display the '.txt' extension on the displayname?
jonas
jonas 2020 年 8 月 2 日
Not sure why the first method did not work then, perhaps a release issue.
Sure, just do not pass the 4 last characters
h(k) = plot(data(:,4),data(:,5),'LineWidth',3,'displayname',d(k).name(1:end-4));
Feliciano Döring
Feliciano Döring 2020 年 8 月 2 日
Thanks!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2015a

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by