How can I input equations with multiple variables?

25 visualizaciones (últimos 30 días)
abhisek singh
abhisek singh el 26 de Nov. de 2020
Comentada: Ameer Hamza el 26 de Nov. de 2020
Hello there guys;
I'm working on a problem where user is being asked for number of equations he wants to give to code to solve them. e.g. if user gives us n = 2, then there would be maximum 2 variables and equations. if user gives us n = 3, then would be 3 equations with 3 different variables. I'm facing issues with it and I'm using
F = eval(['@(x1,x2))',input("Write function f(x1,x2,...xn): ",'s')]);
but as we can see, I need to increase numbers of varables manually ( x1, x2 in this line ). But I want to make it much flexible and it can take any number of equations with any numbers of variables ( of course number of equtions would be equal to number of variables.

Respuesta aceptada

Ameer Hamza
Ameer Hamza el 26 de Nov. de 2020
evak is evil: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval don't use it. It is better to use str2func() here. Following shows an example
n = 3;
xns = strjoin(compose('x%d', 1:n), ',');
func_str = input("Write function f(x1,x2,...xn): ",'s');
F = str2func(sprintf('@(%s) %s', xns, func_str));
  2 comentarios
abhisek singh
abhisek singh el 26 de Nov. de 2020
Thank you very much. This was really helpful but I'm new in MATLAB (Started on 25-11-2020) and I don't have deep knowledge in this. Could you please share links to help me to understand terms (like compose,sprintf etc)? that would be so helpful.
Ameer Hamza
Ameer Hamza el 26 de Nov. de 2020
You can find information about these functions in the documentation. For example, compose(): https://www.mathworks.com/help/matlab/ref/compose.html. You can type the name of the function in the search bar and see its documentation. Also, consider taking the free course: https://www.mathworks.com/learn/tutorials/matlab-onramp.html

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by