1

I want to create a function_handle using an anonymous function for the following:

f(x,y) = 1, if 2 <= x <= 3 and y = 1,
f(x,y) = 0, otherwise

I thought I could just do:

f @(x,y) 1.*((x >= 2) && (x <= 3) & (y == 1));

When I try to evaluate this function by: f(ones(3,1),ones(3,1)), I get the error:

Operands to the || and && operators must be convertible to logical scalar values.

I also noticed that my function seems to work fine when I only input scalar x and y. My question is: How do I correctly define my function handle so that it works for vectors/arrays?

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
ddddDDDD
  • 23
  • 3

1 Answers1

1

You need a single & here if you intend to use x and y as vectors/matrices of the same dimensions.

f = @(x,y) (x>=2) & (x<=3) & (y==1);  %Multiplying by 1 is also not needed here

Recommended reading: What's the difference between & and && in MATLAB?

Community
  • 1
  • 1
Sardar Usama
  • 19,536
  • 9
  • 36
  • 58