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!