Dynamically rename existing structure arrays
Show older comments
Hi all,
I have several .mat files, each of them containing one structure array named "data" (named exactly the same in each .mat file), like the following
data =
hdr: [1x1 struct]
label: {306x1 cell}
time: {1x25 cell}
and my ultimate aim is to merge all those "data" arrays using a function (ft_appendata) of the Fieldtrip toolbox.
In order to do that, I need to have all those "data" arrays named differently from each other.
What I want to do is to create a loop which loads the files and dynamically renames the "data" arrays.
For example, having the files...
1_myfile_1.mat
1_myfile_2.mat
2_myfile_1.mat
2_myfile_2.mat etc...
...I want to load all the files and rename each "data" variable contained in each .mat file...
for s=1:2
for r=1:2
load([num2str(s),'_myfile_',num2str(r),'.mat'])
%here piece of code, which I don't know, needed for renaming the variable
end
end
...in order to get something like...
1_data_1 =
hdr: [1x1 struct]
label: {306x1 cell}
time: {1x25 cell}
1_data_2 =
hdr: [1x1 struct]
label: {306x1 cell}
time: {1x19 cell}
2_data_1 =
hdr: [1x1 struct]
label: {306x1 cell}
time: {1x16 cell}
etc.
I tried to use the eval() function but, as far as I have understood, it generates from scratch a new variable dynamically changing name at each iteration, while I need to simply rename an already existing structure array.
Thank you in advance for your kind help, Chiara
Accepted Answer
More Answers (2)
Michael Haderlein
on 28 Jul 2014
It's not necessary to rename your variables. I suppose you want a matrix with all the structure, right? Then, the following should work:
alldata=struct('hdr',cell(2),'label',[],'time',[]);
for s=1:2
for r=1:2
load([num2str(s),'_myfile_',num2str(r),'.mat'])
alldata(s,r)=data;
end
end
Just concatenate them as you read the files...
alldat=[]; % an empty holder
for s=1:2
for r=1:2
alldat=[alldat;load([num2str(s),'_myfile_',num2str(r),'.mat'])]; % concatenate each
end
end
ADDENDUM
If don't have a huge number this shouldn't be too bad altho it's generally not "best practice" to dynamically grow arrays. Not sure w/ structures what happens if create an empty structure array vis a vis concatenation; never tested it.
Categories
Find more on Matrix Indexing 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!