Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.


Jos
Posts:
1,267
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>... > 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 forloop 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)) ; % preallocation!! 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 runlength 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:end1)+1) = 1 ind2 = cumsum(ind2) output2 = val(ind2)
~ Jos



