How do i fix this 'not enough input arguments' error

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 comentarios

What value for n do you use when you call "fibonacci" ?
I hope you do not simply type
fibonacci(n)
without specifying n, do you ?
Umar
Umar el 7 de Sept. de 2024
Editada: Umar el 7 de Sept. de 2024

Hi @Edward,

Here is the corrected and complete MATLAB function for generating the Fibonacci sequence:

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 ~isnumeric(n) || n <= 0 || floor(n) ~= n
        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

Explanation of Changes

Input Validation: The input validation check now ensures n is not only a positive integer but also checks that it is a whole number using floor(n) ~= n.

Return Values: The function handles the base cases correctly for `n = 1` and `n = 2.

Vector Initialization: The vector fib is initialized to hold n elements, which is important for proper indexing.

Fibonacci Calculation: The loop correctly calculates Fibonacci numbers starting from the third term.

To test the function, you can use the following sample code:

% Test the Fibonacci function
n = 10; % Specify the number of Fibonacci numbers to generate
fib_sequence = fibonacci(n);
disp(['The first ', num2str(n), ' Fibonacci numbers are:']);
disp(fib_sequence);

Please see attached.

Please bear in mind that for large values of n, this iterative method is efficient. However, if you need to compute Fibonacci numbers for very large n,consider using matrix exponentiation or Binet's formula for more efficiency. However, according to John D’Errico’s comments mentioned below, he brought up a good point, While Binet's formula provides a quick way to calculate Fibonacci numbers, it suffers from precision issues in double precision arithmetic, especially for ( n > 70 ). This is due to the inherent limitations of representing large integers in MATLAB.

Always remember to specify a positive integer when calling the function, as highlighted by the comment from @Torsten. For example, calling fibonacci(5) will yield the first five Fibonacci numbers.If further issues arise, consider checking for any MATLAB-specific syntax errors or environmental issues.

Hope this should help resolve your problem. Please let me know if you have any further questions.

Um no! You gave some incorrect advice there.
While Binet's formula does works in a sense, that it gives a correct value (after rounding) if you used infinitely many digits of precision, it will fail when used in double precision for enything even reasonably large.
f100 = fibonacci(sym(100))
f100 = 
354224848179261915075
vpa(log2(f100))
ans = 
68.263227315618048999943866975115
And that number has more than 2^52 bits. It cannot be represented as a double exactly.
The Binet formula is:
r5 = sqrt(5);
Binet = @(n) (((1 + r5)/2).^n - ((1-r5)/2).^n)/r5;
And after rounding, it does always produce the correct result, but only as far as double precision arithmetic applies. And the upper limit for that is 2^53-1. For example, we see:
round(Binet(0:10))
ans = 1x11
0 1 1 2 3 5 8 13 21 34 55
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
fibonacci(sym(0:10))
ans = 
So what do we get when we apply Binet to larger numbers?
num2str(round(Binet(100)),55)
ans = '354224848179263111168'
It fails, and does so miserably. The last 7 digits were incorrect. The point is, you can try to use the Binet formula (implemented in double precision), only as far out as nmax, where nmax can be found as:
syms N real
vpasolve(log2(Binet(N)) == 53,50)
ans = 
78.014540730050042691322847737114
But even that limit is still too high, since there will be some subtractive cancellation issues in the Binet formula, that will preclude getting the correct answer above n==70, when using doubles.
Testing that claim, we find
fibonacci(sym((70:73)'))
ans = 
num2str(round(Binet((70:73)')),55)
ans = 4x15 char array
'190392490709135' '308061521170130' '498454011879265' '806515533049395'
As you can see, round(Binet(70)) is correct down to the units digit, but incorrect for 71 and beyond.
Similarly, matrix exponentiation will also fail miserably around the same point. You CANNOT use doubles to exactly represent integers larger than 2^53-1.
Umar
Umar el 7 de Sept. de 2024
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
Umar el 7 de Sept. de 2024

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.

Iniciar sesión para comentar.

Respuestas (1)

Jatin
Jatin el 10 de Sept. de 2024
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!

Etiquetas

Preguntada:

el 6 de Sept. de 2024

Respondida:

el 10 de Sept. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by