Creating a function that uses contains to check a string then convert to syms

2 vues (au cours des 30 derniers jours)
Richard Cheung
Richard Cheung le 18 Avr 2020
The title wording is a bit confusing but here is the rundown.
I have an input that looks like this:
inputmsg = 'Enter a function of x and y to be approximated:\n';
f = input(inputmsg,'s'); % Take input as string
variable = ["x","y"]; % Patterns to check for
existXY = contains(f,variable) % If the input contains an 'x' or 'y', it will have logical 1
% If f doesn't contain 'x' or 'y', repeat
while ( existXY == 0 )
fprintf('\nPLEASE ENTER A FUNCTION CONTAINING X AND Y\n');
f = input(inputmsg,'s');
variable = ["x","y"];
existXY = contains(f,variable)
end
f = str2sym(f); % Convert f back to symbol
% do maths
This works, but looks very clunky if put half way through a script.
A while back, I was shown how to check for numbers similar to this.
When trying to create a function, if I do either one of these, I get the error thats in the comments.
f = inputFunc('Enter a function of x and y to be approximated:\n','s');
function inputFunc(n)
% TOO MANY INPUT ARGUMENTS
f = inputFunc('Enter a function of x and y to be approximated:\n');
function inputFunc(n)
% TOO MANY OUTPUT ARGUMENTS
How would I lay out the function header to properly take in the arguments?
  4 commentaires
dpb
dpb le 18 Avr 2020
Modifié(e) : dpb le 18 Avr 2020
Well, for your users' sake then at least take the input and cast to lower for them instead of making them reenter from scratch. Unless, of course, it's feasible to have something like
y=2x + A
We don't know what it is you're intending/trying to do so pretty difficult to guess what would need to do or whether the symbolic toolbox would necessarily even be needed.
Richard Cheung
Richard Cheung le 18 Avr 2020
Modifié(e) : Richard Cheung le 18 Avr 2020
The most I can say is that it's necessary for my programming project.
Making a function like this is probably a bit overkill since all I want to do is return an error if a bad input is entered, which matlab will already do, albeit it'll look a bit ugly.

Connectez-vous pour commenter.

Réponses (0)

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by