matlab 螺旋矩阵 如何用matlab实现旋转矩阵
\u87ba\u65cb\u65b9\u9635matlabfunction 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
\u5728\u547d\u4ee4\u884c\u8c03\u7528\u7ed3\u679c\u5982\u4e0b\uff1a
>> 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 9
>> helixsquare(6)
ans =
1 20 19 18 17 16
2 21 32 31 30 15
3 22 33 36 29 14
4 23 34 35 28 13
5 24 25 26 27 12
6 7 8 9 10 11
>> helixsquare(-1)
??? Error using ==> helixsquare
Input number must be positive integer!
Flipdim(X,dim)\u51fd\u6570\u662fmatlab\u4e2d\u9488\u5bf9\u77e9\u9635\u7ffb\u8f6c\u53d8\u6362\u7684\u51fd\u6570\uff0c\u5176\u4e2dX\u8868\u793a\u4e00\u4e2a\u77e9\u9635\uff0cdim\u6307\u5b9a\u7ffb\u8f6c\u65b9\u5f0f\uff0cdim\u4e3a1\uff0c\u8868\u793a\u6bcf\u4e00\u5217\u8fdb\u884c\u9006\u5e8f\u6392\u5217\uff0c2\u8868\u793a\u6bcf\u4e00\u884c\u8fdb\u884c\u9006\u5e8f\u6392\u5217\u3002\u53e6\u5916matlab\u8fd8\u63d0\u4f9b\u4e86\u5de6\u53f3\u3001\u4e0a\u4e0b\u3001\u4ee5\u53ca\u65cb\u8f6c90\u5ea6\u76f4\u63a5\u5229\u7528\u7684\u51fd\u6570\uff0c\u5982\u4e0b\uff1a
\u5de6\u53f3\u7ffb\u8f6c\uff1afliplr\uff08x\uff09
\u4e0a\u4e0b\u7ffb\u8f6c\uff1aflipud\uff08x\uff09
\u65cb\u8f6c\u4e5d\u5341\u5ea6\uff1arot90\uff08x\uff09
\u5728matlab\u53ef\u4ee5\u5728\u547d\u4ee4\u7a97\u53e3\u4e2d\u8f93\u5165help flipdim\u4ee5\u83b7\u5f97\u66f4\u591a\u5e2e\u52a9\u4fe1\u606f\u3002
参考代码:
function A = cyclic(n)
% n阶螺旋矩阵
% 如未指定阶次,默认产生5阶矩阵
if ~nargin, n=5; end
% 照理说应该检查n是否为正整数,这里省略了
% 逐层向内填充数据
A = zeros(n);
c = 0;
n5 = ceil(n/2);
for i = 1 : n5
A(i,i:n-i) = c + (1:n-2*i+1);
A(i:n-i,n-i+1) = c + (1:n-2*i+1)' + (n-2*i+1)*1;
A(n-i+1,n-i+1:-1:i+1) = c + (1:n-2*i+1) + (n-2*i+1)*2;
A(n-i+1:-1:i+1,i) = c + (1:n-2*i+1)' + (n-2*i+1)*3;
c = c + (n-2*i+1)*4;
end
% 对于奇数阶,需补充中心数据
if rem(n,2), A(n5,n5) = n^2; end
测试:
>> cyclic(3)
ans =
1 2 3
8 9 4
7 6 5
>> cyclic(4)
ans =
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
>> cyclic(5)
ans =
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
>> cyclic(6)
ans =
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
扩展阅读:螺旋矩阵matlab代码 ... matlab随机生成3 3矩阵 ... matlab用for循环生成矩阵 ... 矩阵翻转 matlab ... matlab矩阵嵌套矩阵 ... 矩阵除 matlab ... matlab生成6x6矩阵 ... matlab固定范围随机数 ... matlab magic矩阵 ...