matlab constant anonymous function returns only one value instead of an array

前端 未结 2 720
臣服心动
臣服心动 2021-01-29 12:54

I\'ve been searching the net for a couple of mornings and found nothing, hope you can help.

I have an anonymous function like this

f = @(x,y) [sin(2*pi*x         


        
2条回答
  •  粉色の甜心
    2021-01-29 13:06

    Defining an anonymous function f as

    f = @(x,y) [0,1];
    

    naturally returns [0,1] for any inputs x and y regardless of the length of those vectors.

    This behavior puzzled me also until I realized that I expected f(a,b) to loop over a and b as if I had written

    for inc = 1:length(a)
        f(a(inc), b(inc))
    end
    

    However, f(a,b) does not loop over the length of its inputs, so it merely returns [0,1] regardless of the length of a and b.

    The desired behavior can be obtained by defining f as

    g=@(x,y)[zeros(size(x)),ones(size(y))]
    

    as Daniel stated in his answer.

提交回复
热议问题