Using print command recursively.

I have a code with a for loop. In each iteration I need to print the results in a file. How can I use the printed results of previous iteration in the current iteration. Suppose that for the first iteration I have:
fprintf('f(%d) is %fI(x>f)',t,a(t),b(t));
which gives me:
f(1) is 0.6931I(x<3.5000)
Now for the second iteration my f(2) is f(1)+sth. Instead of writing
fprintf('f(%d) is %fI(x>%f)+%fI(x>%f)',t,a(t-1),b(t-1),a(t),b(t));
can I save my previous print as a variable called 'pre_f' and call it in my new fprintf command? for example:
fprintf('f(%d) is %?+%fI(x>%f)',t,pre_f,a(t),b(t));

답변 (1개)

Fangjun Jiang
Fangjun Jiang 2011년 11월 2일

1 개 추천

use sprintf() to print to a variable of string.
pre_f=sprintf('f(%d) is %fI(x>f)',t,a(t),b(t));
use %s to print a string.
NewString=sprintf('Previous string is : %s',pre_f);
What is the purpose of your code?

댓글 수: 2

Walter Roberson
Walter Roberson 2011년 11월 2일
And to get the string to appear on the output,
fprintf('%s\n', pre_f);
or
fprintf('%s\n', NewString)
as appropriate.
Soudeh
Soudeh 2011년 11월 3일
Really thanks Fangjun! It worked for me!
It is a Machine Learning code. In each iteration the results should be printed. Moreover, in each iteration the result is previous result + new part. So imagine for the iteration 20 if you hadn't helped me I must have written all the previous results from 19 iterations.

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2011년 11월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by