Using vector input to anonymous function

조회 수: 105 (최근 30일)
Abdulla Al-Mohannadi
Abdulla Al-Mohannadi 2015년 9월 11일
편집: Guillaume 2019년 9월 6일
If a have a function such as:
fptest = @(osf, T) T^2 - log(osf);
fpout(fptest, 2, 3, 4) %evaluates T in the end
In the first line, is it possible to input "osf" as a vector? For example, osf = [1 2 3] so that fpout evaluates fptest for values of T at osf = 1, 2, and 3 in 3 separate runs?
Thanks, Abdulla

채택된 답변

Guillaume
Guillaume 2015년 9월 11일
Anonymous functions are the same as regular functions (except they're restricted to one-liners with no branching or assignment). They accept any type of input argument of any size, scalar, vectors, arrays of numbers, structures, objects, etc. As long as the code of your function can deal with vectors, you can pass it a vector.
In your case, the anonymous function is already capable to handle vector osf since the only function that uses it, log, can:
>> fptest = @(osf, T) T^2 - log(osf);
>> fptest([1 2 3], 0)
ans =
0 -0.69315 -1.0986
Note that I would change the order of arguments, or the order of the formula in fptest, so that they match. It minimises the chance of you calling the function with the arguments reversed:
fptest = @(T, osf) T^2 - log(osf);
%or
fptest = @(osf, T) -log(osf) + T^2;

추가 답변 (1개)

Abdul Basith Ashraf
Abdul Basith Ashraf 2019년 9월 6일
>>y = @(x) 2.2*x/(1+1.2*x);
>>x = linspace(0,1);
>>y(x)
ans =
0.7398
In the above, I tried passing a vector 'x' to a function handle 'y'. I was expecting 'ans' to be a vector mapping each 'x' to 'y(x)' but it returned a single value. Why is that? Also help me out to get my vector output.
Thanks
  댓글 수: 1
Guillaume
Guillaume 2019년 9월 6일
편집: Guillaume 2019년 9월 6일
In the future, please start a new question of your own as you're definitivetly not answering the original question with your answer.
Your problem has nothing to do with function handles or anonymous functions. It's all to do with the fact that your doing a matrix division / which returns a scalar instead of an element-wise division ./ (which would return a vector).

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by