I need to put a smaller 3D matrix into a bigger 3D matrix. Explaining with an example:
Suppose I have the following 3D matrices:
%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];
Now to put B in A such that: use first dimension: [1 3], second dimension [2 3] and do this for [1,2,3] pages of A. For the given matrix, putting these values will result in:
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)
I won't necessarily have square matrices as 3D pages and the size of A
to put B
in can vary as well. But the matrices will always be 3D. Above is just a small example. What I actually have is dimensions as big as A -> [500,500,5] and B as -> [350,350,4].
This is what sub2ind
do for 2D matrices but I am not yet able to manipulate into use for 3D matrices.
Something like:
NewA = A;
NewA(sub2ind(size(A), [1 3], [2 3], [1 2 3])) = B;
but it gives:
Error using sub2ind (line 69)
The subscript vectors must all be of the same size.
How can I do this?
You don't need sub2ind
, just assign directly:
newA(1,2:3,:)=B(1,:,:)
If you want to use sub2ind
, you need to specify each of the 3 dimensions, for each of the elements you want to replace:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.