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.

 채택된 답변

Matt J
Matt J 2021년 3월 21일
편집: Matt J 2021년 3월 21일
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.
Matt J
Matt J 2021년 3월 21일
편집: Matt J 2021년 3월 21일
No, there is no generic vectorization technique. You could make a lookup table, perhaps.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Matt J
Matt J 2021년 3월 21일
편집: Matt J 2021년 3월 21일
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에 대해 자세히 알아보기

태그

질문:

2021년 3월 21일

편집:

2021년 3월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by