SQL like question.

Bill Denney bill at denney.ws
Fri Sep 5 16:25:36 CDT 2008


Moved from the maintainers list.

Levente Torok wrote:
> Hi All,
>
> Last time Jaroslav helped me a lot with a little trick but this time I am a little bit jammed.
>
> I would like to get solved a simple thing again and I cannot find a fast solution to it.
>
> I have a matrix as
> m = [
> 1 2; 
> 1 1; 
> 2 3; 
> 2 4 ];
>
> I would like to make a unique of its first column but I would like to have the minimum of second column nearby.
> So it would look like:
> [ 1 1; 
>   2 3 ]
>
> This is something like SELECT first_col, min(second_col) FROM m GROUP BY first_col;
>
> If I can be sure that the second nargout of unique() always points always to the last index of the same 
> selector item then the solution would be something like:
>
> m = sort( m, 'descend' );
> [u,i,j] = unique( m(:,1) );
> m(i,:)
>
> but 
> 1) can I be sure about it?
> 2) what if I would want to make aggregate functions such as avg()  or var()
A way to be certain of this would be:

m = [1 2; 1 1; 2 3; 2 4];
u = unique (m(:,1))(:);
for i = 1:numel (u)
  u(i,2) = min (m(m(:,1) == u(i),2));
endfor

And you can substitute any function you want for min.  That may not be
the most efficient way to do it, but it's not too bad.

Have a good day,

Bill


More information about the Help-octave mailing list