How can I let Matlab to put different numbers in different variables?
3 views (last 30 days)
Show older comments
I have to complete my code that should solve an equation with 7 variables to get a specific number.
my equation is like this:
5*x1 + 6*x2 + 7*x3 + 8*x4 + 9*x5 + 10*x6 + 11*x7 = 77 (to get more answers, I will put range like = from 75 to 78).
I will get many solutions, but I am confused how to code it.
I started with initiating x1,2,3,4,5,6,7 and each time I make loop for changing one variable and keep other constants. Then, I do the same thing with the second variable.
This way is not efficient. Can you suggest a coding way that is more efficient?
Thank you
2 Comments
Walter Roberson
on 14 Jul 2017
Are there constraints on the values of the variables? For example are they restricted to positive integers? If they are restricted to integers then you would have a Diophantine Equation and there are techniques for solving those.
Answers (1)
Star Strider
on 14 Jul 2017
You have 1 equation in 7 unknowns, so you will get an infinity of solutions. Solving it seems to be pointless.
To code it, I would use an anonymous function:
f = @(x) 5*x(1) + 6*x(2) + 7*x(3) + 8*x(4) + 9*x(5) + 10*x(6) + 11*x(7) - 77;
Your x-values are now one vector: [x(1),x(2),...,x(7)]. Given a random starting vector, you could use the fsolve function to ‘solve’ it for one set of variables. Whether that is an efficient use of your time is for you to decide.
8 Comments
Star Strider
on 15 Jul 2017
There is only one optimal solution to a linear system of seven (or more) equations with seven unknowns, with real coefficients. You can use the Statistics and Machine Learning Toolbox regress function to get the confidence intervals of the ‘X’ values, since there will be some uncertainty in their estimation.
You can use a loop to experiment with other values for the ‘X’ vector. However, the result the least-squares solution will be the best estimate for it.
See Also
Categories
Find more on Linear Least Squares in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!