我有两个向量r
,d
我想知道在r<d(i)
哪里的次数i=1:length(d)
。
r=rand(1,1E7);
d=linspace(0,1,10);
到目前为止,我已经掌握了以下内容,但是还不够优雅:
for i=1:length(d)
sum(r<d(i))
end
这是R中的一个例子,但是我不确定这是否适用于Matlab:在一个向量中查找少于另一个向量中元素的数目
您可以将单例扩展与结合使用bsxfun
:比循环更快,更优雅,但也占用更多内存:
result = sum(bsxfun(@lt, r(:), d(:).'), 1);
bsxfun
由于隐式单例扩展,在最新的Matlab版本中可以删除:
result = sum(r(:)<d(:).', 1);
一种替代方法是将该histcounts
函数与以下'cumcount'
选项一起使用:
result = histcounts(r(:), [-inf; d(:); inf], 'Normalization', 'cumcount');
result = result(1:end-1);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句