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

1 view (last 30 days)
Catja Coetzee
Catja Coetzee on 1 Jun 2020
Commented: madhan ravi on 1 Jun 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

Answers (2)

Steven Lord
Steven Lord on 1 Jun 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 on 1 Jun 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

Community Treasure Hunt

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

Start Hunting!