# How to write an 'if' script that changes a function depending on x?

2 visualizzazioni (ultimi 30 giorni)
Luqas Lundahl il 11 Mar 2022
Commentato: Luqas Lundahl il 11 Mar 2022
Hello!
I am trying to write a script that changes a function depending on the value of x.
sin(x) if x<=3
arctan(x) if 3<x<=7
e^-x if x<7
trying to only use 1 if statement!
function y=funk(x)
if
x <= 3;
y=sin(x);
else
(3<x) && (x>=7);
y=atan(x);
else
x>7;
y=e^(-x)
end
I'm not sure if i made a syntax error or the code is just plain wrong... Any help is appriciated!
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposte (2)

Johan il 11 Mar 2022
you need to use elseif for secondary condition in your if statement:
function y=funk(x)
if
x <= 3;
y=sin(x);
elseif
(3<x) && (x>=7);
y=atan(x);
else
x>7;
y=e^(-x)
end
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Luqas Lundahl il 11 Mar 2022
would i need to use else if on the second else as well?

Accedi per commentare.

Torsten il 11 Mar 2022
Modificato: Torsten il 11 Mar 2022
function y = funk(x)
if x <= 3
y = sin(x);
elseif (x > 3) && (x <= 7)
y = atan(x);
else
y = exp(-x);
end
end
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Luqas Lundahl il 11 Mar 2022
thank you!

Accedi per commentare.

### Categorie

Scopri di più su Resampling Techniques in Help Center e File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by