Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
NCTM or The Math Forum.



Re: reduce computation time for using a matrix with nan
Posted:
Nov 15, 2012 9:29 AM


"Skirt Zhang" <silence_qunzi@hotmail.com> wrote in message news:k824b5$civ$1@newscl01ah.mathworks.com... > Dear ALL, > > I have a matrix x(750,2000) got from a cell r{} with size (1*6)which has > the following format: > > 1 2 nan nan nan 4 5 6.... > 1 nan 2 nan 4 nan5 6.... > 4 5 2 nan 4 nan5 6.... > ... > 4 5 6 1 2 nan nan nan.... > nan 4 nan5 1 nan 2 6.... > 4 5 2 nan 4 nan5 6.... > I want to calculate a function for the nonnans on each row and then get > the mean value for the results of the functions (from matrix row > calculation). Below is my code: > > for i=1:length(r) > x=r{i} ; > > x2=nan(750,1); > for ii=1:size(x,1) > x1=x(ii,:); > x1=x1(~isnan(x1)); > if ~isempty(x1) > x2(ii,1)=(sum(x1)^33*sum(x1.^2)*sum(x1)+2*sum(x1.^3)); > end > > The problem is the computation time is huge since in one loop I need 1hour > to do so, but without this step it took me only 4min... Since I have 200 > loops to run reducing this step's computation time will be extremely > helpful, can anyone help me about this?
Use ISNAN on the whole matrix at once. Using that information for logical indexing, replace all the NaNs in x with 0's (since those will contribute 0 to the SUMs.) Call SUM on the resulting matrix and specify the dimension input. You don't need to use a loop at all.
 Steve Lord slord@mathworks.com To contact Technical Support use the Contact Us link on http://www.mathworks.com



