Fibonacci sequence that fills an n*n matrix
7 次查看(过去 30 天)
显示 更早的评论
Hey everybody. I'm trying to create an n x n matrix where the first two elements are input as well as n. It needs to fill the matrix row by row with each successive summation. I used a loop, but I'm welcome to other suggestions. Here's my code.
n=input('n=\n');
E1=input('First element=\n');
E2=input('Second element=\n');
fib=zeros(n,n);
fib(1)=E1;
fib(2)=E2;
k=3;
for k=3:size(fib);
fib(n/n,k)=fib(k-1)+fib(k-2);
end
fib
回答(4 个)
the cyclist
2014-8-8
编辑:the cyclist
2014-8-8
Instead of
fib(1)=1;
fib(2)=0;
I assume you meant
fib(1)=E1;
fib(2)=E2;
John D'Errico
2014-8-8
编辑:John D'Errico
2014-8-9
Adam - did you really intend to write it as:
fib(n/n,k)=fib(k-1)+fib(k-2);
Why would you use fib(n/n,k) for an assignment?
Surely you see that n/n is 1. So why not just assign it as
fib(1,k)=fib(k-1)+fib(k-2);
In fact, I have no idea why you are talking about an n*n matrix. There are n elements, not n*n elements.
You are creating a vector of length n. Note that when you index into the matrix, with f(k), you are treating it as a vector. So what do you intend when you talk about an nxn matrix?
And there is no need to initialize k before the start of the for loop. The for loop creates k as a variable.
As far as how to create a matrix of Fibonacci numbers, there are many ways to do so. The simplest way is to use filter, but that is not so obvious how it works if you are just learning to use a loop for the purpose.
n = input('n=\n');
fib = zeros(1,n);
fib(1) = input('First element=\n');
fib(2) = input('Second element=\n');
for k=3:n
fib(k) = fib(k-1) + fib(k-2);
end
fib
If you wish to create an array, then you need to explain what form it must take.
0 个评论
John Jairo Aguirre Sanchez
2018-12-31
clc
clear
%matriz fibonacci
%dimension de la matriz cuadrada
n=6;
h=zeros(n);
%matriz
format longg
for i=1:n
h(1,1)=1;
h(1,2)=1;
for j=3:n
h(i,j)=h(i,j-2)+h(i,j-1);
end
end
for i=2:n
for j=1:n;
if j==1;
h(i,j)=h(i-1,n)+h(i-1,n-1);
else if j==2
h(i,j)=h(i-1,n)+h(i,j-1);
else
h(i,j)=h(i,j-2)+h(i,j-1);
end
end
end
end
h
0 个评论
Sahiro Ortega Campoverde
2022-10-9
for i=2:n
for j=1:n;
if j==1;
h(i,j)=h(i-1,n)+h(i-1,n-1);
else if j==2
h(i,j)=h(i-1,n)+h(i,j-1);
else
h(i,j)=h(i,j-2)+h(i,j-1);
end
end
end
end
h
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!