How to change a variable in a string
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (2)
Rik
el 24 de Abr. de 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
0 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!