a for loop question

1 view (last 30 days)
YI Hsu Lo
YI Hsu Lo on 12 Dec 2012
i have 2 variables and 5 eqautions
i would like to present them in the form
X ( : , : , 1 ) = xx( : , : , 1 , 1 ) + xx ( : , : , 2 , 1 ) + xx ( : , : , 3 , 1 ) + xx ( : , : , 4 , 1 ) + xx ( : , : , 5 , 1 )
X ( : , : , 2 ) = xx ( : , : , 1 , 2 ) + xx ( : , : , 2 , 2 ) + xx ( : , : , 3 , 2 ) + xx ( : , : , 4 , 2 ) + xx (: , : , 5 , 2 )
. . . . . . .
and my method is really stupid:
for m=1:5;
xx (:,:,m,1)=sum(eh(:,:,1)./eh(:,:,m).*log((e(:,:,m+1)-z(:,:,1))./(e(:,:,m)-z(:,:,1))),3);
xx(:,:,m,2)=sum(eh(:,:,2)./eh(:,:,m).*log((e(:,:,m+1)-z(:,:,2))./(e(:,:,m)-z(:,:,2))),3);
xx(:,:,m,3)=sum(eh(:,:,3)./eh(:,:,m).*log((e(:,:,m+1)-z(:,:,3))./(e(:,:,m)-z(:,:,3))),3);
xx(:,:,m,4)=sum(eh(:,:,4)./eh(:,:,m).*log((e(:,:,m+1)-z(:,:,4))./(e(:,:,m)-z(:,:,4))),3);
xx(:,:,m,5)=sum(eh(:,:,5)./eh(:,:,m).*log((e(:,:,m+1)-z(:,:,5))./(e(:,:,m)-z(:,:,5))),3);
end;
for j=1:5;
X ( : , : , j ) = sum ( xx ( : , : , : , j ) , 3 ) ;
end;
how could i construct a for loop to shorten the code?
it seems very easy but somehow it confuse me! could someone answer me please!
and if there's some 'syms' in the equations, can i use the same method?

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 12 Dec 2012
Edited: Azzi Abdelmalek on 12 Dec 2012
xx=rand(5,5,5,3);
[n1,n2,n3,n4]=size(xx);
X=zeros(n1,n2,n4);
for k=1:n4
X(:,:,k)=0;
for l=1:n3
X(:,:,k)=X(:,:,k)+xx(:,:,l,k)
end
end
  1 Comment
YI Hsu Lo
YI Hsu Lo on 12 Dec 2012
excuse me i didn't catch your answer
my 'xx' is a matrix that use those variable 'eh' ,'z' etc.
so i still have to construct the xx term by term?
i apologize if i ask a stupid question

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!