필터 지우기
필터 지우기

How do I call a function after I ask for the input?

조회 수: 1 (최근 30일)
Andrew You
Andrew You 2014년 9월 9일
편집: John D'Errico 2014년 9월 10일
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?

답변 (2개)

dpb
dpb 2014년 9월 9일
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.

John D'Errico
John D'Errico 2014년 9월 9일
편집: John D'Errico 2014년 9월 10일
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.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by