How to transform a matrix into a 3D array (tensor) ?

159 views (last 30 days)
Say I have B, a matrix which looks like this:
B =
1 10 100 2 20 200
3 30 300 4 40 400
And I created a tensor specifically like down below, because I want those elements in that exact order:
A(:,:,1) = [B(1,1) B(1,4); B(2,1) B(2,4)];
A(:,:,2) = [B(1,2) B(1,5); B(2,2) B(2,5)];
A(:,:,3) = [B(1,3) B(1,6); B(2,3) B(2,6)];
So I obtained this:
A(:,:,1) =
1 2
3 4
A(:,:,2) =
10 20
30 40
A(:,:,3) =
100 200
300 400
Is there a way that I could automatize those 3 lines of code? To be able to create a tensor like that from a matrix of different dimensions, not manually telling it each element it needs to take?
B is the result of unfolding the tensor A, so I want to code the inverse operation.
LE:
I've read somewhere on here an algorithm that works for the mode-2 unfolding, which means B looks like this:
B2 =
1 3 10 30 100 300
2 4 20 40 200 400
the code:
x=2; y=2; z=3;
slice = size(B2,2)/x; %6:2=3
part = size(B2,2)/z; %6:3=2
start=1;
A=zeros(x,y,z);
for i=1:slice
A(:,:,i)=B2(:,start:start+part-1)';
start=start+part;
end
I also adapted it for B matrix but I am trying to adapt it to the other type of unfolding, for the matrix B3:
B3 =
1 2 3 4
10 20 30 40
100 200 300 400
and the problem is now the 'part' variable would be 4/3 which isn't too convenient, and I also can't seem to fit the first line into the tensor without causing an error. I've tried manually something like this:
for i=1:3
A(:,:,i)=B3(i,1:4);
end
and I am not sure how to break the first 2 elements of B3 so the next 2 ones can go to the second row of the tensor.

Answers (2)

Matt J
Matt J on 3 Dec 2018
A=[1,2;3 4].*reshape([1,10,100], 1,1,[])

Adam
Adam on 3 Dec 2018
permute( reshape( reshape( B', 3, 4 )', [2 2 3] ), [2 1 3] )
gives the answer you want, but I'm sure there is a tidier way that someone will come up with!
  2 Comments
snowflake
snowflake on 4 Dec 2018
Thank you, I modified it a bit so that it works on different dimensions of a matrix and also for other types of foldings. I've tried to play with reshape and permute before and I couldn't find the perfect match, how did you manage to think of this line of code?
Adam
Adam on 4 Dec 2018
I just played around on the command line with reshape and permute, using knowledge of what order the data gets reshaped in.
I solve a large number of my problems by just trying stuff on command line, knowing what components I likely need, but not necessarily in what combination or order until I just try it. I don't find it worth trying to commit all these things to memory when I have the command line at my disposal to test things so quickly!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!