How to change a variable in a string

11 ビュー (過去 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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by