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

조회 수: 1 (최근 30일)
Catja Coetzee
Catja Coetzee 2020년 6월 1일
댓글: madhan ravi 2020년 6월 1일
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
David Hill
David Hill 2020년 6월 1일
Is your function only defined from 1 to 2? Your function does not make any sense when x = 1.5.

댓글을 달려면 로그인하십시오.

답변 (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