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

4 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 6 Feb 2019
Edited: Stephen23 on 26 Apr 2021
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

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!