Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: reduce computation time for using a matrix with nan
Replies: 1   Last Post: Nov 15, 2012 9:29 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Steven Lord

Posts: 17,944
Registered: 12/7/04
Re: reduce computation time for using a matrix with nan
Posted: Nov 15, 2012 9:29 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply



"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 non-nans 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)^3-3*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




Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.