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.

 采纳的回答

my_input = [1, 2, 3];
my_function(my_input)
ans = 1×3
2 10 28
function result = my_function(n)
result = n.*(n + 1).*(2*n + 1)/3;
end

2 个评论

Sure, this works, but I was hoping for a more general anwser... I used sum in my example, but i would also need a similar solution to use with functions like int and such.
No, there is no generic vectorization technique. You could make a lookup table, perhaps.

请先登录,再进行评论。

更多回答(1 个)

Maybe this is what you had in mind:
my_function([1,2,3])
ans = 1×3
2 10 28
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!

Translated by