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.

 Risposta accettata

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 Commenti

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.
Matt J
Matt J il 21 Mar 2021
Modificato: Matt J il 21 Mar 2021
No, there is no generic vectorization technique. You could make a lookup table, perhaps.

Accedi per commentare.

Più risposte (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.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by