# Solve system of equations with some knowns and unknowns in the same matrix

1 view (last 30 days)

Show older comments

##### 0 Comments

### Accepted Answer

Bruno Luong
on 25 Oct 2022

Edited: Bruno Luong
on 25 Oct 2022

% Random example

A = rand(5,5);

x = rand(5,1),

b = A*x,

[m,n] = size(A);

% put NaN at the position where x is unknown;

xunknown = randperm(n,3);

x(xunknown) = NaN;

% same for b

bunknown = randperm(m,2);

b(bunknown) = NaN;

% Reconstruct unknown x and then b

xunknown = isnan(x);

bunknown = isnan(b);

x(xunknown)=A(~bunknown,xunknown)\(b(~bunknown)-A(~bunknown,~xunknown)*x(~xunknown))

b(bunknown)=A(bunknown,:)*x

##### 2 Comments

### More Answers (1)

David Goodmanson
on 26 Oct 2022

Edited: David Goodmanson
on 26 Oct 2022

Hi Yusuf,

I'm later on an answer (and losing the race more often, to the extent that there is a race, which to be honest there sometimes is), but here is a slightly different way.

% data

n = 7;

m = 3;

A = rand(n,n);

i = sort(randperm(n,m))'; % index of unknown x

j = setdiff(1:n,i)'; % index of unknown b, the complementary index to i

x = zeros(n,1);

x(j) = rand(size(j)) % known x, zeros elsewhere

b = zeros(n,1);

b(i) = rand(size(i)) % known b, zeros elsewhere

%solve

G = zeros(n,n);

G(:,i) = A(:,i);

G(j,j) = -eye(length(j));

g = b-A(:,j)*x(j);

z = G\g

% z is a vector of all the unknowns,

% x(i) for the i indices

% b(j) for the j indices

% check

x(i) = z(i); % insert unknowns into orginal x vector

b(j) = z(j); % insert unknowns into orginal b vector

A*x-b % should be small

##### 2 Comments

David Goodmanson
on 26 Oct 2022

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!