Matlab矢量化矢量创建

罗嫩基

我想向量化以下向量的创建:

例如-设A一个向量[5 3 2 1],设B为一个向量[1 2 3 4]

我想C成为载体[1 1 1 1 1 2 2 2 3 3 4]

含义-中的每个元素iB中重复了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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章