Converting 4D matrix to 2D with multiple for-loop
Show older comments
Hello, I'm trying to convert 4D matrix to 2D matrix instead of for-loop.
Here is my code.
X = randi(10,100,10,100);
A = ones*(10,100);
SUM = zeros(10,100);
for k=1:10
for l=1:100
for m=1:10
for n=1:100
SUM(m,n) = SUM(m,n) + A(k,l) * X(k,l,m,n);
end
end
end
end
I want to know how to change 4D to 2D for simpler calculation without for-loops. Thank you.
Accepted Answer
More Answers (1)
1.- your first command
randi(10,100,10,100)
does not generate a 4D matrix, but 3D the first input field of randi is the range [1:10] within the output values fall within. 4D would be
X=randi(10,10,100,10,100)
2.- reshaping matrices is fairly simple with command reshape
[s1,s2,s3,s4]=size(X)
Total=s1*s2*s3*s4
to a square matrix
X2=reshape(X,[Total^.5,Total^.5])
or to
X3=reshape(X,[10,Total/10])
3.- However, your 4 for loops do more than 'reshaping'. You take a slice of X, multiply it by A, and then cumulatively sum it, don't you?
check if the following 2 for loops are ok:
X=randi(10,10,100,10,100)
A = ones(10,100)
[s1,s2,s3,s4]=size(X)
SUM = zeros(s3,s4)
for m=1:s3
for n=1:s4
X2=X(:,:,m,n)
X3=A.*X2
SUM = SUM+ X3
end
end
If this answer helps in any way to solve your question please click on the thumbs-up vote link above, thanks in advance
John
4 Comments
James Choi
on 18 Feb 2016
John BG
on 19 Feb 2016
Just compared the result from the really compact squeeze answer, and the 2 for loops answer, and they do not seem to be the same,

which one is correct?
John
Andrei Bobrov
on 19 Feb 2016
Hi John! Simple example:
X = randi(20,4,5,3,2);
A = randi(20,4,5);
SUM = zeros(3,2);
for k=1:4
for l=1:5
for m=1:3
for n=1:2
SUM(m,n) = SUM(m,n) + A(k,l) * X(k,l,m,n);
end
end
end
end
[k,l,m,n] = size(X);
z = bsxfun(@times,X,A);
out = reshape(sum(reshape(z,k*l,1,m,n),1),m,n);
John BG
on 19 Feb 2016
Thanks Andrei
Categories
Find more on Logical 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!