3
$\begingroup$

I want to write the following anonymous function in MATLAB.

I have a piecewise function. I want to turn this into a single expression. How can this be accomplished in MATLAB ?

$$f(x,t) = \begin{cases} 20e^{-4x^2} & \text{if $0 \leq t \leq T/2,$} \\ 0 & \text{otherwise.} \end{cases}$$

$\endgroup$
4
$\begingroup$
T = 1.0;
f = @(x,t) (0 <= t & t <= T/2)*20*exp(-4*x.^2) + 0.0;
x = linspace(0,1,100);
plot(x, f(x,T/4), x, f(x,T))
legend('t=T/4','t=T')
$\endgroup$
4
  • $\begingroup$ How can you initialise T to be 1 ? T can be anything. $\endgroup$
    – user36184
    Nov 10 '20 at 6:35
  • $\begingroup$ Set T to whatever you want. I just gave an example. $\endgroup$
    – cfdlab
    Nov 10 '20 at 6:47
  • 6
    $\begingroup$ To enable vectorization with respect to t, you'll need f = @(x,t) (0 <= t & t <= T/2)*20*exp(-4*x.^2) + 0.0;, that is, logical and without short-circuiting (& instead of &&). $\endgroup$
    – cos_theta
    Nov 10 '20 at 13:24
  • $\begingroup$ @cos_theta Thanks I didnt know this, I updated the answer. $\endgroup$
    – cfdlab
    Nov 13 '20 at 3:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy