Effacer les filtres
Effacer les filtres

Hello, I'd like to define this function. Any help please?

1 vue (au cours des 30 derniers jours)
Catja Coetzee
Catja Coetzee le 1 Juin 2020
Commenté : madhan ravi le 1 Juin 2020
I tried making use of the if function:
function u1_problem(x)
x=1;
if x >= 1 && x <= 1.5
u1=@(x) 3.*(x-1);
end
if x > 1.5 && x <= 2
u1=@(x) 3-x;
end
if x > 2
return
end
x=x+1;
end
  2 commentaires
David Hill
David Hill le 1 Juin 2020
Is your function only defined from 1 to 2? Your function does not make any sense when x = 1.5.

Connectez-vous pour commenter.

Réponses (2)

Steven Lord
Steven Lord le 1 Juin 2020
A couple comments:
function u1_problem(x)
Your function doesn't return any values to its caller. So whatever variables you define inside the function are discarded when the function finishes its execution.
x=1;
This overrides whatever the user who called your function passed into your function as input.
if x >= 1 && x <= 1.5
If x must be a scalar, this would work. But if it can be a non-scalar (usually a vector or matrix) it's not going to work.
u1=@(x) 3.*(x-1);
end
This makes u1 a function handle. Do you want to return a function handle or do you want to return a value? [This assumes you modify your code to return u1.]
if x > 1.5 && x <= 2
u1=@(x) 3-x;
end
if x > 2
return
So your function isn't going to define u1 in the case where x is greater than 0 or if x is not greater than or equal to 1?
end
x=x+1;
This modifies the value of x inside this workspace then the function immediately exits and discards the copy of x in this workspace.
end

William Alberg
William Alberg le 1 Juin 2020
Im not entirely sure if this is what you are looking for.
syms x
u = @(x) func(x)
function y = func(x)
if 1 <= x && x <= 1.5
y = 3*(x-1);
elseif 1.5 < x && x <= 2
y = 3-x;
else
y = nan;
end
end
You can also just use func(x) direcly

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by