matlab - Fibonacci matrix using loops of matlab
问题描述
I want to create an MxN matrix of the Fibonacci series.
My Matlab function should take two integers that are M and N and return a two-dimensional array of Fibonacci series like
A =
1 1 2 3 5 8 13 21 34
1 2 3 5 8 13 21 34 55
2 3 5 8 13 21 34 55 89
3 5 8 13 21 34 55 89 144
5 8 13 21 34 55 89 144 233
8 13 21 34 55 89 144 233 377
I just could create 1 row of the matrix
function A = double_fibonacci(M,N)
A = ones(M,N);
for ii = 1:M
for jj = 3:N
A(ii,jj) = A(ii,jj-1) + A(ii,jj-2);
end
end
end
Thanks in advance.
解决方案
If you want to build your matrix with a double loop, then after you finish the first line, you need to prepare the next line so the fibonacci calculations can be done with the same method than for the first line. This "preparation" involve copying the 2nd and 3rd element of the current line into the 1st and 2nd position of the next line.
This would look like this:
function A = double_fibonacci_loop(M,N)
A = ones(M,N);
for ii = 1:M
% build the line normally
for jj = 3:N
A(ii,jj) = A(ii,jj-1) + A(ii,jj-2);
end
% if we're not on the last line, we copy the 2nd and 3rd element of the
% current line into the 1st and 2nd element of the next line, so the
% fibonacci calculation can proceed as in the block above
if ii<M
A(ii+1,1:2) = A(ii,2:3) ;
end
end
However, if you don't specifically need a double loop, I would propose another way to build that matrix. Just compute only once a Fibonacci suite with all the elements required, then copy the relevant elements in each line of your final matrix.
This would look like:
function A = double_fibonacci(M,N)
%% Construct a single fibonacci suite with the required number of elements
nElements = M+N-1 ;
basefib = ones(1,nElements) ;
for k=3:nElements
basefib(k) = basefib(k-1) + basefib(k-2) ;
end
% After that block, basefib =
% [ 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ]
%% Now dispatch the relevant elements in each line of your matrix
A = ones(M,N);
for k=1:M
A(k,:) = basefib(k:k+N-1) ;
end
And just to make sure, both function output the same result:
>> A = double_fibonacci(6,9)
A =
1 1 2 3 5 8 13 21 34
1 2 3 5 8 13 21 34 55
2 3 5 8 13 21 34 55 89
3 5 8 13 21 34 55 89 144
5 8 13 21 34 55 89 144 233
8 13 21 34 55 89 144 233 377
推荐阅读
- c# - DataTemplate 的绑定给目标一个不正确/未设置/空值
- python - Python:在不同的窗口中绘制多个图形(相同的数据但具有不同的 X 范围)
- alamofire - AlamofireImage:如何为 af_setImage 设置 timeoutIntervalForRequest?
- django - Django ORM - 查询取决于通过表
- protractor - 迭代直到找到匹配的文本
- dart - 如何在 Flutter 上以编程方式清除应用程序缓存
- python - 如何在 Python 中找到两个一维数组之间的马氏距离?
- gcc - 可以提取我当前的工具链吗?
- google-compute-engine - GCE 托管组(自动缩放)- HTTP(S) 和 TCP 请求的代理/负载均衡器
- python - 使用固定输入变量进行回归预测的等高线图