How to change a variable in a string

5 次查看(过去 30 天)
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