help-octave
[Top][All Lists]
Advanced

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

Re: Yet Another Vectorization Quiz


From: bpabbott
Subject: Re: Yet Another Vectorization Quiz
Date: Tue, 14 Dec 2010 22:39:10 +0000 (GMT)

On Dec 14, 2010, at 05:12 PM, Carlo de Falco <address@hidden> wrote:

Hi all,

I need to shift all the zeros in a (possibly very large) matrix
to the end of each column without changing the ordering of the
remaing elements, e.g.:

a = [ 1 2 4 0 [ 1 2 4 6
2 3 5 6 ==> 2 3 5 7
3 0 0 7 3 4 6 0
0 4 6 0] 0 0 0 0]

with a for loop this can be done as

for j = 1:columns (a)
v = zeros (rows (a), 1);
v(1:nnz (a(:, j))) = a(a(:, j) != 0, j);
a(:, j) = v;
endfor

I personally see no obvious way to improve this,
does anyone have any idea?

Thanks,
c.

a = [1 2 4 0;2 3 5 6; 3 0 0 7; 0 4 6 0];

a =

   1   2   4   0
   2   3   5   6
   3   0   0   7
   0   4   6   0

Two lines?

[~, n] = sort (a==0);
a = a (ones (size (a, 1), 1) * (0:size (a, 2) - 1) * 4 + n)

ans =

   1   2   4   6
   2   3   5   7
   3   4   6   0
   0   0   0   0

You can't tell from the result, but this is designed to not sort the entries non-zero values. Consider a small modification to "a"

a = [3 2 4 0;2 3 5 6; 1 0 0 7; 0 4 6 0]
a =

   3   2   4   0
   2   3   5   6
   1   0   0   7
   0   4   6   0

[~, n] = sort (a==0);
a (ones (size (a, 1), 1) * (0:size (a, 2) - 1) * 4 + n)
ans =

   3   2   4   6
   2   3   5   7
   1   4   6   0
   0   0   0   0

Ben


reply via email to

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