How to Solve for x for 20 functions

1 view (last 30 days)
Hi,
I have 4 column vectors (C,V,B and N), each has 20 intial values and they represent 20 spatial points ([C(i), V(i), B(i), N(i)], [C(i+1),V(i+1), B(i+1), N(i+1)]) and so on. I want to solve for x for each point using this function -> K=[(C(i)+x(i))*(V(i)+x(i))]/[(B(i)-x(i))*(N(i)-x(i))] (K is constant) and then get new values for each row in each vector ( C(i_new)=C(i)+x(i), V(i_new)=V(i)+x(i).....etc) and sort them again in new vectors (C_new, V_new, B_new and N_new)
1- So how can I construct this model? I always get confused when I want to do for loops by numel.
2- I was thinking to use vpasolve to get all x. However, I get 2 answers of x since the functons is second order in x. How can I choose first answer of x and use it later to find my next solutions?
Thnaks

Accepted Answer

Wan Ji
Wan Ji on 26 Aug 2021
You can get symbolic solution by
syms K C V B N X
eq = K*(B-X)*(N-X)-(C+X)*(V+X);
x = solve(eq, X)
and the final process is
K = 1;
% There are two solutions, x1 is the first solution
x1 = @(C,V,B,N) (C + V - (B.^2.*K.^2 + 2*B.*C.*K - 2*B.*K.^2.*N + ...
4*B.*K.*N + 2*B.*K.*V + C.^2 + 2*C.*K.*N + 4*C.*K.*V - 2*C.*V + ...
K.^2.*N.^2 + 2*K.*N.*V + V.^2).^(1/2) + B.*K + K.*N)./(2*(K - 1));
% x1 is the second solution
x2 = @(C,V,B,K) (C + V + (B.^2.*K.^2 + 2*B.*C.*K - 2*B.*K.^2.*N + ...
4*B.*K.*N + 2*B.*K.*V + C.^2 + 2*C.*K.*N + 4*C.*K.*V - 2*C.*V + ...
K.^2.*N.^2 + 2*K.*N.*V + V.^2).^(1/2) + B.*K + K.*N)./(2*(K - 1));
C = rand(20,1); % randomly initialized data
V = rand(20,1);
B = rand(20,1);
N = rand(20,1);
X = x1(C,V,B,N); % choose the first answer of x, you can also choose the second
C_new = sort(C + X);
V_new = sort(V + X);
B_new = sort(B + X);
N_new = sort(N + X);
  7 Comments
Wan Ji
Wan Ji on 26 Aug 2021
Edited: Wan Ji on 26 Aug 2021
Also, as I have already solved it with sybolic solver, no more symbolic process is needed with the code now.
Meteb Mejbel
Meteb Mejbel on 26 Aug 2021
Great, I just tried it. It did work and yes without symbolic process. Thank you so much

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!