0

I am attempting to create a function for the Fibonacci numbers using a for loop. My code is as follows:

function fib = fibGenerator(N) 
fib(1) = 0;
fib(2) = 1;
for i = 3:N
   fib(i) = fib(i-1)+fib(i-2);
end

The following error message is displayed: Variable fib must be of data type uint32. It is currently of type double. Check where the variable is assigned a value.

I'm unsure of how to correct this.

Update

function fib = fibGenerator(N) 
fibGenerator(1) = uint32(0);
fibGenerator(2) = uint32(1);
for i = 3:N
  fibGenerator(i) = fibGenerator(i-1)+fibGenerator(i-2);
end

1 Answers1

1

You have to cast when you initially create fib: fib(1) = uint32(0);

Here is an example demonstrating this. When creating x you decide the type. Even if later assignments are double or of other types, it will keep its type.

>> x=uint32(1)
x =
  uint32
   1
>> x(2)=double(2)
x =
  1×2 uint32 row vector
   1   2
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • Thanks for the suggestion - I would not have thought of this! I made the adjustment, but I am now getting the error message 'Output argument "fib" (and maybe others) not assigned during call to "fibGenerator" '. – JulianAngussmith Feb 23 '20 at 08:28
  • You changed the name of the variable from `fib` to `fibGenerator`. Revert that change and it will work. – Daniel Feb 23 '20 at 08:35
  • That's what I thought, but the following error message is displayed 'Variable fib must be of size [1 1]. It is currently of size [1 5]. Check where the variable is assigned a value.' – JulianAngussmith Feb 23 '20 at 08:38
  • That's what I thought, but the following error message is displayed 'Variable fib must be of size [1 1]. It is currently of size [1 5]. Check where the variable is assigned a value.' – JulianAngussmith Feb 23 '20 at 08:38
  • Your code generates the first n fibonacci numbers. What is your task, to generate only the n-th one? – Daniel Feb 23 '20 at 08:41
  • I believe so. I need to generate the nth term in the sequence and assign this value to the variable 'fib' – JulianAngussmith Feb 23 '20 at 08:46
  • That is telling you what's wrong. I guess there must be also an assignment telling you what to do? A `fib=fib(end)` at the end of your function should fix it, returning only the last one. – Daniel Feb 23 '20 at 08:48
  • Yes, it has. Thank you a lot for your patience! – JulianAngussmith Feb 23 '20 at 08:51