help-octave
[Top][All Lists]
Advanced

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

Re: remove for-loop from following code


From: Juan Pablo Carbajal
Subject: Re: remove for-loop from following code
Date: Sun, 6 Nov 2011 09:07:09 +0100

On Sat, Nov 5, 2011 at 3:16 PM, Stefaan Himpe <address@hidden> wrote:
> Hello all,
>
> I have a question about optimizing my code.
>
> I start from Y = [ 1 ; 3; 2 ]
> I want to end up with Ytr = [ 1 0 0 0 ; 0 0 1 0 ; 0 1 0 0 ]
> (so the number in Y indicates the column in which I want to see a one; the
> number of elements in each row can is given in the following code as a
> parameter D)
>
> For now I do the following
>
> function [Ytr] = ytransform(D, Y)
>  [rows, cols] = size(Y);
>  for row = 1:rows
>    Ytr(:,row) = (1:D == Y(row));
>  endfor
> endfunction
>
> Is there a way to do implement this without for loop over all rows of Y?
>
> Best regards & thanks for this wonderful software.
> Stefaan.
>
> _______________________________________________
> Help-octave mailing list
> address@hidden
> https://mailman.cae.wisc.edu/listinfo/help-octave
>

Try,
N = lenth(Y);
subs = [(1:N).' Y(:)];
Ytr = accumarray (subs, ones(N,1));

It may be buggy. I do not have Octave with me right now (and my Sage
notebook doesn't want to run that code.). Definitely accumarray is a
function that can do what you want.

-- 
M. Sc. Juan Pablo Carbajal
-----
PhD Student
University of Zürich
http://ailab.ifi.uzh.ch/carbajal/


reply via email to

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