0

I'm facing an issue with this simple Fibonacci number generator program:

function f = fibonr(n)
f(1) = 1; 
f(2) = 1;
    for i = 3:n
    f(i) = f(i-1) + f(i-2);
    end

end

If I want to display only the n-th number of the sequence, what adjustments should I make?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
james42
  • 307
  • 5
  • 16
  • 2
    Once the for-loop is completed (after n iterations) the nth number will be the last one stored in `f` right? You can then display `f(end)` after the `end` statement of the loop. Is it what you mean? – Benoit_11 Oct 05 '15 at 19:23
  • I did as you' ve said, but in this case I get two outputs: the first one with the last number stored, and the answer of the program with the whole vector of numbers – james42 Oct 05 '15 at 19:29

2 Answers2

2
function f = fibonr(n)
f = zeros(n,1); %//initialise the output array
f(1,1) = 1;
f(2,1) = 1;
for ii = 3:n
    f(ii,1) = f(ii-1,1) + f(ii-2,1);
end
%//create a string with text and variables
str = sprintf('The %d th number in the Fibonacci sequence is %d',n,f(ii,1));
disp(str) %//display your output.
end

first up: don't use i as a variable. Secondly, I switched to using column vectors, since MATLAB processes them faster, as well as I initialised the array, which is way faster (hence the shiny orange wiggles below your f(i)= line).

Call your function:

output = fibonr(10);
The 10 th number in the Fibonacci sequence is 55

If you use e.g. n=20 and still want the 10th argument just call output(10)

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
0

if you want the specified output right away you can use nargin. This code will give you all of the sequence if you call fibonr(n), or you can specify a vector to get the fibonacy numbers at said positions. If you are interested in both, your specified output and all the numbers, you can call the function with: [output, fibnumbers] = fibonr(n,v);

function [output,f] = fibonr(n,v)
f(1) = 1; 
f(2) = 1;
    for i = 3:n
    f(i) = f(i-1) + f(i-2);
    end

 if nargin() > 1
     output = f(v);
 else
     output = f;
end
Dennis Klopfer
  • 759
  • 4
  • 17