Assigning a Matlab vector according to a function

2019-09-02 12:14发布

问题:

I basically want to vectorize the following:

vect_y = zeros(1,numel(vect_x);
for i = 1:numel(vect_x)
    vect_y = sum(vect_x(1:i));
end

Is this possible? As an example, I was trying to use arrayfun the following way:

y = arrayfun(@(y) sum(y), vect_x(1:1), vect_x(1:2), ..., vect_x(1:n));

But this won't work and it's not clean.

edit: So I know now that cumsum solves the above, but I am curious as to how I would do this for any function.

回答1:

What you want can be done with the cumsum function directly:

vect_y = cumsum(vect_x);