How to convert 2d matrix to 4d matrix?

If I have a 4*4 matrix like this
a=[30,31;32,33]; % a can be more than 2d array
b=[40,41;42,43]; % b can be more than 2d array
c=[50,51;52,53]; % c can be more than 2d array
d=[60,61;62,63]; % d can be more than 2d array
X=[1,2,3,a;5,6,b,8;c,10,11,12;d,14,15,16];
how to convert it to, in this case, to 4*4*2*2 where X(1,4,1,1)=30, X(1,4,1,2)=31,X(1,4,2,1)=32,X(1,4,2,2)=33, X(2,3,1,1)=40,X(2,3,1,2)=41,X(2,3,2,1)=42,X(2,3,2,2)=43 and so on?

 Accepted Answer

Ameer Hamza
Ameer Hamza on 18 May 2020
Edited: Ameer Hamza on 18 May 2020
Are you looking for something like this
a=[30,31;32,33]; % a can be more than 2d array
b=[40,41;42,43]; % b can be more than 2d array
c=[50,51;52,53]; % c can be more than 2d array
d=[60,61;62,63]; % d can be more than 2d array
X = cat(3, a, b, c, d);
Or maybe this
a=[30,31;32,33]; % a can be more than 2d array
b=[40,41;42,43]; % b can be more than 2d array
c=[50,51;52,53]; % c can be more than 2d array
d=[60,61;62,63]; % d can be more than 2d array
X(1,4,:,:) = a;
X(2,3,:,:) = b;
X(3,2,:,:) = c;
X(4,1,:,:) = d;
Result
>> size(X)
ans =
4 4 2 2

4 Comments

Yeah, thank you for your answer. I edited your suggestion, which is somewhat like
Sulaymon's suggestion , to add a,b,c and d to the original matrix like that
XX=[1,2,3,0;5,6,0,8;0,10,11,12;0,14,15,16];
X=repmat(XX,[1,1,2,2]);
X(1,4,:,:) = a;
X(2,3,:,:) = b;
X(3,2,:,:) = c;
X(4,1,:,:) = d;
But again if I don't know the dimensions of a,b,c,d (I mean they can be 3 or more dimensions matrices) how to make it more general?
Try this. It will work for an arbitrary number of dimensions of 'a'
a=rand(2,2,2); % a can be more than 2d array
b=rand(2,2,2); % b can be more than 2d array
c=rand(2,2,2); % c can be more than 2d array
d=rand(2,2,2); % d can be more than 2d array
XX=[1,2,3,0;5,6,0,8;0,10,11,12;0,14,15,16];
X=repmat(XX,[1,1,size(a)]);
col_idx = repmat({':'}, 1, ndims(a));
X(1,4,col_idx{:}) = a;
X(2,3,col_idx{:}) = b;
X(3,2,col_idx{:}) = c;
X(4,1,col_idx{:}) = d;
I am glad to be of help.

Sign in to comment.

More Answers (1)

It is going to be something like that:
X(:,:,:,1)=a;
X(:,:,:,2)=b;
X(:,:,:,3)=c;
X(:,:,:,4)=d;

1 Comment

Thank you for your answer. I edited your suggestion to add them to the original matrix like that
XX=[1,2,3,0;5,6,0,8;0,10,11,12;0,14,15,16];
X=repmat(XX,[1,1,2,2]);
X(1,4,:,:) = a;
X(2,3,:,:) = b;
X(3,2,:,:) = c;
X(4,1,:,:) = d;
But if I don't know the dimensions of a,b,c,d (I mean they can be 3 or more dimensions matrices) how to make it more general?

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!