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

2 次查看(过去 30 天)
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 个评论
dpb
dpb 2020-4-18
编辑:dpb 2020-4-18
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 2020-4-18
编辑:Richard Cheung 2020-4-18
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.

请先登录,再进行评论。

回答(0 个)

产品

Community Treasure Hunt

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

Start Hunting!

Translated by