Combine numerous arrays with similar names

11 views (last 30 days)
I have imported 66 arrays containing met data into matlab. They all have same number of columns but different rows. I want to combine all these array into one master array to create a continuous dataset of my met data. All arrays have names such as crn_1, crn_2, crn_3, .... crn_65, crn_66.
I was trying to write a loop where the value of 'i' in the loop would change such that it would import the next array in the series and combine it into the master array.
Something like
crn_all=[];
for i = 1:66
crn=crn_i;
crn_all=[crn_all;crn];
end
Where the value of i would change to represent the next array name instead of the position within the array. Obviously the above code does not work. Are there any ways to accomplish this?
Thanks!

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 10 Jun 2016
Edited: Azzi Abdelmalek on 10 Jun 2016
The first solution is to change your code, by storing all your data in one array or one cell array. If i't's not possible for reason I ignore, then you can use eval function, which is generally not recommended.
crn_1=rand(3,1)
crn_2=rand(3,1)
crn_3=rand(3,1)
out=[];
for k=1:3
eval(sprintf('out=[out;crn_%d]',k))
end
Another way to do it:
crn_1=rand(3,1)
crn_2=rand(3,1)
crn_3=rand(3,1)
out=[];
for k=1:3
s=sprintf('crn_%d',k)
save('file',s)
a=load('file')
out=[out;a.(s)]
end
  1 Comment
Jos (10584)
Jos (10584) on 10 Jun 2016
the first solution is the way to go. Ignore the other ones!

Sign in to comment.

More Answers (2)

Jos (10584)
Jos (10584) on 10 Jun 2016
You should be able to avoid this problem by loading them into array of structs or cells, rather than in variables with variable names...
It is the contents of a variable that is supposed to be flexible, not its name!
How did you import these variables?
  2 Comments
Mark Pleasants
Mark Pleasants on 10 Jun 2016
I have a bunch of .dat files containing the met data. I simply used crn_1=importdata('filename.dat',',');
Jos (10584)
Jos (10584) on 10 Jun 2016
import them like this:
filenames = {'filename1.dat','filename2.dat',...}
for k=1:numel(filenames)
cm{k} = importdata(filenames{k}) ;
end

Sign in to comment.


Steven Lord
Steven Lord on 10 Jun 2016
Is it possible to do that? Yes.
Is it recommended to create variables named like that? NO.
See question 1 in the Programming section of the FAQ for a description of techniques you can use to resolve this situation and a discussion of why you should avoid this situation in the future.

Categories

Find more on Cell Arrays 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!