How to load different txt files with different names in for loop?

2 ビュー (過去 30 日間)
Simon
Simon 2022 年 12 月 29 日
コメント済み: Simon 2022 年 12 月 29 日
Hello, I have a big amount of txt files which have different names after the mount which is constant, their names go like 'mount_1_max_mz.txt'. The number between mount and max can vary between 1 and 5, the max word can either be avg or max and then the last two letters can vary quite signifcantly from mz, my, mx to fy, fx and fz. Each txt files of those has two columns containing data corresponding to x and y values that I want to plot. I want my for loop code to read the data from all these txt files, plot their data, and of course vary the legend, titles y axis names based on the name of txt file. my mz and mx correspond to torque and fx fy and fz correspond to force. Can anyone please help me :)

回答 (1 件)

Cameron
Cameron 2022 年 12 月 29 日
Rather than dynamically creating names for files, I think it would be better to select the files you want to open and plot them. I would do something like this
[file,path] = uigetfile('*.txt','MultiSelect','on'); %select path
if path == 0; return; end %if you hit cancel or exit out of the uigetfile screen
if ~iscell(file); file = {file}; end %if you only select one file, then make that file into a cell array
cd(path) %change directory
hold on %hold onto the plot
for FileNum = 1:length(file) %loop through the files
%this is an example of a file where x data is in column 1
%and y data is in column 2. you can configure everything
%within the for loop however you'd like
ReadFileData = readmatrix(string(file(FileNum)));
plot(ReadFileData(:,1),ReadFileData(:,2),'-o')
end
hold off %end hold
legend(extractBefore(file,'.'),'Location','northeast') %configure your legend how you'd like

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by