Effacer les filtres
Effacer les filtres

System of linear equations with for loop

17 vues (au cours des 30 derniers jours)
letoppina
letoppina le 31 Mar 2021
Hello, is it possible to solve a system of linear equations with a for loop? I would like to iterate one of the known parameters and see all of the solutions of the system for each iteration. Here is an example of how I am solving the system without the iteration:
A0 = 1;
B0 = 2;
C0 = 3;
syms a b c
eqn1 = a - b == A0;
eqn2 = a + b + c == B0;
eqn3 = a - b + c == C0;
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [a b c]);
X = linsolve(A,B);
a = double(X(1))
b = double(X(2))
c = double(X(3))
Now, what if the values of A0 are composed of a vector of 10 different values? I should have 10 values for each of the a, b, c parameters as output. I was thinking to iterate the equations with a for loop. How can I do that?
Thank you all in advance!

Réponses (1)

Vishesh
Vishesh le 20 Sep 2023
I understand that you want to solve a system of linear equations using a "for" loop for 10 different values of "A0" in your script.
You can achieve this using the following steps:
  1. Initialize "A0" with 10 different values.
  2. Initialize an empty array "final_values" to store results of all 10 iterations.
  3. Use a "for" loop to iterate through all 10 values of "A0" and create a new "eqn1" equation for each value of "A0".
  4. Store the result of each iteration in the "final_values" array.
The script for the above steps is provided below:
A0 = [1 2 3 4 5 6 7 8 9 10]; %taking 10 different values of A0.
B0 = 2;
C0 = 3;
syms a b c;
eqn2 = a + b + c == B0;
eqn3 = a - b + c == C0;
final_values=[]; %initializing an empty array to store values of a,b and c in each iteration.
for i=1:10 % iterating each value of "A0"
eqn1 = a - b == A0(i);
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [a b c]);
X = linsolve(A,B);
final_values=[final_values;[double(X(1)) double(X(2)) double(X(3))]]; % storing values of a,b and c.
end
disp(final_values);
0.5000 -0.5000 2.0000 1.5000 -0.5000 1.0000 2.5000 -0.5000 0 3.5000 -0.5000 -1.0000 4.5000 -0.5000 -2.0000 5.5000 -0.5000 -3.0000 6.5000 -0.5000 -4.0000 7.5000 -0.5000 -5.0000 8.5000 -0.5000 -6.0000 9.5000 -0.5000 -7.0000
Please refer to the following documentation for more information on the "for" loop:

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by