How do I convert characters to a mathematical function?

I got a table full of functions like:
times(minus(x104,x1),add3(x132,x101,x1))
and I would like to make that into a calculable function. How can I do that?

5 commentaires

Joseph Cheng
Joseph Cheng le 3 Avr 2017
Modifié(e) : Joseph Cheng le 3 Avr 2017
you can create functions to do this. https://www.mathworks.com/help/matlab/matlab_prog/create-functions-in-files.html do that for each operation, then use eval() (hate to use eval but since the table is a string it is probably the best way to evaluate it without having to write a parser.)
I have thousands of equations like that, is there an easier way? I have a program that generates different equations and I must use them to calculate the results for different values (that I'll get from a .mat file). Thanks for the reply anyway!
Is that format some standard one, e.g. from another language? (I don't recognize it.) I don't see how you can get around writing a parser, unless you are lucky enough that someone else as done so for this format. I'm not sure why you would expect there to be an "easy" way.
Yeah, I know it's not usual, but mathlab actually recognizes it. If, instead of variables, i had values like:
times(minus(104,1),add3(132,101,1))
Mathlab would give me the result (104-1)*(132+101+1) = 24102
Not unless you've written (or downloaded from somewhere else) add3 it won't--
>> which add3
'add3' not found.
>>
And, just for the record, it's "MATlab" for "MATrix LABoratory" not "MATHlab". It began life as a matrix algebra tool almost exclusively; all the other stuff has come with the years.
Ah! Perhaps that's happening in the Symbolic Toolbox; I don't have it to test??? If that were the case, there's some way there to translate the values of variables to numeric result if the syntax is correct altho I don't know what that is, specifically.

Connectez-vous pour commenter.

Réponses (1)

As the other respondent says, it's a parser or some variation upon eval
First, if you have control over the syntax generated by the other program, could generate directly executable expressions if instead of add3(x,y,z) it generated sum([x y z]). Then
>> x104=pi; x1=0.4; x132=28; x101=1.01; % set some values
>> times(minus(x104,x1),sum([x132,x101,x1])) % execute (slightly) modified expression
ans =
80.6302
Alternatively, if can't do that, as the other respondent alluded, you'll have to have a library of functions to execute the string as generated. One way for the sample would be
>> s='times(minus(x104,x1),add3(x132,x101,x1))';
If previously have defined
>> add3=@(x1,x2,x3) sum([x1 x2 x3]);
then
>> eval(s)
ans =
80.6302
>>

Catégories

En savoir plus sur Startup and Shutdown dans Centre d'aide et File Exchange

Commenté :

dpb
le 3 Avr 2017

Community Treasure Hunt

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

Start Hunting!

Translated by