필터 지우기
필터 지우기

saving in loop-- using eval or num2str?

조회 수: 17 (최근 30일)
Nina
Nina 2012년 7월 20일
I am creating 64 3D arrays out of one large array. On each iteration of the loop, I want to save only the file created in that loop. All of the code works great except the line with the save function. Since my array name is based off the eval function, I don't know how to refer to it in the save function. Also tried just using num2str function with the year (commented in code) with no luck. Is this possible to do and how is it done? Your help greatly appreciated!!
%separate event_int_all 3D array into 64 3D arrays based on year
ct=1;
for k=1:64;
yr=1947+k;
eval(['events_',num2str(yr) '=NaN(66,6,60);']);
for j=1:size(event_int_all,3);
for i=1:size(event_int_all,1);
if i==1 && j~=1 && event_int_all(i,1,j-1)~=k;
ct=1;
end%if1
if isnan(event_int_all(i,:,j))==1;
continue
elseif i==1 && j~=1 && event_int_all(i,1,j-1)~=k;
ct=1;
elseif event_int_all(i,1,j)==k; eval(['events_',num2str(yr),'(i,:,ct)','=event_int_all(i,:,j);']);
else
continue
end%if2
end%fori
ct=ct+1;
end%forj
filename=['year_' num2str(yr) '.mat'];
save('filename', eval(['events_' num2str(yr)])); %!! doesn't work
%also tried save('filename','events_' num2str(yr)) doesn't work
end%fork

채택된 답변

Jan
Jan 2012년 7월 20일
편집: Jan 2012년 7월 20일
You can omit the evil EVAL. As you see it causes problems, as it ever does.
% eval(['events_',num2str(yr) '=NaN(66,6,60);']);
data = NaN(66,6,60);
% eval(['events_',num2str(yr),'(i,:,ct)','=event_int_all(i,:,j);']);
data(i,:,ct) = event_int_all(i,:,j);
% save('filename', eval(['events_' num2str(yr)]))
S = struct(sprintf('events_%d', y), data);
save('filename', 'S', '-struct');
EVAL reduces the efficiency of the program, the maintainability of the code, the life-time of the programmer and the band-width of the forum servers.
  댓글 수: 1
Nina
Nina 2012년 8월 7일
Yes! The sprintf function was the key to making this work. Thank you.

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

추가 답변 (1개)

James Tursa
James Tursa 2012년 7월 20일
save(filename, ['events_' num2str(yr)]);

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by