How can I change the name of a variable and assign to it the name of a mat file?
12 views (last 30 days)
Show older comments
I am loading a mat file and making some changes to it and then I want to save the new matrix by using the name of the mat file. The code I am using is:
load LRWW.mat
for i=2002:-1:1141
LRWW(i)=[];
end
for i=1:140
LRWW(1)=[];
end
for i=2:51
LRWW(i)=[];
end
matname = ['D:\MATLAB\\LRWW.mat'];
save(matname,'LRWW');
So far so good. My problem is that I need to do this for many mat files. Every time I have to change the name (LRWW in this example) manually. Is there a way to automate the procedure?
Thank you very much
Accepted Answer
Jan
on 18 Feb 2013
Edited: Jan
on 18 Feb 2013
YourFolder = 'D:\MATLAB\';
List = dir(fullfile(YourFolder, '*.mat'));
for iList = 1:numel(List)
aFile = fullfile(YourFolder, List{iList}.name);
FileData = load(aFile);
Field = fieldnames(FileData);
FileData.(Field{1})[1:140, 142:191, 1141:2002] = [];
save(aFile, '-struct', 'Data');
end
More Answers (1)
Azzi Abdelmalek
on 18 Feb 2013
Edited: Azzi Abdelmalek
on 18 Feb 2013
for k=1:10
filename{k}=sprintf('file%d',k)
end
Will generate file1, file2,...,file10
3 Comments
Image Analyst
on 18 Feb 2013
If the names of your variables that are stored in your old mat file are unknown and change from file to file, then you need to use dynamic fieldnames like Jan shows you.
See Also
Categories
Find more on Database Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!