Combine numerous arrays with similar names

4 ビュー (過去 30 日間)
Mark Pleasants
Mark Pleasants 2016 年 6 月 10 日
コメント済み: Jos (10584) 2016 年 6 月 10 日
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!

採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 6 月 10 日
編集済み: Azzi Abdelmalek 2016 年 6 月 10 日
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 件のコメント
Jos (10584)
Jos (10584) 2016 年 6 月 10 日
the first solution is the way to go. Ignore the other ones!

サインインしてコメントする。

その他の回答 (2 件)

Jos (10584)
Jos (10584) 2016 年 6 月 10 日
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 件のコメント
Mark Pleasants
Mark Pleasants 2016 年 6 月 10 日
I have a bunch of .dat files containing the met data. I simply used crn_1=importdata('filename.dat',',');
Jos (10584)
Jos (10584) 2016 年 6 月 10 日
import them like this:
filenames = {'filename1.dat','filename2.dat',...}
for k=1:numel(filenames)
cm{k} = importdata(filenames{k}) ;
end

サインインしてコメントする。


Steven Lord
Steven Lord 2016 年 6 月 10 日
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.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by