Including masking condition (NaN assignment) in anonymous function definition

3 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Rik
Rik il 2 Dic 2021
0/0
ans = NaN
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)

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by