How to use the 'Open' command to open any .mat file found in a folder without hard coding the file name e.g. '%s/*.mat'?

1 次查看(过去 30 天)
Hello Community,
I am struggling to get a piece of code to work. I have asked another question here , but if I get this following part right, I think it will help answer the first question. I have been fortunate enough to find Image Analyst's answer on recursive searching through folders, so I am using that as the base code to search folders, but I have an issue with the 'open' command. In a batch, I am trying to open the file with the .mat extension that is found in a childfolder, and then for a structure to be created from the workspace variables, as follows:
if numberOfWorkspaces >= 1
% Go through all those files and exctract the correct variables.
for f = 1 : numberOfWorkspaces
st = open(dir('*.mat')); % <<<<This is the part causing the error>>>>
offset = 1;
xlswrite('locations.xls', [st.newfolder st.X1 st.X2 st.Y1 st.Y2], 1, sprintf('A%d',offset));
offset = offset + 1;
fullFileName = fullfile(thisFolder, baseFileNames(f).name);
fprintf(' Processing MAT file %s\n', fullFileName);
end
else
fprintf(' Folder %s has no MAT files in it.\n', thisFolder);
end
but, it throws up this error:
Error using open (line 68)
NAME must contain a single string.
Error in extVars (line 52)
st = open(dir('*.mat'));
I want the code to be able to open the .mat file that is found within each folder in the batch - so I dont want to hard code specific .mat file names.
Can you advise of a solution to this problem? Many thanks in advance.
Regards,
10B.

采纳的回答

Walter Roberson
Walter Roberson 2016-3-21
dir() returns a structure of information, one array element per file. There is a "name" field that holds the name. You will need to iterate over each of the times.
I don't think you should be using open() either. I think you should be using load()
dinfo = dir('*.mat');
for K = 1 : length(dinfo)
thismat = dinfo(K).name;
st = load(thismat);
....
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by