I need to create a function that replaces all instances of variable_dot with diff(variable,t) in a given symbolic function. I don't want to tell the function which variables to look for, I want it to operate on anything that ends in _dot.
For example:
func = x_dot + y_dot
I want to call newFunc = convertFunction(func)
to give
syms x(t) y(t);
newFunc = diff(x,t) + diff(y,t)
Has anybody performed similar, or can anybody point me towards the best approach to take?
You can use regular expressions:
s= 'func = x_dot + y_dot'
expr='\w+_dot'
new_s= regexprep(s,expr,'diff(${strrep($0,''_dot'','''')},t)')
Here's the solution I used, based on AVK's answer. While his method came close, I ran into problems converting between strings and symbolic equations in a valid manner. Excuse the use of eval, it was the quickest way I could think of achieving this, I'm more than open to improvements.
function [ newFunc ] = replaceDotNotation( func )
vars = symvar(func);
newFunc = func;
for i = 1:numel(vars)
if endsWith(char(vars(i)), '_dot')
expr ='\w+_dot';
newVarName = regexprep(char(vars(i)),expr,'${strrep($0,''_dot'','''')}(t)');
s = ['syms ', newVarName];
eval(s);
s = ['newVal = ', regexprep(char(vars(i)),expr,'diff(${strrep($0,''_dot'','''')},t)')];
eval(s);
newFunc = subs(newFunc, vars(i), newVal);
end
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.