From: Anthony on 13 May 2010 21:49 Hey, I am trying to get rid of this loop and possibly use of logical indexing to make this more efficient. for i=1:length(Returns) if(Returns(i,:) > 0) BothPos(i,1) = 1; else BothPos(i,1) = 0; end end BothPos = sum(BothPos); I have a matrix of returns "Returns". And I want to count only if both elements in each row are > 0. Any ideas on how to do this without an if/else. Thanks Anthony
From: Walter Roberson on 13 May 2010 22:07 Anthony wrote: > I am trying to get rid of this loop and possibly use of logical indexing > to make this more efficient. > for i=1:length(Returns) > if(Returns(i,:) > 0) > BothPos(i,1) = 1; > else > BothPos(i,1) = 0; > end > end > BothPos = sum(BothPos); > I have a matrix of returns "Returns". And I want to count only if both > elements in each row are > 0. Any ideas on how to do this without an > if/else. The whole can be done quite compactly: sum(all(Returns,2));
From: Anthony on 13 May 2010 23:56 That doesn't seem to work on my matrix. Perhaps I wasn't clear enough in my explanation. Returns is 252x2. If Returns(i,1) and Returns(i,2) are both > 0 then I want to count. Do this for all the rows and at the end have just the # of times this condition is satisfied. In loop form again: for i=1:length(Returns) if(Returns(i,:) > 0) BothPos(i,1) = 1; else BothPos(i,1) = 0; end end BothPos = sum(BothPos); Thanks again Anthony
From: Walter Roberson on 14 May 2010 01:00 Anthony wrote: > That doesn't seem to work on my matrix. Perhaps I wasn't clear enough in > my explanation. > > Returns is 252x2. If Returns(i,1) and Returns(i,2) are both > 0 then I > want to count. Do this for all the rows and at the end have just the # > of times this condition is satisfied. Yup, my code would do exactly that. %setup >> Returns = rand(252,2) > 0.7; %the code >> sum(all(Returns,2)) 22 %cross-check >> sum(Returns(:,1) & Returns(:,2)) ans = 22 %after running your code: >> BothPos BothPos = 22
From: Bruno Luong on 14 May 2010 01:57
"Anthony " <antfarinaccio(a)gmail.comremove.spam> wrote in message <hsihkj$blf$1(a)fred.mathworks.com>... > That doesn't seem to work on my matrix. Perhaps I wasn't clear enough in my explanation. > You should modify Walter's command to sum(all(Returns>0,2)) Bruno |