Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matlab 有没有一种不使用for循环的方法可以做到这一点?_Matlab_Function_For Loop_Matrix - Fatal编程技术网

Matlab 有没有一种不使用for循环的方法可以做到这一点?

Matlab 有没有一种不使用for循环的方法可以做到这一点?,matlab,function,for-loop,matrix,Matlab,Function,For Loop,Matrix,目前我在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 ri

目前我在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不。这是一个挑战。你可以通过分配标量
n
y([n,x-n+1],n:x-n+1)=n
来简化代码。也可能快一点。但是为什么你需要避免循环呢?@CrisLuengo谢谢你的改进。分配给我的任务不允许使用for循环。这是一个家庭作业问题,不是吗?@Durkee不。这是一个挑战。太棒了!我从来没有想到过。就像那一行:)太棒了!我永远不会想到这一点。就像那一行:)
function y = pyramid(x)
    m([1 x], 1:x) = 1;
    m(1:x, [1 x]) = 1;
    y = bwdist(m,'chessboard')+1;
end
pyramid = @(x) min(min((1:x),(1:x).'), min((x:-1:1),(x:-1:1).'));