fprintf in an OutPutFcn

3 ビュー (過去 30 日間)
Sergio Quesada
Sergio Quesada 2018 年 6 月 13 日
コメント済み: Sergio Quesada 2018 年 6 月 13 日
Hi everybody, I'm trying to edit this output function within the command fopen and fprintf:
function stop=outfun(x,optimValues,state)
stop = false;
switch state
case 'init'
fID2=fopen(['I_vs_texp--',datestr(now,'dd_mm_yyyy_HH_MM_SS') '.txt'],'a');
case 'iter'
fprintf(fID2,'%6.2f %12.8f\r\n',{optimValues.iteration, optimValues.resnorm, x(1),x(2),x(3)});
case 'done'
fclose ('all')
end
, but something must be wrong with the name given to the new file, because it gives me the following:
Undefined function or variable 'fID2'.
Thanks !!
  2 件のコメント
Adam
Adam 2018 年 6 月 13 日
Well, you define it in one case of a switch statement and then access it in a mutually exclusive one so in the state where you define it you don't use it and in the state where you try to use it you don't define it.
Sergio Quesada
Sergio Quesada 2018 年 6 月 13 日
編集済み: Sergio Quesada 2018 年 6 月 13 日
But if i define it on the 'init' statement, it will create one different file after each iterarion...

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2018 年 6 月 13 日
編集済み: Stephen23 2018 年 6 月 13 日
Add this line at the start of the function:
persistent FiD2
Each time the function is called it has no recollection of what happened last time it was called, unless you explicitly give it some way to remember: that is exactly what persistent is for, so that the next time the function is called, it will remember that variable. Note that in general it is a bad practice to call fclose('all') like that, except perhaps from the command line.
function stop=outfun(x,optimValues,state)
persistent fid
stop = false;
switch state
case 'init'
tmp = datestr(now,'dd_mm_yyyy_HH_MM_SS');
tmp = sprintf('I_vs_texp--%s.txt',tmp);
fid = fopen(tmp,'a');
case 'iter'
fprintf(fid,'%6.2f %12.8f\r\n',{optimValues.iteration, optimValues.resnorm, x(1),x(2),x(3)});
case 'done'
fclose(fid)
end
  6 件のコメント
Adam
Adam 2018 年 6 月 13 日
A is not a cell array in that case though, it is a numeric array.
Sergio Quesada
Sergio Quesada 2018 年 6 月 13 日
oh, ok. Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by