简体   繁体   English

arrayfun到bsxfun可能

[英]arrayfun to bsxfun possible

I know that bsxfun(which works fast!) and arrayfun(as far as I could understand, uses loops internally which is expected to be slow) are intended for different uses, at least, at the most basic level. 我知道bsxfun(工作很快!)和arrayfun(据我所知,内部使用循环(预期会很慢))至少在最基本的层面上适合不同的用途。

Having said this, I am trying 话虽如此,我正在尝试

  1. to sum up all the numbers in a given array, say y, before a certain index 在给定索引之前,将给定数组(例如y)中的所有数字相加
  2. add the number at the specific location(which is the number at the above index location) to the above sum. 将特定位置的数字(即上述索引位置的数字)与上述总和相加。

I could perform this with the below piece of example code easily: 我可以使用下面的示例代码轻松执行此操作:

% index array
x = [ 1:6 ]; % value array
y = [ 3 3 4 4 1 1 ];
% arrayfun version
o2 = arrayfun(@(a) ...
              sum(y(1:(a-1)))+...
              y(a), ...
              x)

But it seems to be slow on large inputs. 但是,对于大的投入,这似乎很慢。

I was wondering what would be a good way to convert this to a version that works with bsxfun, if possible. 我想知道将它转换为与bsxfun兼容的版本的好方法是什么。

PS the numbers in y do not repeat as given above, this was just an example, it could also be [3 4 3 1 4 ...] PS y中的数字不像上面给出的那样重复,这只是一个例子,也可能是[3 4 3 1 4 ...]

Is x always of the form 1 : n? x是否总是形式为1:n? Assuming the answer is yes, then you can get the same result with the much faster code: 假设答案是肯定的,那么您可以通过更快的代码获得相同的结果:

o2 = cumsum(y);

Side note: you don't need the brackets in the definition of x. 旁注:x的定义中不需要括号。

if you have a supported GPU device, you can define your variables as gpuArray type since arrayfun, bsxfun and pagefun are compatible with GPUs. 如果您具有受支持的GPU设备,则可以将变量定义为gpuArray类型,因为arrayfun,bsxfun和pagefun与GPU兼容。 GPU computing is supposed to be faster for large data. 对于大数据,GPU计算应该更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM