arrayfun to bsxfun possible

95 views Asked by At

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.

Having said this, I am trying

  1. to sum up all the numbers in a given array, say y, before a certain index
  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.

P.S. the numbers in y do not repeat as given above, this was just an example, it could also be [3 4 3 1 4 ...]

2

There are 2 answers

1
verbatross On

Is x always of the form 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.

0
Baback Kh On

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 computing is supposed to be faster for large data.