Converting 4D matrix to 2D with multiple for-loop

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.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 2월 17일
편집: Andrei Bobrov 2016년 2월 17일
X = randi(100,10,100,10,100);
A = randi(20,10,100);
[k,l,m,n] = size(X);
z = bsxfun(@times,X,A);
out = reshape(sum(reshape(z,k*l,1,m,n),1),m,n);
or
out = squeeze(sum(reshape(z,k*l,1,m,n)));

댓글 수: 3

+1 very nice
Thank you Stephen!
James Choi
James Choi 2016년 2월 18일
편집: James Choi 2016년 2월 18일
Fantastic code!! Thank you so much.
This is much simpler than my code and also its performance is absolutely better than for loop.
You really help me improve entire calculation efficiency.
I think someone who want to optimize such as fmincon, they should use bsxfun and reshape.
Thank you again.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

John BG
John BG 2016년 2월 17일
편집: John BG 2016년 2월 19일
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

Thank you for your kind explanation. It really help me understand how matlab code works.
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
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);
Thanks Andrei

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2016년 2월 17일

댓글:

2016년 2월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by