# Select mxm matrix from mxn matrix and solve systems of linear equations

1 view (last 30 days)
Thuy Tran on 27 Feb 2020
Commented: Thuy Tran on 28 Feb 2020
Hi everyone,
I has started using Matlab recently. There are two problems in my following code:
+ Firstly, I would like to choose different sets of m columns from n columns matrix. e.g,5 columns from 10 columns.
There must be 252 sets, however, my code randomly select so there are some sets are the same (only the position of the columns are changed).
+ Secondly, when solving the systems of linear equations with matrix: a=xb then x=a\b, there appears error "Warning: Matrix is close to singular
or badly scaled.Results may be inaccurate" since the det(a)~0. I have set "if (det(a)<=-1e-12) | (det(a)>=1e-12)" but it seems not so good.
A =[ 0 0 2 2 6 3 4 5 2 1
2 2 0 0 0 1 0 0 0 1
0 2 0 1 2 0 1 0 0 1
0 0 0 0 0 0 0 1 1 0
3 7 1 3 7 3 4 4 3 4 ];
%choose different sets of 5 columns from 10 columns: 10!/(5!5!)=252 sets
for i=1:252
c=randperm(length(A),5);
a=A(:,c);
b=[5.8; 2.4; 1.6; 0.2; 10];
%Error "Warning: Matrix is close to singular or badly scaled"
%if det(a)~=0
if (det(a)<=-1e-12) | (det(a)>=1e-12)
x=a\b;
%Find non-negative and non-Infinities x values
if (x(:,:)>=0) & (x(:,:)~=Inf)
disp(x)
disp(a)
end
end
end

J. Alex Lee on 27 Feb 2020
Second problem, maybe make tolerance more stringent?

Thuy Tran on 28 Feb 2020
Thanks a lot for your quick reply. However, "nchoosek" doesn't work for my case. I want to select 5 colums (5x5 matrix) from 10 columns (5x10 matrix). From my code, there are 252 output but some of them are the same (only different in column's position), e.g, [5 2; 3 1] and [2 5; 1 3] are the same.
For the secons problem, make tolerance more stringent is also the only way I can think of up to now.
J. Alex Lee on 28 Feb 2020
I'm not sure I understand your examples, which are 2x2...but it sounds like you are confirming that you wish to find ALL the unique combinations of K columns of a matrix that has N columns. In this case, nchoosek() should do exactly what you need
clc;
clear;
A =[ 0 0 2 2 6 3 4 5 2 1
2 2 0 0 0 1 0 0 0 1
0 2 0 1 2 0 1 0 0 1
0 0 0 0 0 0 0 1 1 0
3 7 1 3 7 3 4 4 3 4 ];
K = 5
N = size(A,2)
colsets = nchoosek(1:N,K);
b = [5.8; 2.4; 1.6; 0.2; 10];
% confirm that you have the right number of combinations
nCombinations = size(colsets,1)
for i = 1:nCombinations
ASub = A(:,colsets(i,:));
if rank(ASub) < K
fprintf('skip combination %3d\n',i)
else
x = ASub \ b;
end
end
Thuy Tran on 28 Feb 2020
Sorry, I misunderstood your previous sugesstion. Thank you so much for your help. It is exactly what I need.