Combine numerous arrays with similar names

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!

 Réponse acceptée

Azzi Abdelmalek
Azzi Abdelmalek le 10 Juin 2016
Modifié(e) : Azzi Abdelmalek le 10 Juin 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 commentaire

Jos (10584)
Jos (10584) le 10 Juin 2016
the first solution is the way to go. Ignore the other ones!

Connectez-vous pour commenter.

Plus de réponses (2)

Jos (10584)
Jos (10584) le 10 Juin 2016

1 vote

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 commentaires

Mark Pleasants
Mark Pleasants le 10 Juin 2016
I have a bunch of .dat files containing the met data. I simply used crn_1=importdata('filename.dat',',');
import them like this:
filenames = {'filename1.dat','filename2.dat',...}
for k=1:numel(filenames)
cm{k} = importdata(filenames{k}) ;
end

Connectez-vous pour commenter.

Steven Lord
Steven Lord le 10 Juin 2016

1 vote

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.

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by