removing inner for loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 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 Kommentare
Weitere Antworten (1)
Sargondjani
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!