Assigning a Matlab vector according to a function

2019-09-02 12:18发布

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条回答
可以哭但决不认输i
2楼-- · 2019-09-02 12:39

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

vect_y = cumsum(vect_x);
查看更多
登录 后发表回答