How to transform a matrix into a 3D array (tensor) ?
107 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(2 个)
Adam
2018-12-3
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 个评论
Adam
2018-12-4
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!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!