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!