How do I append my answers in an array, while using loop?

14 Ansichten (letzte 30 Tage)
Uche
Uche am 22 Mär. 2023
Bearbeitet: Uche am 23 Mär. 2023
Good day, please can someone help me with this problem?
In the code below, I want to add the following conditions:
  1. Solve the equation 10 times using a "for" loop or while function. That is, have a variable L=10, and substrate 1 from it after each iteration. End loop, when L=0.
  2. Create an array of two column vectors for the x and y values from each iteration, with x=6, and y=5 as the first values of this array. Similar to append.
  3. Each solution of x and y, will be used as the z and w values for the next iteration.
z = 6;
w = 5;
syms x y
eqn1 = x + y + z + w == 13;
eqn2 = 2*x + 3*y - w == -1;
sol = solve([eqn1, eqn2], [x,y]);
xSol = sol.x
ySol = sol.y

Akzeptierte Antwort

VBBV
VBBV am 23 Mär. 2023
z = 6;
w = 5;
syms x y
eqn1 = x + y + z + w == 13;
eqn2 = 2*x + 3*y - w == -1;
A = [6 5; zeros(10,2)]; % create matrix with x and y values as
L = 10;
k = 2;
% using while loop
while L > 0
sol = solve([eqn1, eqn2], [x,y]);
xSol = (sol.x);
ySol = (sol.y);
A(k,:) = [double(xSol) double(ySol)]; % use double
Z = double(xSol);
W = double(ySol);
syms z w x y;
eqn1 = x + y + z + w == 13;
eqn2 = 2*x + 3*y - w == -1;
eqn1 = subs(eqn1,[z,w],[Z,W]); % substitute new values for z and w in eqn1
eqn2 = subs(eqn2,[z,w],[Z,W]); % substitute new values for z and w in eqn2
k = k+1;
L = L-1;
end
A % final matrix with appended values
A = 11×2
6 5 2 0 34 -23 30 -28 62 -51 58 -56 90 -79 86 -84 118 -107 114 -112
  3 Kommentare
Uche
Uche am 23 Mär. 2023
Amazing! Thank you.
Uche
Uche am 23 Mär. 2023
Bearbeitet: Uche am 23 Mär. 2023
@VBBV For this line, I would not want to specify a fixed number of columns (in this case 10). How can I leave the number of rows as a variable?
This is the problem I am having, if I specify 20, but run the 10 iterations, the first 10 positions are filled, the rest are returned as zeros. I don't want the zeros.
A = [6 5; zeros(10,2)]; % create matrix with x and y values as

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by