创建金字塔棋盘矩阵MATLAB

时间:2014-06-24 17:30:29

标签: matlab matrix

我想在白色背景上创建一个金字塔形状的棋盘。它需要是一个大矩阵(1186,686)或我只是手动完成。我所追求的简化版本如下:

0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0
0 0 0 1 0 1 0 0 0
0 0 1 0 1 0 1 0 0
0 1 0 1 0 1 0 1 0
1 0 1 0 1 0 1 0 1

1 个答案:

答案 0 :(得分:1)

这是一次尝试,它是半矢量化的,因为我还没知道如何在没有for循环的情况下做到这一点。

function B = board(rows, cols, centerright)
    c2 = cols/2;
    mid = floor(c2);
    if c2 ~= int32(c2) || centerright
        mid = mid + 1;
    end

    B = zeros(rows,cols);
    for row = 2:min([rows, mid+1, cols-mid+2])
        offset = row-2;
        newr = zeros(1, cols);
        newr([mid-offset:2:mid+offset]) = 1;
        B(row,:) = newr;
    end
end

演示:

>> board(6,9)
ans =
     0     0     0     0     0     0     0     0     0
     0     0     0     0     1     0     0     0     0
     0     0     0     1     0     1     0     0     0
     0     0     1     0     1     0     1     0     0
     0     1     0     1     0     1     0     1     0
     1     0     1     0     1     0     1     0     1
>> board(6,10,0)
ans =
     0     0     0     0     0     0     0     0     0     0
     0     0     0     0     1     0     0     0     0     0
     0     0     0     1     0     1     0     0     0     0
     0     0     1     0     1     0     1     0     0     0
     0     1     0     1     0     1     0     1     0     0
     1     0     1     0     1     0     1     0     1     0
>> board(6,10,1)
ans =
     0     0     0     0     0     0     0     0     0     0
     0     0     0     0     0     1     0     0     0     0
     0     0     0     0     1     0     1     0     0     0
     0     0     0     1     0     1     0     1     0     0
     0     0     1     0     1     0     1     0     1     0
     0     1     0     1     0     1     0     1     0     1