removing inner for loop
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
Andrei Bobrov
on 11 Apr 2012
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 Comments
More Answers (1)
Sargondjani
on 11 Apr 2012
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 Comments
See Also
Categories
Find more on Matrix Indexing 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!