Azzera filtri
Azzera filtri

saving in loop-- using eval or num2str?

17 visualizzazioni (ultimi 30 giorni)
Nina
Nina il 20 Lug 2012
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

Risposta accettata

Jan
Jan il 20 Lug 2012
Modificato: Jan il 20 Lug 2012
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 Commento
Nina
Nina il 7 Ago 2012
Yes! The sprintf function was the key to making this work. Thank you.

Accedi per commentare.

Più risposte (1)

James Tursa
James Tursa il 20 Lug 2012
save(filename, ['events_' num2str(yr)]);

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by