Define Matlab function depending from another function

155 Views Asked by At

I have a function $\phi(x,t)$ and I want to define a function $f$ whose values depend on $\phi$. Specifically:

$$f(x,t) = \begin{cases}6\phi(x,t)+1, & \text{if }\phi(x,t) < 0 \\ 2\phi(x,t), & \text{otherwise} \end{cases}$$

In Matlab I tried:

function g = f(x,t)  
if phi(x,t) < 0  
    g = 6*phi(x,t)+1;  
else   
    g = 2*phi(x,t);  
end

But it doesn't work. Any advice?

1

There are 1 best solutions below

1
On BEST ANSWER

Your code will only work if phi(x,t) returns a scalar. If it returns a non-scalar array, you'll get an error. And presumably if x and/or t is non-scalar then phi(x,t) will have the same dimensions? With that assumption, here is one way you can adapt your function:

function g = f(x,t)
pxt = phi(x,t);
g = zeros(size(pxt));
i0 = (pxt < 0);
g(i0) = 6*pxt(i0)+1;
g(~i0) = 2*pxt(~i0);