开发者

How to save the output values with each run in the same file in matlab

I get two different (numeric and character )output values at each run, I want to save these value in a file in order to use them in another process. I saved them in a struct of array then I saved them in (mat file) as follow:

Sim(i).No Sim(i).Nam

save('Sim', 'Sim")

I want to saved these value at each run in the same file ... the problem is in the next run I get just the values of the l开发者_如何学运维ast run.


You can use the '-append' option of SAVE to add data to a saved file. However, you need to be careful to save each run with a different name, otherwise you'll just be overwriting the save file.

Thus, you could do something like this:

for i=1:nRuns

%# create Sim

%# make variable name containing 'i'
simName = ['Sim_',num2str(i)];
saveStruct.(simName) = Sim;
%# save field 'Sim_#', where # is the value of i, to a file 'Sim'
%# in the first iteration, we cannot use append, since the file doesn't exist yet.
if i==1
save('Sim','-struct','saveStruct',simName)
else
save('Sim','-struct','saveStruct',simName,'-append')
end

%# to save memory, re-initialize saveStruct
saveStruct = struct;

end %# loop


You are trying to save-to-disk a struct array incrementally, so you need to load, appended, and re-save the array each time (something that is not recommended for very large data):

% load existing Sim.mat
if exist('Sim.mat','file')
   load('Sim')
end
% check Sim was indeed loaded and if so extend it
if exist('Sim','var') && ~isempty(Sim)
   Sim(end+1).No = No;
   Sim(end+1).Nam = Nam;
else 
   % create a new Sim (presumably the first time)
   Sim(1).No = No;
   Sim(1).Nam = Nam;
end
% save the exented Sim
save Sim Sim

The above assumes you have No and Nam defined earlier in the code. If you were running this in a loop, a better approach would be to just keep Sim in memory and save the entire struct array at the end of the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜