How do I vectorize a function with intermediate range vector
显示 更早的评论
This is my function:
function result = my_function(a)
n = [-a:1:a];
result = sum(n .^ 2);
end
It works when the input argument is an integer, but I would like it to work in cases like this:
my_input = [1, 2, 3];
% This works as expected:
my_output = arrayfunc(@my_function, my_input);
% my_output is [2, 10, 28]
% This currently doesn't produce the desired output:
my_output1 = my_function(my_input);
% my_output is 2, but should be the same as above.
采纳的回答
更多回答(1 个)
Maybe this is what you had in mind:
my_function([1,2,3])
function result = my_function(a)
result = arrayfun( @(n)sum((-n:n).^ 2) , a);
end
This hides arrayfun() from the user, but doesn't have the execution speed advantages of a truly "vectorized" implementation.
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!