【问题标题】:Is there a way to do this without a for-loop?有没有办法在没有 for 循环的情况下做到这一点?
【发布时间】: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


【解决方案1】:

如果你有图像处理工具箱,你可以使用bwdist:

function y = pyramid(x)
    m([1 x], 1:x) = 1;
    m(1:x, [1 x]) = 1;
    y = bwdist(m,'chessboard')+1;
end

使用min的其他解决方案:

pyramid = @(x) min(min((1:x),(1:x).'), min((x:-1:1),(x:-1:1).'));

【讨论】:

  • 太棒了!我从来没有想过。
  • 喜欢单线 :)
猜你喜欢
  • 1970-01-01
  • 2020-12-20
  • 2022-01-19
  • 1970-01-01
  • 2023-03-07
  • 2020-04-07
  • 2021-07-09
  • 2018-07-29
  • 2023-03-15
相关资源
最近更新 更多