How to change a variable in a string

9 Ansichten (letzte 30 Tage)
Lachlan Cooley
Lachlan Cooley am 24 Apr. 2020
Bearbeitet: Mehmed Saad am 24 Apr. 2020
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

Antworten (2)

Rik
Rik am 24 Apr. 2020
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 am 24 Apr. 2020
Bearbeitet: Mehmed Saad am 24 Apr. 2020
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));

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by