2

I would like to vectorize the creation of the following vector:

For example- Let A be a vector [5 3 2 1] And let B be a vector [1 2 3 4]

I would like C to be the vector [1 1 1 1 1 2 2 2 3 3 4]

Meaning- each element i in B is duplicated A(i) times in C.

I haven't found a way to vectorize the creation of this, any ideas?

Thanks in advance!

Ronen

Divakar
  • 218,885
  • 19
  • 262
  • 358
RonenKi
  • 370
  • 4
  • 11
  • as well as this one: http://stackoverflow.com/questions/1975772/matlab-array-manipulation (and many other linked ones) – Amro Nov 09 '14 at 14:18

1 Answers1

3

Approach #1

Here's one approach if B doesn't have any zeros -

C = nonzeros(bsxfun(@times,bsxfun(@le,[1:max(A)]',A),B))

Approach #2

A general case solution -

mask = bsxfun(@le,[1:max(A)]',A) %//'
B_ext = bsxfun(@times,mask,B)
C = B_ext(mask)

Approach #3

cumsum based approach and must be pretty efficient one -

idx = [1 cumsum(A(1:end-1))+1] %// indices where each new B values start
C = zeros(sum(A),1) %// storage for output
C(idx) = diff([0 B]) %// put those values, but offseted
C = cumsum(C) %// finally get the output
Divakar
  • 218,885
  • 19
  • 262
  • 358