0

I have tried to solve this problem by reading old questions and by googles help.

I writing a short script in matlab where the user types in a equation and then plot the data by using eval.

But I want to check if the equation is right and uses the right variables and so...

I have three variables, X,Y,Z with upper case, so for example 'X+Y-Z-7.5' is a solid equation, but 'XB-Z' isn't. Just 'X' is also a solid "equation"...

How can I write the expression? Here is what I have...

regexp(test,'(X|Y|Z)$|(X|Y|Z|\d)&&(+|-|*|/|)') 

My next plan is to do like,

if regexp(test,'(X|Y|Z)$|(X|Y|Z|\d)&&(+|-|*|/|)') == 1
    disp ('Correct')
end

So I want the regexp return if the string matches the whole expression, not just startindex. I have problem to fix that too.

Please, I'm stuck.

Jocken
  • 1
  • 1
    There are many useful web pages that help you generate regular expressions. I use the [Python version of Regular Expressions 101](https://regex101.com/#python), which pretty closely approximates MATLAB's syntax as well. – sco1 Feb 06 '16 at 18:14
  • There are also 2 very different questions here. Testing for the presence of `X`, `Y`, and `Z` is straightforward, but using other criteria (what are those?) to test and see if the equation is 'right' is not necessarily a trivial task. – sco1 Feb 06 '16 at 18:20
  • Save yourself some time, use `ezplot()` and `ezplot3()` – Oleg Feb 06 '16 at 20:05

1 Answers1

0

One potential solution (if you have the Symbolic Math Toolbox) is to simply rely on that to determine whether the equations are valid.

You can use symvar to extract all symbols used in the equation and compare these to the variables you allow.

allowed = {'X', 'Y', 'Z'};
vars = symvar(userinput);

tf = ismember(vars, allowed);

if ~all(tf)
    disp('Invalid Variables Used');
end

This is likely going to be much more robust than attempting to create regular expressions as it relies on MATLAB's internal parser.

Suever
  • 64,497
  • 14
  • 82
  • 101
  • Using `eval` is a very bad idea and the more it can be avoided, the better. See [this answer of mine}(http://stackoverflow.com/questions/32467029/how-to-put-these-images-together/32467170#32467170) for details and official documentation on why it should be avoided – Adriaan Feb 06 '16 at 19:05
  • @Adriaan while I completely agree, the user is already stating that he is using it to do his plotting. – Suever Feb 06 '16 at 19:07
  • @Adriaan - I use eval because I dont any other way around. I have a set of data, which I read into X,Y,Z. The user then type in what one want to plot, X+Y or just Y. How can I achieve the same thing without eval? So I have like, X = rand(1,5) Y = rand(1,5) Z = rand(1,5) Userinput = 'X+Y' How can i plot this without using eval? – Jocken Feb 06 '16 at 19:26
  • @Jocken that's a topic for another question. Ask one and someone with expertise in user interfaces in MATLAB can hopefully help you – Adriaan Feb 06 '16 at 19:33