bartsimpson
bartsimpson

Reputation: 23

Solving unknowns of a matrix in Matlab

I have a list of formula stored in a cell array, and I solve the unknowns within the matrix.

For example, consider a 2*2 matrix:
[2x+y, 4q+z; 3x+0.5y, 2q+12z ]

How to solve q,x,y,z by setting each cell equals 20? (i.e., q= 4, x =5, y = 10, z=1)

Upvotes: 2

Views: 1266

Answers (2)

Matthew Gunn
Matthew Gunn

Reputation: 4529

You're asking to solve a linear system. The canonical way to write a linear system is as A*x = b where A is a matrix, x is the vector to solve for, and b is also a vector. Writing your problem (in math) using matrices, the system is:

     [0   2   1   0        [q        [20
      4   0   0   1    *    x    =    20
      0   3  .5   0         y         20
      2   0   0  12]        z]        20]

To solve the system numerically in MATLAB:

A = [0, 2, 1, 0; 4, 0, 0, 1;, 0, 3, .5, 0; 2, 0, 0, 12];
b = [20; 20; 20; 20];
xsol = linsolve(A, b);

You could also do xsol = A \ b. A point of caution: both linsolve and \ will solve the system in the least squares sense if the system is overdetermined (typically, system is overdetermined if A is m by n where m > n).

xsol(1) will give the value for q, xsol(2) will give value for x, etc... Solution is [4.7826; 5.0000; 10.0000; 0.8696]

Upvotes: 4

misaligar
misaligar

Reputation: 325

One way to achieve what you are looking for is to use the Symbolic Toolbox. Here is an example code to solve for q, x, y, and z.

syms q x y z
A = [2*x+y==20, 4*q+z==20; 3*x+0.5*y==20, 2*q+12*z==20];
S = solve(A,[q x y z]);
disp([S.q S.x S.y S.z]);

Output:

[110/23, 5, 10, 20/23]

Upvotes: 2

Related Questions