螺旋方阵matlab

来源:百度知道 编辑:UC知道 时间:2024/06/14 17:09:39
跪求怎么用matlab语言编写螺旋方阵啊, 1 16 15 14 13
2 17 24 23 22
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9
1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8 9

function x=helixsquare(n)
% Helix square matrix.
% X = HELIXSQUARE(N)
% Return N-by-N helix square matrix X with elements from 1 to N*N.

if n<=0 | ~isreal(n) error('Input number must be positive integer!');end
n=fix(n(1));
mid=(n+1)/2;
x=zeros(n);
pos=1;
dir=-i;
for k=1:n*n
row=-imag(pos+dir);
col=real(pos+dir);
if abs(row-mid)> n/2 | abs(col-mid)>n/2
dir=i*dir;
row=-imag(pos+dir);
col=real(pos+dir);
end
if x(row,col)~=0
dir=i*dir;
row=-imag(pos+dir);
col=real(pos+dir);
end
x(row,col)=k;
pos=pos+dir;
end

在命令行调用结果如下:

>> helixsquare(5)

ans =

1 16 15 14 13
2 17 24 23 12
3 18 25 22 11
4 19 20 21 10
5 6 7 8