Convert polynomial operations inputs in double vector as output
4 次查看(过去 30 天)
显示 更早的评论
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]
0 个评论
采纳的回答
Matt J
2022-7-24
编辑:Matt J
2022-7-24
converter('2*s^2 + s +1')
converter( 's*(s+1)*(s+5)' )
converter('(s+2)*(s+3)^2')
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 个评论
更多回答(1 个)
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
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?
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!