Matlab第三次打卡
程序员文章站
2022-07-13 21:53:31
...
Task03:数据类型
语法知识
1.奇数阶魔方矩阵
魔方矩阵的设计思路之一,是构造一个扩展的零矩阵A,随后用顺序矩阵v填入A的相应对角线,再用行、列叠加使矩阵A的中心n阶矩阵零元素填满。最后取出中心n阶方阵,即得魔方矩阵。
下面为奇数阶魔方矩阵的程序,文件名为odd_magic.
%This is program for creat a matrix of odd order magic
clear
n=input('please input a odd number \n');
if mod(n,2)==0
'input number must be odd.';
end
n1=2*n-1;m=(n-1)/2;
A=zeros(n1);
for i=1:n
for j=1:n
v(i,j)=(i-1)*n+j;
end
end
for k=1:m+1
B=zeros(1,n-2+2*k);
B(k:(k+n-1))=v(k,:);
A=A+diag(B,n+1-2*k);
end
for k=m+2:n
B=zeros(1,3*n-2*k);
B(n-k+1:2*n-k)=v(k,:);
A=A+diag(B,n+1-2*k);
end
if m==1
A(4,:)=A(4,:)+A(1,:);
A(2,:)=A(2,:)+A(5,:);
A(:,4)=A(:,4)+A(:,1);
A(:,2)=A(:,2)+A(:,5);
else
Bu=A(1:m,:);
Bd=A((n1-m+1):n1,:);
Bl=A(:,1:m);
Br=A(:,(n1-m+1):n1);
A(m+1:2*m,:)=A(m+1:2*m,:)+ Bd;
A((n1-2*m+1):n1-m,:)=A((n1-2*m+1):n1-m,:)+Bu;
A(:,m+1:2*m)=A(:,m+1:2*m)+Br;
A(:,(n1-2*m+1):n1-m)=A(:,(n1-2*m+1):n1-m)+Bl;
end
M=A(m+1:(n1-m),m+1:(n1-m)); %取*n阶方阵,即为魔方矩阵
2.数据类型概述
3.字符型数组
实例演练
>> odd_magic
please input a odd number
3
>> n
n =
3
>> M
M =
4 9 2
3 5 7
8 1 6
>> odd_magic
please input a odd number
5
>> n
n =
5
>> M
M =
11 24 7 20 3
4 12 25 8 16
17 5 13 21 9
10 18 1 14 22
23 6 19 2 15
>> v
v =
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
>> A
A =
0 0 0 0 1 0 0 0 0
0 0 0 6 0 2 0 0 0
0 0 11 24 7 20 3 0 0
0 16 4 12 25 8 16 4 0
21 0 17 5 13 21 9 0 5
0 22 10 18 1 14 22 10 0
0 0 23 6 19 2 15 0 0
0 0 0 24 0 20 0 0 0
0 0 0 0 25 0 0 0 0
>> magic(5)
ans =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
>> sum(M) %列元素之和的向量
ans =
65 65 65 65 65
>> sum(M') %行元素之和的向量
ans =
65 65 65 65 65
>> trace(M) %主对角线元素之和
ans =
65
>> trace(M') %反向主对角线元素之和
ans =
65
【例3-19】建立字符串数组A='Today is Saturday.'及B='I want to eat ice-cream.'检查它们的长度,将他们进行水平连接和垂直连接。
>> A =
'Today is Saturday.'
>> b='I want eat ice-cream.'
b =
'I want eat ice-cream.'
>> na=size(A)
na =
1 18
>> nb=size(b)
nb =
1 21
>> NA=strcat(A,b)
NA =
'Today is Saturday.I want eat ice-cream.'
>> NB=strvcat(A,b)
NB =
'Today is Saturday. '
'I want eat ice-cream.'
>> size(NB)
ans =
2 21
>> double(NB)
ans =
84 111 100 97 121 32 105 115 32 83 97 116 117 114 100 97 121 46 32 32 32
73 32 119 97 110 116 32 101 97 116 32 105 99 101 45 99 114 101 97 109 46
>> k=findstr(s,'the')
k =
6 30
或
>> k1=findstr('the',s)
k1 =
6 30
>> S1='The area is at least 400 square meters';
>> newarea=strrep(S1,'400','1000')
newarea =
'The area is at least 1000 square meters'
>> asii=char(reshape(32:127,32,3)')
asii =
3×32 char 数组
' !"#$%&'()*+,-./0123456789:;<=>?'
'@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_'
'`abcdefghijklmnopqrstuvwxyz{|}~'
总结思考
1.在魔方矩阵程序运行方面存在一些问题,经过纠正最终得到正确结果,但具体的矩阵不是很清楚;掌握了一些求和的函数;
2.数据类型上对于字符串相关的函数有了理解和掌握。
上一篇: 网站开发中安全问题初探
下一篇: Linux学习之路-(2.vi编辑器)