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

1 次查看(过去 30 天)
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 个)

Steven Lord
Steven Lord 2020-6-1
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 2020-6-1
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by