Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
vectorizing

Subject: vectorizing

From: Natalia

Date: 14 Mar, 2013 23:22:10

Message: 1 of 3

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!

Subject: vectorizing

From: Jos (10584)

Date: 15 Mar, 2013 07:24:05

Message: 2 of 3

"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

Subject: vectorizing

From: Bruno Luong

Date: 15 Mar, 2013 08:11:11

Message: 3 of 3

ind = [1, 25, 50, 70, 100, 110]
val = [1 2 4 6 10 ]

a = zeros(1, ind(end));
a(ind(1:end-1)+1) = diff([0 val]);
a = cumsum(a)

% Bruno

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us