How can I save and plot all values of x and y for each value of C? x and y values are in the vertical axis and C in the horizontal axis in the graphic. I need to use the function "solve"

V=[1,2,3,4];
A=3;
i=1;
while i<=4
C=A*V(i);
syms x y
eqn1 = C*x + y == 2;
eqn2 = -x + y == 3;
sol = solve([eqn1, eqn2], [x, y]);
xSol = double(sol.x);
ySol = double(sol.y);
i=i+1;
end

 Accepted Answer

Try the following code:
clear;clc;
V=[1 2 3 4];
A=3;
for i=1:numel(V)
C(i)=A*V(i);
syms x y
eqn1=C(i)*x+y==2;
eqn2=-x+y==3;
sol=solve([eqn1 eqn2],[x y]);
xSol(i)=double(sol.x);
ySol(i)=double(sol.y);
end
Also, plot the values to see if they are correct:
figure(1);plot(C,xSol);
figure(2);plot(C,ySol);

4 Comments

OK thank you! but do you know why it says "the variable C xSol and ySol appears to change size on every loop iteration"?
Because for this code we didn't define the vectors that we will use previously. Change the code to following:
clear;clc;
V=[1 2 3 4];
A=3;
%preallocation
C=zeros(1,numel(V));
xSol=zeros(1,numel(V));
ySol=zeros(1,numel(V));
for i=1:numel(V)
C(i)=A*V(i);
syms x y
eqn1=C(i)*x+y==2;
eqn2=-x+y==3;
sol=solve([eqn1 eqn2],[x y]);
xSol(i)=double(sol.x);
ySol(i)=double(sol.y);
end
figure(1);plot(C,xSol);
figure(2);plot(C,ySol);
Ok thank you!! you think this is an efficient way of solving a large linear equation system?
Also if C(i)=A-V(i) there is an error that says "Unable to perform assignment because the left and right sides have a different number of elements", how can I solve this problem?

Sign in to comment.

More Answers (0)

Categories

Products

Asked:

on 26 Jan 2021

Commented:

on 27 Jan 2021

Community Treasure Hunt

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

Start Hunting!