0

In the code shown, I want to save one parameter (fval) per iteration in one variable, but not sure how to do it. Can someone advise?

clear;
close all;
clc;

for i = 0 : 100
    ii = i * 0.01;
    options = optimset('Display','iter-detailed', ...
                       'Algorithm','interior point', ...
                       'Diagnostics','on');

    options.TolCon = 0;
    options.TolFun = 0;
    [X,faval,exitfag,output,lambda,grad,hessian]=fmincon(@myfun9,0,[],[],[],[],ii,1,@mycon,options);

end;   
bushmills
  • 673
  • 5
  • 17
  • do you want to save the return value `fval` in a separate variable each iteration? So you will have 100 variables after the loop? – bushmills Jan 09 '17 at 06:40
  • How about using an array, e.g. define `fval = [];` before the loop and then at the end of each iteration do `fval = [fval; faval];` to store the new values. Note, this will only work when `faval` has same dimensions for all iterations. – hmofrad Jan 09 '17 at 08:27
  • @hmofrad That's not recommended. Read why: https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html – Sardar Usama Jan 09 '17 at 09:08
  • @Sardar_Usama I see your point! – hmofrad Jan 09 '17 at 16:08
  • Note that you can take all the `options...` setting out of the loop – EBH Jan 09 '17 at 19:06

1 Answers1

0

If you want to create 101 separate variables for storing each value, that's not recommended. Pre-allocate an array for fval for storing the values of faval in each iteration as shown below:

fval = zeros(101,1);      %Pre-allocating memory for fval
for k = 0 : 100
    ii = k * 0.01;
    options = optimset('Display','iter-detailed', ...
                       'Algorithm','interior point', ...
                       'Diagnostics','on');

    options.TolCon = 0;
    options.TolFun = 0;
    [X,faval,exitfag,output,lambda,grad,hessian]=fmincon(@myfun9,0,[],[],[],[],ii,1, ...
                       @mycon,options);

    %Storing value of faval in fval(k+1). Note that indexing starts from 1 in MATLAB
    fval(k+1) = faval;    
end

By the way, it seems from your code that you're not interested in the values of all other parameters i.e. X,exitfag,output,lambda,grad,hessi, because these parameters will be overwritten in each iteration. If you're not interested in these values. You can skip storing them using tilde (~). So you might also want to use the following instead:

[~,faval]=fmincon(@myfun9,0,[],[],[],[],ii,1, @mycon,options);
% exitfag, output, lambda, grad, hessi are skipped automatically as per fmincon doc

Suggested reading:
1. Dynamic Variables
2. Preallocation
3. Why does MATLAB have 1 based indexing?
4. Tilde as an Argument Placeholder

Community
  • 1
  • 1
Sardar Usama
  • 19,536
  • 9
  • 36
  • 58