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

I had just started looking at natsortfiles as you answered, thank you so much.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data 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