How do I call a function after I ask for the input?
Ältere Kommentare anzeigen
So I am asking for the input N, where N is the number of terms in a fibonacci sequence the user would like to generate. I wrote a fibonnaci.m function as follows:
function f = Fibonacci(N)
%Input: The number of the terms of the fibonacci sequence you would like
%to generate.
%Output: The first "n" terms of the fibonacci sequence.
f=zeros(N,1); %Empty matrix: nx1
f(1) = 1; %Base cases for fibonacci sequence
f(2) = 1;
for i=3:N
f(i) = f(i-1) + f(i-2); %Recursive definition of fibonacci
%sequence
end
Then, I tried to write a script called FibonacciAsk.m:
N = input('How many terms of the fibonacci sequence would you like to generate:');
Fibonacci(N);
I input a value like 4. But nothing returns in the command window. Any advice?
Antworten (2)
dpb
am 9 Sep. 2014
The trailing semicolon on the line calling your function caused Matlab to not echo the result to the command line...
Fibonacci(N);
Try
Fibonacci(N)
instead, or
FN=Fibonacci(N);
disp(FN)
to return the values to a variable.
1 Kommentar
Andrew You
am 9 Sep. 2014
John D'Errico
am 9 Sep. 2014
Bearbeitet: John D'Errico
am 10 Sep. 2014
When you terminate a line with a semi-colon, it tells MATLAB NOT to dump the results of a computation to the command window.
So here you called it as...
Fibonacci(N);
So what happened was MATLAB did the computation, tried to return a variable to you. But you provided no output arguments. AND you terminated the line with a semi-colon. So the obvious conclusion for MATLAB was that you were not interested in the result. It was dumped into the bit bucket.
At first in MATLAB, we write lines of code that have no semi-colons, so all lines dump a mess of stuff to the command window. So then we learn to terminate all lines with a semi-colon, preventing that mess of output. But the answer is to recognize when it is necessary and appropriate, when you want to see something and when not.
Kategorien
Mehr zu Function Creation finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!