amir1122
amir1122

Reputation: 57

display Fibonacci sequence with disp_function in matlab

i want to result Fibonacci sequence from its formula:

1+sqrt(5)/2).^n-(1-sqrt(5)/2).^n)/sqrt(5);

by disp function,not fprintf;but i couldn't. how can write it by disp to below form: f(0)= 0 f(1)= 1 f(2)= 1 f(3)= 2

Upvotes: -4

Views: 98

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

  • First of all, you had errors in you code when calculate Fibonacci sequence, where brackets should surround 1+sqrt(5) and 1-sqrt(5)
  • Secondly, you can remove ; at the end of expression f = ..., such that it will display f in the command window

Example

n = 1:10;
f=(((1+sqrt(5))/2).^n-((1-sqrt(5))/2).^n)/sqrt(5)

such that

f =

    1.0000    1.0000    2.0000    3.0000    5.0000    8.0000   13.0000   21.0000   34.0000

or display result like below

for n = 1:10
  f=(((1+sqrt(5))/2).^n-((1-sqrt(5))/2).^n)/sqrt(5);
  disp(['F(',num2str(n-1),')=',num2str(f)]);
end

such that

F(0)=1
F(1)=1
F(2)=2
F(3)=3
F(4)=5
F(5)=8
F(6)=13
F(7)=21
F(8)=34
F(9)=55

UPDATE

If you would like to apply arrayfun, you can use the code below

a =input('n:');
n = 1:a;
fdisp = @(n) disp(['F(',num2str(n-1),')=',num2str((((1+sqrt(5))/2).^n-((1-sqrt(5))/2).^n)/sqrt(5))]);

arrayfun(fdisp,n)

Upvotes: 2

Related Questions