How do you convert a 4D matrix into a N by M
Show older comments
I've got a 4D array from a nested for loop [Month, day, record [pair of values] ] that I need to convert into a single N by M matrix in order to run a probablilty matrix analysis....any ideas on the conversion from 4D to 2D?
Answers (4)
Wayne King
on 26 Oct 2011
Hi Oliver, you can use reshape() but you have to be mindful of how the elements are filled in the 2-D matrix.
For example:
x = randn(2,2,2);
x1 = reshape(x,4,2);
1 Comment
Jan
on 26 Oct 2011
The PERMUTE command might be helpful in addition.
Andrei Bobrov
on 27 Oct 2011
e.g.
a4d = randi(125,[2 2 2 2])
[s1,ign1,s3,ign2] = size(a4d)
a2d = reshape(permute(a4d,[1 3 2 4]),s1*s3,[])
Image Analyst
on 27 Oct 2011
One way to do it is to create your 2D array at the same time as you created your 4D array - inside your 4 nested for loops that you already have. Use a counter, like "row"
row = 1;
array2D = zeros(10*11*12*13, 1); % Preallocate
for d1 = 1:10
for d2 = 1:11
for d3 = 1:12
for d4 = 1:13
% Create your 4D array
array4D(d1,d2,d3,d4) = theValue;
% Now create your 2D array
array2D(row, 1) = d1;
array2D(row, 2) = d2;
array2D(row, 3) = d3;
array2D(row, 4) = d4;
array2D(row, 5) = theValue;
% Now increment the row number
row = row + 1;
end
end
end
end
Oliver
on 27 Oct 2011
0 votes
1 Comment
Fangjun Jiang
on 27 Oct 2011
Certainly. Just write nested for-loops. It depends on the order you want, right. The easiest way doesn't require any loop. For example, a=rand(2,3,4,5); b=a(:).
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!