Convert polynomial operations inputs in double vector as output

조회 수: 4 (최근 30일)
Nélio Dias
Nélio Dias 2022년 7월 23일
댓글: Nélio Dias 2022년 7월 24일
I am developing a Matlab App to work with control theory, transfer function, and controllers, so I need to build a function that takes the polynomial inputs in a string format from the user and transforms them into numbers vectors. I know that was the symbolic toolbox, but Matlab doesn't allow me to create a standalone version with this toolbox, so I am trying to develop the fuction that will convert this. This is an example of what the function has to do:
converter('2*s^2 + s +1') = [2 1 1]
converter('s*(s+1)*(s+5)') = [1 6 5 0]
converter('(s+1)*(s+3)^2') = [1 8 21 18]

채택된 답변

Matt J
Matt J 2022년 7월 24일
편집: Matt J 2022년 7월 24일
converter('2*s^2 + s +1')
ans = 1×3
2.0000 1.0000 1.0000
converter( 's*(s+1)*(s+5)' )
ans = 1×4
1.0000 6.0000 5.0000 0.0000
converter('(s+2)*(s+3)^2')
ans = 1×4
1.0000 8.0000 21.0000 18.0000
function p=converter(str)
fn=str2func("@(s)"+vectorize(str));
x=linspace(0,1,100);
y=fn(x);
p=polyfit(x,y,1);
for i=2:20
if p(1)<=1e-6*p(2), break; end
p=polyfit(x,y,i);
end
p(1)=[];
end
  댓글 수: 3
Matt J
Matt J 2022년 7월 24일
It should work in the Matlab Compiler, though.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2022년 7월 24일
You should probably approach this as a task in Parsing. It is a lot easier to get this kind of task right if you write a formal definition of what you will accept, such as in Backus-Naur Form (BNF)
At the moment I do not see any BNF tools implemented in MATLAB, so I would suggest that you consider using yacc and lex to create some C code that you can call from MATLAB.
I have a memory that there used to be Blog posts about building "tiny languages" in MATLAB, but I cannot find that.
  댓글 수: 2
Walter Roberson
Walter Roberson 2022년 7월 24일
Will it always be simple literal constant integers? Integers and fixed point numbers? leading zeros before a decimal point optional? Digits after a decimal point optional? If .5 and 5. are considered valid, so digit before period is not necessary, and digits after period is not needed, then is period by itself an error or to be treated as 0?
Are exponents in floating point accepted? integer followed by exponent without decimal point? Which exponent characters are permitted? e E d D h H?
are expressions such as sqrt(2) permitted? sin(pi/7)? sin(pi*s/7)? sqrt(s^2 + 1)?
is division by an s expression supported?
Is using [] as brackets supported? If so does it mean list building?
Nélio Dias
Nélio Dias 2022년 7월 24일
I think in integers and to two decimal places

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

카테고리

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

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by