Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: vectorizing
Replies: 2   Last Post: Mar 15, 2013 4:11 AM

 Messages: [ Previous | Next ]
 Jos Posts: 1,268 Registered: 10/24/08
Re: vectorizing
Posted: Mar 15, 2013 3:24 AM

"Natalia " <menna@leeds.ac.uk> wrote in message <khtm32\$csr\$1@newscl01ah.mathworks.com>...
>
> I have a list of indexes ( 1, 25, 50, 70, 100, 110) and a list of values to assign ( 1 2 4 6 10 )
> ( Please note there are not regular patterns of any kind neither for indexes or the values to assign.
>
> I would like my output to be:
> output(1:25) = 1;
> output(26:50) = 2;
> output(51:70) = 4;
> output(71:100) = 6;
> output(101:110) = 10;
>
> is there a way of vectorizing this??
> I don't want to go into a loop. My lists are of hunders of thousands values.
> thanks!

Note that a clever for-loop is fast, and much easier to understand and maintain

ind = [1 3 8 11 15 20] ;
val = [1 2 4 6 10] ;

output = zeros(1,ind(end)) ; % pre-allocation!!
if ind(1)==1, ind(1)=0 ; end % special case!!
for k = 1:numel(ind)-1,
output(ind(k)+1:ind(k+1)) = val(k) ;
end

If you insist, take a look at one of the run-length decoders available on the File Exchange, or write one yourself, like:

ind = [1 3 8 11 15 20] ;
val = [1 2 4 6 10] ;
ind2 = zeros(1,ind(end))
if ind(1)==1, ind(1)=0 ; end % special case!!
ind2(ind(1:end-1)+1) = 1
ind2 = cumsum(ind2)
output2 = val(ind2)

~ Jos

Date Subject Author
3/15/13 Jos
3/15/13 Bruno Luong