saving in loop-- using eval or num2str?

17 次查看(过去 30 天)
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