Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


Math Forum » Discussions » Software » comp.soft-sys.matlab

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Jos

Posts: 1,266
Registered: 10/24/08
Re: vectorizing
Posted: Mar 15, 2013 3:24 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

"Natalia " <menna@leeds.ac.uk> wrote in message <khtm32$csr$1@newscl01ah.mathworks.com>...
> Thanks in advance.
>
> 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
Read Re: vectorizing
Jos
3/15/13
Read Re: vectorizing
Bruno Luong

Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.