【发布时间】:2019-01-18 12:43:19
【问题描述】:
目前我在 MATLAB 中有这个功能
function [ y ] = pyramid( x )
%PYRAMID Returns a "pyramid"-shapped matrix.
y = zeros(x); % Creates an empty matrix of x by x.
rings = ceil(x/2); % Compute number of "rings".
for n = 1:rings
% Take the first and last row of the ring and set values to n.
y([n,x-n+1],n:x-n+1) = n*ones(2,x-2*(n-1));
% Take the first and last column of the ring and set values to n.
y(n:x-n+1,[n,x-n+1]) = n*ones(x-2*(n-1),2);
end
end
产生以下输出:
piramide(4)
ans =
1 1 1 1
1 2 2 1
1 2 2 1
1 1 1 1
piramide(5)
ans =
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
piramide(6)
ans =
1 1 1 1 1 1
1 2 2 2 2 1
1 2 3 3 2 1
1 2 3 3 2 1
1 2 2 2 2 1
1 1 1 1 1 1
有没有办法在不使用 for 循环的情况下获得相同的结果?
【问题讨论】:
-
您可以通过分配一个标量
n:y([n,x-n+1],n:x-n+1) = n来简化代码。可能也快一点。但是为什么需要避免循环呢? -
@CrisLuengo 感谢您的改进。分配给我的任务不允许使用 for 循环。
-
这是一道作业题,不是吗?
-
@Durkee 不,这是一个挑战。
标签: matlab function for-loop matrix