How do i fix this 'not enough input arguments' error
2 次查看(过去 30 天)
显示 更早的评论
Im trying to create a fibonacci sequence and have mostlyeverything figured out but i can't seem to fix this.
function fib = fibonacci(n)
% This function gives the first n numbers in the Fibonacci sequence
% Input: n - the number of Fibonacci numbers to generate
% Output: fib - a row vector containing the first n Fibonacci numbers
if n<=0
error('Input must be a positive integer');
elseif n == 1
fib = 0;
return;
elseif n == 2
fib = [0, 1];
return;
end
% Initialize the first two Fibonacci numbers
fib = zeros(1, n);
fib(1) = 0;
fib(2) = 1;
% Compute the Fibonacci sequence
for i = 3:n
fib(i) = fib(i-1) + fib(i-2);
end
end
5 个评论
Umar
2024-9-7
Hi @John D'Errico,
Thanks for sharing your knowledge. Your insights are indeed valuable in emphasizing the importance of computational precision and the limitations inherent in numerical methods for large indices in Fibonacci calculations.
Umar
2024-9-7
Hi @John D’Errico,
What are your thoughts about computing Fibonacci numbers using symbolic representation as shown below. Doesn’t this approach circumvent the limitations of floating-point precision, allowing for accurate calculations regardless of size:
function f = fibonacci(n) if n < 0 error('Input must be a non-negative integer.'); end f = sym(zeros(1, n + 1)); f(1) = 0; f(2) = 1; for k = 3:n + 1 f(k) = f(k - 1) + f(k - 2); end end
% Example usage: f100 = fibonacci(100); disp(f100);
Please see attached.
回答(1 个)
Jatin
2024-9-10
When you define a function within a script, MATLAB identifies the function by the file name. Therefore, executing the script is equivalent to running the command:
>> fibonacci
This is equal to calling the function without providing any input arguments. To handle this situation, you should verify the input arguments and provide a meaningful error message or notification within the function script. You can utilize the nargin variable, which holds the number of input arguments passed to the function, to display an informative message as shown below:
function fib = fibonacci(n)
% This function gives the first n numbers in the Fibonacci sequence
% Input: n - the number of Fibonacci numbers to generate
% Output: fib - a row vector containing the first n Fibonacci numbers
if nargin < 1
error('You need to pass at least one parameter to this function!');
end
if n <= 0
error('Input must be a positive integer');
elseif n == 1
fib = 0;
return;
elseif n == 2
fib = [0, 1];
return;
end
% Initialize the first two Fibonacci numbers
fib = zeros(1, n);
fib(1) = 0;
fib(2) = 1;
% Compute the Fibonacci sequence
for i = 3:n
fib(i) = fib(i-1) + fib(i-2);
end
end
Kindly go through the documentation of "nargin" for more details:
Hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Number Theory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!