Assigning a Matlab vector according to a function

懵懂的女人 提交于 2020-01-17 04:15:29

问题


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);


来源:https://stackoverflow.com/questions/28649272/assigning-a-matlab-vector-according-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!