我想将以下向量的创建向量化:
例如-设A
一个向量[5 3 2 1]
,设B为一个向量[1 2 3 4]
我想C
成为载体[1 1 1 1 1 2 2 2 3 3 4]
含义-中的每个元素i
在B
中重复了A(i)
一次C
。
我还没有找到一种矢量化此方法的方法,有什么想法吗?
提前致谢!
罗嫩
方法#1
如果B
没有,这是一种方法zeros
-
C = nonzeros(bsxfun(@times,bsxfun(@le,[1:max(A)]',A),B))
方法#2
一般情况下的解决方案-
mask = bsxfun(@le,[1:max(A)]',A) %//'
B_ext = bsxfun(@times,mask,B)
C = B_ext(mask)
方法#3
cumsum
基于方法,并且必须非常有效-
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句