Function with Non Constant Variable

조회 수: 1 (최근 30일)
User7605
User7605 2020년 10월 26일
댓글: Adam Danz 2020년 10월 27일
Hello,
I'm wondering if there's a way to run this code while keeping x a variable (Instead of inputting a number for the required input 'x', have a variable so I can create a graph of results). Currently I just recieve output 'Unrecognized Function or variable 'x', even when putting sym x in the code.
Thanks for any help!
  댓글 수: 4
per isakson
per isakson 2020년 10월 27일
x must have a value, e.g.
%%
x = 17;
S(3,1,x,2)
or maybe the Symbolic Toolbox lets you use a variable, x, without a value.
Adam Danz
Adam Danz 2020년 10월 27일
" I want the x input to work as a variable"
This part is still unclear, hence the variety of answers. Do you mean you want to pass a variable to the 3rd input (see per isakson's or Stephen Cobeldick's answer) or do you mean that the 3rd variable should be a symbolic variable (see Walter Roberson's answers).

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

답변 (3개)

Stephen23
Stephen23 2020년 10월 27일
You could create an anonymous function:
fun = @(x) S(3,1,x,2);
..
fun(17)

Walter Roberson
Walter Roberson 2020년 10월 27일

syms x
output = S(3, 1, x, 2);
disp(output)
output = S(3, 1, 4, 2);
disp(output)

function SF = S(F, a, x, n)
if isa(a, 'sym') || isa(x, 'sym')
SF = piecewise(x >= a, F*(x-a)^n, 0);
elseif x >= a
SF = F.*(x-a).^n;
else
SF = zeros(size(x));
end
end

  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 10월 27일
[Please preserve the above for investigation of a system problem.]

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


Walter Roberson
Walter Roberson 2020년 10월 27일
syms x
output = S(3, 1, x, 2);
disp(output)
{3(x1)20 if  1x otherwise
output = S(3, 1, 4, 2);
disp(output)
27
function SF = S(F, a, x, n)
if isa(a, 'sym') || isa(x, 'sym')
SF = piecewise(x >= a, F*(x-a)^n, 0);
elseif x >= a
SF = F.*(x-a).^n;
else
SF = zeros(size(x));
end
end

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by