How to loop through multiple text files and make plot for each one in a single script?

I have 5 text files that have the same exact variables and column formats. The txt. files are named a1.txt, a2.txt, etc. I have a script that solves for a velocity value as every x coordinate in the txt file. I would like to run all 5 txt files and then plot their different velocity function into one figure, so that I can compare. Here is the code I have so far:
%Open and read txt file
fid = fopen('Test.txt','rt');
fgetl(fid);
data = fscanf(fid,'%f',[7, Inf]);
%Grab variables from txt file
s = data(:,1);
x = data(:,2);
%Calculating V
%EXAMPLE EQUATION
v = 2*s
figure
plot(x,v,'Color',[0,0.7,0.9])
title('Test Plot')
xlabel('x')
ylabel('v')
Now what I would like to do is create a loop that reads 5 txt files in my directory, then create 5 different plots within 1 figure

 採用された回答

KSSV
KSSV 2021 年 9 月 24 日
編集済み: KSSV 2021 年 9 月 24 日
txtFiles = dir('*.txt') ;
N = length(txtFiles) ;
figure
hold on
for i = 1:N
%Open and read txt file
fid = fopen(txtFiles(i).name,'rt');
fgetl(fid);
data = fscanf(fid,'%f',[7, Inf]);
%Grab variables from txt file
s = data(:,1);
x = data(:,2);
%Calculating V
%EXAMPLE EQUATION
v = 2*s
plot(x,v)
end
title('Test Plot')
xlabel('x')
ylabel('v')
legend

5 件のコメント

Error for this line:
fid = fopen(txtFiles)i).name,'rt');
The error reads:
File: A1Code.m Line: 11 Column: 26
Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax
error. To construct matrices, use brackets instead of parentheses.
KSSV
KSSV 2021 年 9 月 24 日
It is a typo error..... edited the code.
Andrew Lackey
Andrew Lackey 2021 年 9 月 24 日
Thank you, it works perfectly! How can I make each plot a different color? And add a legend?
KSSV
KSSV 2021 年 9 月 24 日
You can save the data into array and use your required color. Read about legend to give your required names.
Andrew Lackey
Andrew Lackey 2021 年 9 月 24 日
Thank you!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeInteractive Control and Callbacks についてさらに検索

質問済み:

2021 年 9 月 24 日

コメント済み:

2021 年 9 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by