我正在使用matlab制作一个三维数组,它根据模式进行。虽然我可以手动写出数组,但我相信有更快的方法可以做到这一点。
multiArray = cat(3,...
[1+randn(4,3); 1*randn(4,3)],...
[2+randn(4,3); 2*randn(4,3)],...
[3+randn(4,3); 3*randn(4,3)]);
如果我想让上面的数组为8x3x25,那么最后一行将是
[25+randn(4,3); 25*randn(4,3)]
但是如何在不经过所有繁琐的干预步骤的情况下制作这样的阵列呢?
答案 0 :(得分:3)
这是使用bsxfun
的可能方式。
%// 25 x 4 x 3 with elements for i + randn(4,3)
P = bsxfun(@plus, (1:25)', randn(25,4,3));
%// 25 x 4 x 3 with elements for i * randn(4,3)
T = bsxfun(@times, (1:25)', randn(25,4,3));
%// Concatenate and shift dimensions to get desired size output
multiArray = shiftdim([P T], 1);
答案 1 :(得分:3)
虽然mikkola basically got the solution,但最后不需要移动维度。
s=[4,3,25];
it=reshape(1:s(3),1,1,[]);
out = [bsxfun(@plus , it, randn(s));...
bsxfun(@times, it, randn(s))];
答案 2 :(得分:1)
如果你不介意为了提高效率而把事情带到4D
-
N = 25; %// Number of 3D slices
out = randn(4,2,3,N);
out(:,1,:,:) = bsxfun(@plus,permute(1:N,[1 4 3 2]),out(:,1,:,:));
out(:,2,:,:) = bsxfun(@times,permute(1:N,[1 4 3 2]),out(:,2,:,:));
out = reshape(out,8,3,N);
要合法化解决方案,让我们从输入A = randn(8,3,N)
开始,并用它初始化输出out
。另外,让我们将3D切片的数量作为一个小数字,所以说N = 3
。
因此,
>> N = 3;
A = randn(8,3,N);
out = reshape(A,[4 2 3 N]); %// This replaces "out = randn(4,2,3,N)"
接下来,我们运行将更改out
-
>> out(:,1,:,:) = bsxfun(@plus,permute(1:N,[1 4 3 2]),out(:,1,:,:));
out(:,2,:,:) = bsxfun(@times,permute(1:N,[1 4 3 2]),out(:,2,:,:));
out = reshape(out,8,3,N);
现在,开始验证每个3D
切片 -
>> out(1:4,:,1) - A(1:4,:,1)
ans =
1 1 1
1 1 1
1 1 1
1 1 1
>> out(1:4,:,2) - A(1:4,:,2)
ans =
2 2 2
2 2 2
2 2 2
2 2 2
>> out(1:4,:,3) - A(1:4,:,3)
ans =
3 3 3
3 3 3
3 3 3
3 3 3
>> out(5:end,:,1)./A(5:end,:,1)
ans =
1 1 1
1 1 1
1 1 1
1 1 1
>> out(5:end,:,2)./A(5:end,:,2)
ans =
2 2 2
2 2 2
2 2 2
2 2 2
>> out(5:end,:,3)./A(5:end,:,3)
ans =
3 3 3
3 3 3
3 3 3
3 3 3