How do you convert a 4D matrix into a N by M

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)

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

The PERMUTE command might be helpful in addition.

Sign in to comment.

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,[])
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
Oliver on 27 Oct 2011
Maybe my approach is wrong....is there a way of creating a nested for loop and getting an output strainght to a vector?

1 Comment

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(:).

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 26 Oct 2011

Community Treasure Hunt

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

Start Hunting!