将较小的3D矩阵放入更大的3D矩阵(3D sub2ind)

时间:2017-10-19 09:23:32

标签: matlab matrix multidimensional-array

我需要将较小的3D矩阵放入更大的3D矩阵中。用一个例子解释:

假设我有以下3D矩阵:

%A is the big matrix
A(:,:,1)=[ 0.3545    0.8865    0.2177
           0.9713    0.4547    0.1257
           0.3464    0.4134    0.3089];

A(:,:,2)=[  0.7261    0.0098    0.7710
            0.7829    0.8432    0.0427
            0.6938    0.9223    0.3782];

A(:,:,3) = [0.7043    0.2691    0.6237
            0.7295    0.6730    0.2364
            0.2243    0.4775    0.1771];

%B is the small matrix
B(:,:,1) = [0.3909    0.5013 
            0.0546    0.4317];


B(:,:,2) =[0.4857    0.1375 
           0.8944    0.3900];

B(:,:,3) =[0.7136    0.3433
           0.6183    0.9360];

现在将B放入A中:使用第一维:[1 3],第二维[2 3],并对A的[1,2,3]页执行此操作。对于给定的矩阵,放置这些值将导致:

NewA(:,:,1) = [ 0.3545    0.3909    0.5013     % putting the value of %B(1,:,1)
                0.9713    0.4547    0.1257
                0.3464    0.0546    0.4317;   % putting the value of %B(2,:,1)


NewA(:,:,2)=[  0.7261    0.4857    0.1375      % putting the value of %B(1,:,2)
               0.7829    0.8432    0.0427
               0.6938    0.8944    0.3900];    % putting the value of %B(2,:,2)


NewA(:,:,3) = [0.7043    0.7136    0.3433      % putting the value of %B(1,:,3)
               0.7295    0.6730    0.2364
               0.2243    0.6183    0.9360];    % putting the value of %B(2,:,3)

我不一定将方形矩阵作为3D页面,A放入B的大小也可能不同。但矩阵将永远是3D。以上只是一个小例子。我实际拥有的尺寸与A一样大 - > [500,500,5]和B为 - > [350,350,4]。

这是sub2ind对2D矩阵所做的事情,但我还不能用于3D矩阵。

类似的东西:

NewA = A;  
NewA(sub2ind(size(A), [1 3], [2 3], [1 2 3])) = B;

但它给出了:

Error using sub2ind (line 69)
The subscript vectors must all be of the same size.

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您不需要sub2ind,只需直接分配:

newA(1,2:3,:)=B(1,:,:)

如果您想使用sub2ind,则需要为要替换的每个元素指定3个维度中的每个维度:

dim1A=[1 1 1 1 1 1];  % always first row
dim2A=[2 3 2 3 2 3];  % second and third column, for each slice
dim3A=[1 1 2 2 3 3];  % two elements from each slice

newA(sub2ind(size(A),dim1A,dim2A,dim3A))=B(1,:,:)

newA(:,:,1) =

    0.3545    0.3909    0.5013
    0.9713    0.4547    0.1257
    0.3464    0.4134    0.3089


newA(:,:,2) =

    0.7261    0.4857    0.1375
    0.7829    0.8432    0.0427
    0.6938    0.9223    0.3782


newA(:,:,3) =

    0.7043    0.7136    0.3433
    0.7295    0.6730    0.2364
    0.2243    0.4775    0.1771