removing inner for loop
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi all;
I have a matrix named "a" which must be multiplied by 4 different numbers for each index of "i". I want to do this without inner for loop "j".
For example like program below,for ' i=1' and 'j=1' , all elements of matrix ' a' must be multiplied by 'pr(1,1)'. This operation would be repeated up to 'j=4'. I want to omit 'j loop' in the way for each 'i' , all elements of 'a' multiplied by all columns of 'pr(i,:)' without for loop 'j'. In your opinion, how can I do this? This example was described below:
pr=[0.3 0.5 0.1 0.1; 0.2 0.5 0.2 0.1; 0.3 0.4 0.2 0.1;0.2 0.4 0.1 0.3]; a=[3,7,0,5,8;9,3,1,0,0;3,2,9,2,0;1,4,9,3,1;];
sum=0;
for i=1:4
for j=1:4
sum = sum + pr(i,j)*a;
end
end
Thaks,
댓글 수: 0
채택된 답변
Andrei Bobrov
2012년 4월 11일
sum1 = sum(bsxfun(@times,a,reshape(pr,1,1,[])),3)
OR
in this is case
b = unique(pr);
k = histc(pr(:),b);
sum1 = sum(bsxfun(@times,a,reshape(b.*k,1,1,[])),3)
댓글 수: 0
추가 답변 (1개)
Sargondjani
2012년 4월 11일
first: dont use 'i' and 'j' because they are sqrt(-1) and the imaginary part of an imaginary number. dont use 'sum' either, because its an operator as you will see next
you dont need any for loop:
total=sum(sum(pr))*a;
as x*a + y*a + z*a=(x+y+z)*a. If you want to keep the loop over i, then im sure you can figure that out yourself now...
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!