I can't use the output from my function

11 visualizzazioni (ultimi 30 giorni)
Here is a simple function I created to generate the nth Fibonacci number:
function []=Fib(n)
sn(1) = 1;
sn(2) = 1;
for i=3:n
sn(i)=sn(i-1)+sn(i-2);
end
sn(n)
end
So Fib(5) give me ans = 5 However, when I try to execute "Fib(5)*2" I get the message "Too many output arguments" This is really really basic stuff, but I have no idea how to work Matlab and would appreciate some help. Thanks

Risposta accettata

Stephen23
Stephen23 il 25 Gen 2016
Modificato: Stephen23 il 25 Gen 2016
Change the function definition to specify sn as an output:
function sn = Fib(n)
The line you wrote
sn(n)
does not output anything, it just displays a value in the command window. You can read in the documentation about how to define functions properly:
Bonus Tips
Learning MATLAB means learning lots of new things. A good place to start are by doing these tutorials:
and reading this advice for beginners:
  1 Commento
Joshua Hall
Joshua Hall il 25 Gen 2016
Thanks! It's now giving me all of the Fibonacci numbers rather than just the nth one, but I think I can fix it

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Get Started with MATLAB in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by