Loading a mat file consisting a variable

1 次查看(过去 30 天)
I have a function in which the value of variable b comes from another function. I have mat files saved named des1,des2,des3,des4..... 1,2,3,4... correspond the values of b. I want des(b).mat to be loaded. what could be the method of doing it?

回答(2 个)

Image Analyst
Image Analyst 2012-12-2
Please see the FAQ for some code examples: http://matlab.wikia.com/wiki/FAQ#How_can_I_process_a_sequence_of_files.3F The first example does what you want, though I left out some robustness for the sake of simplicity. To be robust, you'd use exist() to check that the file actually exists before reading it. Or you could just check to make sure that you have a list of only what you know exists. Thus you'd adapt the FAQ like this:
myFolder = 'C:\Documents and Settings\yourUserName\My Documents';
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, 'des*.mat');
matFiles = dir(filePattern);
for k = 1 : length(matFiles)
baseFileName = matFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
storedStructure = load(fullFileName);
b = storedStructure.b;
% Now do something with b - whatever you want.
end
This is a fairly robust way of processing your files, and it could eliminate some errors, like you're looping over des1 through des500, but for some weird reason, des348.mat and des412.mat don't exist, which would generate an error if you tried to create the filenames systematically with sprintf() inside the loop and didn't check first with exist() before calling load().

Azzi Abdelmalek
Azzi Abdelmalek 2012-12-2
编辑:Azzi Abdelmalek 2012-12-2
for k=1:4
data=load(sprintf('des%d',k))
end
data is a struct variable, if file des1 contains one variable b, to get b:
b=data.b

类别

Help CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by