フィルターのクリア

saving variables contained within a function

17 ビュー (過去 30 日間)
Kyle Stanhouse
Kyle Stanhouse 2011 年 6 月 28 日
I need to save variables that are computed inside a function (called from a header) without providing them as output parameters. I can't use 'save' because the function is called inside a loop and it overwrites (the variables computed change over time). Is the only way to accomplish this through 'fprintf'?

採用された回答

Rick Rosson
Rick Rosson 2011 年 6 月 28 日
It is probably not the only way to accomplish this task, but it will certainly work.
You can use fprintf to print to a text file instead of to the command window. Please check the documentation:
doc fopen
doc fclose
doc fprintf
The code would be something like:
filename = 'data.txt';
txt = fopen(filename,'w')
...
...
for ...
...
fprintf(txt, '...\n' , ...);
...
end
...
...
fclose(txt);
...
...
HTH.
Rick

その他の回答 (2 件)

Matt Fig
Matt Fig 2011 年 6 月 28 日
Have you looked into the -append option of SAVE?
  1 件のコメント
Kyle Stanhouse
Kyle Stanhouse 2011 年 6 月 28 日
yes but as i understand i would have to create a new name for the variable each time the function is called....the help documentation for save using append has this:
Note Saving with the -append option does not append additional elements to any arrays that are already saved in the MAT-file.
so if i went this route i would have to create a new name each time right?

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


Rick Rosson
Rick Rosson 2011 年 6 月 28 日
Another approach would be to declare a persistent variable that will accumulate the results each time you call the function, and then perhaps write the results out to a MAT file the last time you call the function.
Please check the documentation:
doc persistent
The function template would be:
function y = foo(x)
persistent results
if isempty(results)
results = zeros(...);
end
...
...
end
HTH.

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by