How do I implement sort_nat.m a function for opening and reading files?

I am a beginner matlab user and I want to read all files of a certain type in a folder, and save certain pieces of data (in this case line 18) out of the file as a matrix.
I have pieced together this code from various sources. It isn't exactly what I want but it's getting close.
This code will save the data in the wrong order, as the files are being read in the order file001, file015, file002.
Because of this I need to use the sort_nat.m function that I have downloaded and placed in the matlab directory, however I do not know where to implement it.
If you have a better way to write this script or can show me how to implement sort_nat.m that would be great.
Thanks
% Specify the folder where the files live.
myFolder = 'D:\Capstone\TFI Data\2D Curtain test 1';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.asA'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
fid = fopen(fullFileName,'rt');
data = cell2mat( textscan(fid, '%f', 'HeaderLines', 17, 'collectOutput', true) );
fclose(fid);
V(k)= data(1)
end

 採用された回答

Stephen23
Stephen23 2019 年 2 月 6 日
編集済み: Stephen23 2021 年 4 月 26 日
You can download my FEX submission NATSORTFILES here:
and also look at the Examples page, which shows how to use it with filenames. Following those examples, your code would be like this:
P = 'D:\Capstone\TFI Data\2D Curtain test 1';
S = dir(fullfile(P,'*.asA'));
S = natsortfiles(S);
for k = 1:numel(S)
F = fullfile(P,S(k).name);
fprintf(1,'Now reading %s\n',F);
fid = fopen(F,'rt');
C = textscan(fid, '%f', 'HeaderLines', 17, 'collectOutput', true);
fclose(fid);
data = cell2mat(C);
... the rest of your code
end

1 件のコメント

Isaac Brambley
Isaac Brambley 2019 年 2 月 6 日
I had just started looking at natsortfiles as you answered, thank you so much.

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Import and Analysis についてさらに検索

製品

質問済み:

2019 年 2 月 6 日

編集済み:

2021 年 4 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by