Logic Statements in Function Handle
6 views (last 30 days)
Show older comments
I am trying to perform a logic statement in a function handle, so that I can evaluate a function at a series of coordinates, then make decisions.
I have the following:
p --> an N x 2 Double array. Contains pairs of coordinates [x,y]
Fi --> a griddedInterpolant function. The coordinates in p fall within range and domain of the grid that was interpolated to obtain this (so they are compatible).
Fi2 --> a second griddedInterpolant function, derived from a second set of data more or less the same as in Fi.
Important point: the values that can be evaluated in Fi and Fi2 are partially mutually exclusive. If Fi is negative, the Fi2 must be positive, and the other way around. However, it is possible for both to be positive (there is a gap between them).
I've used this to make a function handles as follow:
fd=@(p) Fi(p);
fd2=@(p) Fi2(p);
These work just fine for calling later on and give nice sensible values when evaluated at p or sub-arrays of p.
Here's the tricky bit. I want to make a new function handle ("fh") that takes the evaluations of these functions at p, and then makes a step-change based on certain results for each individial p entry. Essentially, I want a function handle that does the work of an If statement. So, I tried to accomplish this by making 2 function handles for evaluating, and then treating them as logic statements, so I am multiplying by 1 or 0.
What I have tried (simplified), is this:
fha=@(p) (feval(fd,p));
fhb=@(p) (feval(fd2,p));
fh=@(p) max((fha<(0))*A, (fhb)<(0)*B, ((fha)>(0)*(fhb)>(0))*((A+B)/2));
This should be the equivalent of:
If fha < 0, then A; elseif fhb < 0, then B; else average of A and B
In other words, if a point within p has coordinates in a region where fd is negative, that point will have an associate value A. If it is in a position where fd2 is negative, it will be B. But if it falls in the regions where both evaluate to positive, its assigned value is the average of A and B.
I've also tried this nesting the feval statements into the fh call, and doing it as a single handle. Neither has worked. Is there a smart way to approach this, keeping in mind that I need to pass this handle to another function and then do lots of array manipulation stuff with it?
8 Comments
Paul
on 9 Jun 2023
You may be interested in this blog post that shows how to implement if-else construct via anonymous functions.
Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!