JuMoGar
JuMoGar

Reputation: 1760

How to solve a linear system of equations with 2D matrices on the RHS

I am trying to solve this problem:

Problem to solve

I am trying to declare a matrix of matrices for the right hand side (RHS), but I do not know how do it. I am trying this:

MatrizResultados = [[1, 3; -1, 2]; [0, 4; 1, -1]; [2, 1; -1, 1]]

But the result is all one matrix, like so:

MatrizResultados =

 1     3
-1     2
 0     4
 1    -1
 2     1
-1     1

How can I store these as separate matrices, within one matrix, to solve the above problem?

Here is my current Matlab code, to try and solve this question:

syms X Y Z;

MatrizCoeficientes = [-1, 1, 2; -1, 2, 3; 1, 4, 2];
MatrizVariables = [X; Y; Z];
MatrizResultados = [[1, 3; -1, 2]; [0, 4; 1, -1]; [2, 1; -1, 1]];

Upvotes: 1

Views: 1172

Answers (1)

Wolfie
Wolfie

Reputation: 30047

The symbolic math toolbox is overkill for this.

This is 4 separate systems of equations, since addition is linear i.e. there is no cross over in matrix elements. You have, for example

- x(1,1) + y(1,1) + 2*z(1,1) = 1
- x(1,1) + 2*y(1,1) + 3*z(1,1) = 0
  x(1,1) + 4*y(1,1) + 2*z(1,1) = 2

This can be solved using the mldivide (\) operator, from a matrix of coefficients. This can be constructed like so:

% Coefficients of all 4 systems
coefs = [-1 1 2; -1 2 3; 1 4 2];
% RHS of the equation, stored with each eqn in a row, each element in a column
solns = [ [1; 0; 2], [-1; 1; -1], [3; 4; 1], [2; -1; 1] ];

% set up output array
xyz = zeros(3, 4);
% Loop through solving the system
for ii = 1:4
    % Use mldivide (\) to get solution to system
    xyz(:,ii) = coefs\solns(:,ii);
end

Result:

% xyz is a 3x4 matrix, rows are [x;y;z], 
% columns correspond to elements of RHS matrices as detailed below
xyz(:,1) % >> [-10   7  -8], solution for position (1,1)
xyz(:,2) % >> [ 15 -10  12], solution for position (2,1)
xyz(:,3) % >> [ -1   0   1], solution for position (1,2)
xyz(:,4) % >> [-23  15 -18], solution for position (2,2)

Upvotes: 3

Related Questions