help-octave
[Top][All Lists]

## Re: Increase efficiency of nested loops that use str2double and datenum

 From: Bill Denney Subject: Re: Increase efficiency of nested loops that use str2double and datenum functions? Date: Mon, 08 Dec 2008 07:47:57 -0500 User-agent: Thunderbird 2.0.0.18 (Windows/20081105)

```Jared Stofflett wrote:
> The following code operates on a cell matrix obtained using the sqlite3
> package. It takes several minutes to run with a matrix containing about
> 20000
> rows. The bottlenecks appear to be the datenum and str2double
> functions. Any help on increasing it's efficiency would be appreciated.
>
> DJI2=0;
> for i=1:length(DJI)
> DJI2(i,1)=datenum(char(DJI(i,2)),'yyyy-mm-dd');
> for j=3:7
> DJI2(i,j-1)=str2double(char(DJI(i,j)));
> end
> end
>

Hi Jared,

Sorry that I don't have time for a full answer now, but I would
investigate str2num (which is vectorized) and cellfun.  I don't recall
off the top of my head how to use cellfun with an additional argument,
but for the str2double, you should be able to do something like

DJI2(:,2:6) = str2num(DJI(:,3:7));

That would replace the second loop and move the statement outside of the
loop.

If that doesn't work, you can do something like

DJI2(:,2:6) = reshape(str2num(strvcat(DJI(:,3:7)(:)), size(DJI(:,3:7)));

or using cellfun:

DJI2(:,2:6) = cellfun(@str2double, DJI(:,3:7));

Thanks,

Bill

```