How can I input equations with multiple variables?

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.

 採用された回答

Ameer Hamza
Ameer Hamza 2020 年 11 月 26 日

1 投票

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 件のコメント

abhisek singh
abhisek singh 2020 年 11 月 26 日
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 2020 年 11 月 26 日
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

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by