我想生成N-by-N-by-3矩阵A
,使A(:,:,i) = eye(n)*i
。如何在不使用for循环的情况下(即以矢量化方式)执行此操作?
答案 0 :(得分:1)
>> N = 4;
>> A = reshape(kron(1:3,eye(N)),[N N 3])
A(:,:,1) =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
A(:,:,2) =
2 0 0 0
0 2 0 0
0 0 2 0
0 0 0 2
A(:,:,3) =
3 0 0 0
0 3 0 0
0 0 3 0
0 0 0 3
答案 1 :(得分:1)
另一种选择是使用BSXFUN,将单位矩阵与1,2,3
>> bsxfun(@times,eye(4),permute(1:3,[3,1,2]))
ans(:,:,1) =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
ans(:,:,2) =
2 0 0 0
0 2 0 0
0 0 2 0
0 0 0 2
ans(:,:,3) =
3 0 0 0
0 3 0 0
0 0 3 0
0 0 0 3
答案 2 :(得分:0)
如果您在引入BSXFUN之前有旧版本的MATLAB,请考虑此选项(与@Jonas的答案相同):
N = 4; M = 3;
A = repmat(eye(N),[1 1 M]) .* repmat(permute(1:M,[3 1 2]),[N N 1])
A(:,:,1) =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
A(:,:,2) =
2 0 0 0
0 2 0 0
0 0 2 0
0 0 0 2
A(:,:,3) =
3 0 0 0
0 3 0 0
0 0 3 0
0 0 0 3