Including masking condition (NaN assignment) in anonymous function definition
5 views (last 30 days)
Show older comments
If I want to mask some part of the plot (for example points located inside unit disk) I can use the following code:
[X,Y] = meshgrid(-6:.1:6) ;
[T,R] = cart2pol(X,Y) ;
f = @(t,r) r .* cos(t) ;
Z = f(T,R) ; % (*)
Z( R< 1 ) = NaN ; % (*)
figure, surfc(X,Y,Z)
Is it possible to include the masking commands directly into anonymous function definition in order to avoid definition of auxiliary variable Z (lines with (*) ).
In my first attempt I followed the pattern of defining piece-wise continuous functions. Something like this
g = @(t,r) (r<2) .* (r .* cos(t) ) + (r>=2) .* NaN ;
figure, surfc(X,Y, g(T,R) )
However, this code does not work because function g will always return NaN. How can it be done?
0 Comments
Accepted Answer
Rik
on 2 Dec 2021
0/0
You can use this to your advantage:
[X,Y] = meshgrid(-6:.1:6) ;
[T,R] = cart2pol(X,Y) ;
NaN_if_true_one_if_false=@(tf) (1-tf)./(1-tf);
g = @(t,r) (r .* cos(t) ) .* NaN_if_true_one_if_false(r<1);
surfc(X,Y,g(T,R))
%repeat original
f = @(t,r) r .* cos(t) ;
Z = f(T,R) ; % (*)
Z( R< 1 ) = NaN ; % (*)
figure, surfc(X,Y,Z)
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!