How to change a variable in a string

조회 수: 8 (최근 30일)
Lachlan Cooley
Lachlan Cooley 2020년 4월 24일
편집: Mehmed Saad 2020년 4월 24일
Hello,
I have a function that displays the nth Fibonacci number and outputs it. Using the code below I have resulted in the displaying this information as shown further down.
function fib(n)
% Set the Fibonacci number to calculate.
% Create a row vector called containing n ones.
F = ones(1,n);
% This vector is used to store the Fibonacci
% numbers; its first element is currently F_1
% and its second element is F_2 (if n>1).
% If n>2, then use the recursive formula
% to calculate F_3, F_4, ... , F_n.
for k = 3:n
F(k) = F(k-1) + F(k-2);
status =['Fibonacci no. = ', num2str(F(k))];
disp(status);
end
results in the output
Fibonacci no.= 2
Fibonacci no.= 3
Fibonacci no.= 5
Fibonacci no.= 8
Fibonacci no.= 13
Fibonacci no.= 21
Fibonacci no.= 34
Fibonacci no.= 55
for n = 10
How would I go about producing the result below?
Fibonacci no. 3 = 2
Fibonacci no. 4 = 3
Fibonacci no. 5 = 5
Fibonacci no. 6 = 8
Fibonacci no. 7 = 13
Fibonacci no. 8 = 21
Fibonacci no. 9 = 34
Fibonacci no. 10 = 55

답변 (2개)

Rik
Rik 2020년 4월 24일
It is much cleaner to use fprintf. That way you can also much more easily insert more numbers to display:
function fib(n)
% Set the Fibonacci number to calculate.
% Create a row vector called containing n ones.
F = ones(1,n);
% This vector is used to store the Fibonacci
% numbers; its first element is currently F_1
% and its second element is F_2 (if n>1).
% If n>2, then use the recursive formula
% to calculate F_3, F_4, ... , F_n.
for k = 3:n
F(k) = F(k-1) + F(k-2);
fprintf('Fibonacci no. %d = %d\n',k,F(k));
end
end

Mehmed Saad
Mehmed Saad 2020년 4월 24일
편집: Mehmed Saad 2020년 4월 24일
status =sprintf('Fibonacci no.%d = %d',k,F(k));
disp(status);
But fprintf can do both job in 1 command i.e. format the string and print it
fprintf('Fibonacci no. % d = %d\n',k,F(k));

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by