多维数组的创建
1.多维数组的创建
(1)多维数组的创建可以通过直接赋值来取得。
例题:设置三维矩阵A,第一页为magic(3),第二页为vander([1,2,3]),第三页为Pascal(3)。
B(:,:,1)表示第一页!
>> B(:,:,1)=magic(3); %第一页
>> B(:,:,2)=vander([1 2 3]);
>> B(:,:,3)=pascal(3);
>> B
B(:,:,1) =
8 1 6
3 5 7
4 9 2
B(:,:,2) =
1 1 1
4 2 1
9 3 1
B(:,:,3) =
1 1 1
1 2 3
1 3 6
(2)通过矩阵函数生成
例题:设置三维正态分布的随机矩阵C,其中m=n=4,k=3
C=rand(4,4,3)
C(:,:,1) =
0.9572 0.4218 0.6557 0.6787
0.4854 0.9157 0.0357 0.7577
0.8003 0.7922 0.8491 0.7431
0.1419 0.9595 0.9340 0.3922
C(:,:,2) =
0.6555 0.2769 0.6948 0.4387
0.1712 0.0462 0.3171 0.3816
0.7060 0.0971 0.9502 0.7655
0.0318 0.8235 0.0344 0.7952
C(:,:,3) =
0.1869 0.7094 0.6551 0.9597
0.4898 0.7547 0.1626 0.3404
0.4456 0.2760 0.1190 0.5853
0.6463 0.6797 0.4984 0.2238
关于函数 rand()
rand
rand Uniformly distributed pseudorandom numbers.
R = rand(N) returns an N-by-N matrix containing pseudorandom values drawn from the standard uniform distribution on the open interval(0,1).
rand(M,N)or rand([M,N]) returns an M-by-N matrix.
rand(M,N,P,…) or rand([M,N,P,…]) returns an M-by-N-by-P-by-… array. rand returns a scalar.
rand(SIZE(A)) returns an array the same size as A.
例题:矩阵复制生成多维矩阵C,它是由矩阵A=[1 2;3 4],复制成343 矩阵
C=repmat(A,[3,4,3]) %将矩阵A复制成3*4,复制后再复制3页
>> A=[1 2;3 4]
A =
1 2
3 4
>> C=repmat(A,[3,4,3]) %将矩阵A复制成3*4,复制后再复制3页
C(:,:,1) =
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
C(:,:,2) =
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
C(:,:,3) =
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
1 2 1 2 1 2 1 2
3 4 3 4 3 4 3 4
例题:用矩阵连接函数cat,生成多维数组D=cat(dim,A,B,C),A=magic(3),B=ones(3),C=eye(3),维数dim=3
其中eye()的含义如下:
eye
eye Identity matrix(单位矩阵:除了对角线是1,其他地方均为0).
eye(N) is the N-by-N identity matrix.
eye(M,N) or eye([M,N]) is an M-by-N matrix with 1’s on
the diagonal(主对角线) and zeros elsewhere.
>> A=magic(3);
>> B=ones(3);
>> C=eye(3);
>> D=cat(3,A,B,C)
D(:,:,1) =
8 1 6
3 5 7
4 9 2
D(:,:,2) =
1 1 1
1 1 1
1 1 1
D(:,:,3) =
1 0 0
0 1 0
0 0 1
法二:看似简单,其实是不推荐的,不好 实现复用性
>> D=cat(3,magic(3),ones(3),eye(3))
D(:,:,1) =
8 1 6
3 5 7
4 9 2
D(:,:,2) =
1 1 1
1 1 1
1 1 1
D(:,:,3) =
1 0 0
0 1 0
0 0 1
2.多维数组的运算
思想:多维数组的运算和二维数组的运算基本相同,MATLAB的大多数内装函数是支持多维数组,如果不支持的话,可以分别用二维数组经多次 运算来代替
>> B(:,:,1)=magic(3);
>> B(:,:,2)=ones(3);
>> B(:,:,3)=eye(3)
B(:,:,1) =
8 1 6
3 5 7
4 9 2
B(:,:,2) =
1 1 1
1 1 1
1 1 1
B(:,:,3) =
1 0 0
0 1 0
0 0 1
>> size(B)
ans =
3 3 3 %3行3列3页
>> sum(B) %每页中每列求和
ans(:,:,1) =
15 15 15
ans(:,:,2) =
3 3 3
ans(:,:,3) =
1 1 1
>> prod(B) %每页中每列求积
ans(:,:,1) =
96 45 84
ans(:,:,2) =
1 1 1
ans(:,:,3) =
0 0 0
>> sum(sum(B)) %每页的和
ans(:,:,1) =
45
ans(:,:,2) =
9
ans(:,:,3) =
3
>> sum(sum(sum(B))) %整个三维矩阵的和
ans =
57
>>