help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: vectorization problem


From: Jordi Gutiérrez Hermoso
Subject: Re: vectorization problem
Date: Tue, 1 Nov 2011 18:23:22 -0400

On 1 November 2011 13:47, John W. Eaton <address@hidden> wrote:
> Is there an efficient way to replace all NaNs in each column of the
> following matrix by the last non-NaN value in the column?
>
> Example matrix:
>
>  M = [1   3   7
>       2   4   NaN
>       NaN 5   NaN
>       NaN 6   NaN];
>
> Desired result:
>
>      [1   3   7
>       2   4   7
>       2   5   7
>       2   6   7];

How about the following?

    nanpos = isnan (m);
    nancols = find (any (nanpos) & ! all (nanpos));

    if (any (nancols))
      [i, j] = find(nanpos);
      minrows = [i(1); i(find (diff (j)) + 1)]';

      ## If the whole column is nan, ignore it
      minrows(minrows == 1) = [];

      idx = sub2ind (size (m), minrows - 1, nancols);
      vals = m(idx);
      m(nanpos) = vals (lookup (nancols, j));
    endif

It seems faster on my machine and seems to have a smaller memory
footprint than the existing solution. It's fairly stingy about
creating large intermediate temporaries.

HTH,
- Jordi G. H.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]