How can I change the name of a variable and assign to it the name of a mat file?

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

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)

for k=1:10
filename{k}=sprintf('file%d',k)
end
Will generate file1, file2,...,file10

3 Comments

Thanks for your answer but that is not what I was looking for. What I am asking is how can I use the name of the mat file (here LRWW) in the rest of the commands without having to write it manually. Now, whenever I am loading a new mat file I am changing the name of the variable 6 times in the program.
%first change
load LRWW.mat
%second change
for i=2002:-1:1141
LRWW(i)=[];
end
%third change
for i=1:140
LRWW(1)=[]; end
%fourth change
for i=2:51
LRWW(i)=[];
end
%fifth change
matname = ['D:\MATLAB\\LRWW.mat'];
%sixth change
save(matname,'LRWW');
I hope now my question makes more sense. I am sorry I wasn't clear enough the first time.
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.

Sign in to comment.

Categories

Asked:

on 18 Feb 2013

Community Treasure Hunt

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

Start Hunting!