I have a function handle that operates on 2d arrays of arbitrary size:
R2T = @(DL1,DL2) arrayfun(@(DL1,DL2)...
1/(fzero(@(x)fFitObj1(x)./fFitObj2(x)-...
DL1./DL2,[minLim maxLim])) ...
,DL1,DL2) - C1;
Here's a bottom-up breakdown of what it does:
fzero(@(x)fFitObj1(x)./fFitObj2(x)-DL1./DL2,[minLim maxLim])
- This bit looks for a zero of the considered function on the interval[minLim maxLim]
, wherefFitObj1
andfFitObj2
are function handles available from before,C1
is some known constant andDL1, DL2
are provided.@(DL1,DL2)1/(fzero(...))
- a wrapper forfzero
that allowsDL1
andDL2
to be provided from outside.arrayfun(@(DL1,DL2)...,DL1,DL2)
- another wrapper which allowsfzero
to correctly operate element-by-element whenDL1, DL2
are provided as a matrix.R2T = @(DL1,DL2) arrayfun(...) - C1;
- yet another wrapper that allows to provideDL1, DL2
from outside.
My problem is that sometimes the matrices DL1, DL2
may contain NaN
values, in which case fzero
returns the following error:
Error using fzero (line 242)
Function values at interval endpoints must be finite and real.
This is why I naturally thought of the available operations with short-circuiting, so I tried to incorporate a any(isnan([DL1,DL2]))
into this so that fzero
won't even be evaluated if its inputs would be NaN
- but whatever I try (e.g. a custom-made ternary operator) the fzero
seems to be evaluated and the code errors.
The desired result: I'd like to implement a lazy evaluation of the fzero
to only occur when the inputs are valid (in this case, not NaN
), and return NaN
otherwise as demonstrated in the Edit below.
Related resources:
Edit:
Here's a piece of code that illustrates the problem (MATLAB 2014a):
clear variables; clc;
LIM = [0 5];
fFitObj1 = @(x)x.^2; fFitObj2 = @(x)1;
C1 = 100;
[DL1A,DL2A,DL1B] = deal(ones(2));
DL1B(4) = NaN; DL2B = DL1B;
R2T = @(DL1,DL2) arrayfun(@(DL1,DL2)...
1/(fzero(@(x)fFitObj1(x)./fFitObj2(x)-...
DL1./DL2,LIM)) ...
,DL1,DL2) - C1;
R2T(DL1A,DL2A) %//case A, runs fine
%{
// ans =
//
// -99 -99
// -99 -99
%}
R2T(DL1B,DL2B) %//case B, errors due to NaN
%{
// Error using fzero (line 242)
// Function values at interval endpoints must be finite and real.
//
// Error in @(DL1,DL2)1/(fzero(@(x)fFitObj1(x)./fFitObj2(x)-DL1./DL2,LIM))
//
//
// Error in @(DL1,DL2)arrayfun(@(DL1,DL2)1/(fzero( .....
%}
The desired result, in case B is:
ans =
-99 -99
-99 NaN
.m
file instead? – Byelaw.m
files are more flexible than anonymous functions, so it must be possible (the process of capturing variables via arguments may be less elegant, but you can useif
-else
as well astry
catch
, which would be a huge benefit in this case) – Byelawarrayfun
with something faster too. – JennyfFitObj1
,minLim
,...) – ByelawminLim
andmaxLim
) in the current scope, just like an anonymous function can. But it also can use normal statement blocks, it doesn't have to be just one single expression. – Absinthism