Fibonacci sequence that fills an n*n matrix
조회 수: 6 (최근 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!