How to save output(.mat) file for all generated values instead of last values ?

조회 수: 3(최근 30일)
I am trying to run the optimization using the following code. The code runs fine and evey thing is working.
But I wanted to saved all the values of x obtained in all iterations, but only the last value is saved in .mat file (screenshot attached).
I tried using the save after the function ends, but that results in error. Please help me...
-----------------------------------------------------------------------------------------------
function y = opt(x)
Kp = x(1);
Ki = x(2);
disp(x);
save('pqfile.mat','x')
options = simset ('SrcWorkspace','current','DstWorkspace','current');
out = sim('try_fit',[],options);
y=j;
end
-----------------------------------------------------------------------------------------------
Thanks & Regards
Sanjeev Gupta
  댓글 수: 3
Mathieu NOE
Mathieu NOE 2021년 3월 10일
hello again
so to me x is the ouput of another function ? (from the Optimization Toolbox )
in that case you can have a code that concatenates the previous x pair with a new one like :
% init
X = [];
% maybe here for or while loop
% your Optimization Toolbox funtion here
x = stuff(...); %
y = opt(x); % where is y used - in the above function ?
X = [X; x(:)]; % concatenation of previous and current x values
% end of for / while loop
does it make sense to you ?

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

답변(1개)

Walter Roberson
Walter Roberson 2021년 3월 9일
function y = opt(x)
Kp = x(1);
Ki = x(2);
disp(x);
filename = 'pqfile.mat';
if ~exist(filename)
pqsave.x = [];
else
pq = load(filename, 'x');
pqsave.x = pq.x;
end
pqsave.x(end+1) = x;
save(filename, '-struct', pqsave);
options = simset ('SrcWorkspace','current','DstWorkspace','current');
out = sim('try_fit',[],options);
y=j;
end
This is not efficient. More efficient would be
function y = opt(x)
persistent pqsave
if isempty(pqsave); pqsave.x = []; end
Kp = x(1);
Ki = x(2);
disp(x);
filename = 'pqfile.mat';
pqsave.x(end+1) = x;
save(filename, '-struct', pqsave);
options = simset ('SrcWorkspace','current','DstWorkspace','current');
out = sim('try_fit',[],options);
y=j;
end
but even more efficient would be
function [y, saved_x] = opt(x)
persistent pqsave
if isempty(pqsave); pqsave.x = []; end
if nargout > 1
y = [];
saved_x = pqsave.x;
return
end
Kp = x(1);
Ki = x(2);
disp(x);
pqsave.x(end+1) = x;
options = simset ('SrcWorkspace','current','DstWorkspace','current');
out = sim('try_fit',[],options);
y=j;
end
To use this, call opt as usual with a single output. Then after that is all finished, call it once with two outputs (no inputs needed). Ignore the first output, and the record of the x values will be in the second output. This avoids doing all the save() operations.

범주

Find more on Manual Performance Optimization in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by