# Create arrays of observations

조회 수: 1(최근 30일)
CARLOTTA DENTICO 2021년 8월 4일
댓글: Rik 2021년 8월 4일
Hello everybody,
Probably it is a very silly question but I am struggling on it..
I have a series of observations saved as 'pt_mean_lev1_1' up to 'pt_mean_lev1_348' (see picture below) and I want to make an array of them being a = 1x348. How can I do that?
Thank you very much! ##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
CARLOTTA DENTICO 2021년 8월 4일
fram = (lon>=0 & lon<=20 & lat>=76 & lat<=80);
for k = 1:348
eval(['pt_lev1_' ,num2str(k), ' = reshape(pt_lev1(:,:,',num2str(k),'),[],1);']);
eval(['pt_mean_lev1_', num2str(k), '= mean(pt_lev1_',num2str(k),'(fram,:),1,''omitnan'');']);
end

댓글을 달려면 로그인하십시오.

### 채택된 답변

Sulaymon Eshkabilov 2021년 8월 4일
Here is one of the viable solutions with dynamically naming variables and attaining their values from the workspace.
a = [];
for ii=1:348
Var = strcat('pt_mean_lev1_', num2str(ii));
a=[a, eval(Var)];
end
##### 댓글 수: 3표시숨기기 이전 댓글 수: 2
Rik 2021년 8월 4일
In the screenshot you can see the number of elements of each element. Growing the array dynamically like this (instead of pre-allocating) results in terrible performance. I would also refrain from teaching people to use eval as the solution. As already evidenced in this thread, that is a source of trouble.
k=500000;N=100;%N=348 takes mare than the 55 second limit
tic
a = [];
for ii=1:N
a=[a, rand(k,1)];
end
toc
Elapsed time is 15.427005 seconds.
tic
a = zeros(k,N);
for ii=1:N
a(:,ii)=rand(k,1);
end
toc
Elapsed time is 0.513869 seconds.

댓글을 달려면 로그인하십시오.

### 추가 답변(2개)

CARLOTTA DENTICO 2021년 8월 4일
Do you mean here?
Basically, these are monthly mean of temperature spatially averaged over a specific area of the world, in every months for 29 years (I have a total of 348 means i.e 12x29) that I have extracted from a NetCDf file..
I need these means since I need to calculate time series of winter months (from October to April) and summers months (from May to September) and calculate the mean of winters and summers over 29 years.
All that is to calculate the anomalies of a single month compared to winters in the whole period..
##### 댓글 수: 1표시숨기기 없음
Sulaymon Eshkabilov 2021년 8월 4일
I meant a separate thread and not here. Two questions in one thread that is confusing.

댓글을 달려면 로그인하십시오.

Rik 2021년 8월 4일
You should not name your variables dynamically. Why are you not storing them in an array when reading? What is wrong with the code below?
fram = (lon>=0 & lon<=20 & lat>=76 & lat<=80);
pt_lev1_=zeros(size(pt_lev1,1)*size(pt_lev1,2),348);
for k = 1:348
pt_lev1_(:,k) = reshape(pt_lev1(:,:,k),[],1);
end
pt_mean_lev1_=mean(pt_lev1_(fram,1:k),1,'omitnan')

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!