is that possible to convert the use of arrayfun to bsxfun?

1 view (last 30 days)
Hi all,
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 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 Comments
Matt J
Matt J on 29 Oct 2017
Isn't sum(y(1:(a-1)))+y(a) the same thing as sum(y(1:a))? Why isolate y(a)?
Umut
Umut on 29 Oct 2017
you are right ;) I dont know why I left it this way. Basically, this is a code that I am trying to improve here and there which I wrote a long time ago. And this is an artifact of that. Indeed this might change the situation, let me check, thanks for pointing out this to me. Sometimes one can get too blind to see easy stuff :(

Sign in to comment.

Accepted Answer

Matt J
Matt J on 29 Oct 2017
Edited: Matt J on 29 Oct 2017
I think you're going to have better luck with,
z=cumsum(y);
o2=z(x)

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!