如何在MATLAB中创建这种特殊的分形图案?

时间:2019-05-16 17:42:37

标签: matlab

在这种特殊的分形模式中,我需要制作一个零和一个数组:

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

实际数组应为100 x100。模式应从中间(x,y)坐标开始,并扩展为看起来像模式(使用循环)。

到目前为止,我仅设法制作了一个看起来像“ +”号的图案。我不确定如何继续。

到目前为止,这是我的代码:

n = zeros(16); % using 16x16 array for practice
x = length(n)/2;
y = length(n)/2;
z = length(n) - 1;

xso = length(n)/2; % x axis south movement
xno = length(n)/2; % x axis north movement
yea = length(n)/2; % y axis east movement
ywe = length(n)/2; % y axis west movement

for i = 1:1:z
        newyea = move('east', x, yea);
        n(x, newyea) = 1;
        yea = newyea;

        newywe = move('west', x, ywe);
        n(x, newywe) = 1;
        ywe = newywe;

        newxso = move('south', xso, y);
        n(newxso, y) = 1;
        xso = newxso;

        newxno = move('north', xno, y);
        n(newxno, y) = 1;
        xno = newxno;
end

我还有一个用户定义的功能:

function newval = move(dir, x, y)

switch dir
    case 'east'
        newval = y + 1;
    case 'west'
        newval = y - 1;
    case 'south'
        newval = x + 1;
    case 'north'
        newval = x - 1;
end

1 个答案:

答案 0 :(得分:1)

由于对循环的外观没有任何限制,因此我将提出以下解决方案。但是,在此之前,让我们看一下您的示例:

Given example

您应该将所需的尺寸d限制为奇数,即d = 11, 13, 15, ...,或者应该指定在偶数尺寸d的情况下如何继续图案,例如此处d = 12。对于我的解决方案,我决定依靠维度d为奇数。

代码如下:

d = 15;                 % Dimension

A = zeros(d);           % Initialize output array A

c = (d + 1) / 2;        % Calculate center index (row, column)

A(:, c) = 1;            % Add: Cross 
A(c, :) = 1;

J = 0;                  % Auxiliary index
for I = (c+2):2:d       % For every second row (or column) from center to border
  J = J + 1;             
  l = 4 * J - 1;        % Calculate length of line to draw
  s = c - (l-1)/2;      % Calculate start point of line
  e = c + (l-1)/2;      % Calculate end point of line
  A(I, s:e) = 1;        % Add: "South" line
  A(s:e, I) = 1;        % Add: "East" line
  A(c - 2*J, s:e) = 1;  % Add: "North" line
  A(s:e, c - 2*J) = 1;  % Add: "West" line
end

figure(1);              % Show image
imagesc(A);

d = 15的输出(与给定示例进行比较):

Output for d = 15

d = 99的输出:

Output for d = 99

希望有帮助!

如果您对for循环有更严格的限制,请告诉我们。然后,我将尝试相应地修改我的代码。