Select mxm matrix from mxn matrix and solve systems of linear equations
2 views (last 30 days)
Show older comments
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.
Hope to receive your help. Thank you so much in advance.
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
0 Comments
Accepted Answer
J. Alex Lee
on 27 Feb 2020
Does this help with first problem: https://www.mathworks.com/help/matlab/ref/nchoosek.html
Second problem, maybe make tolerance more stringent?
3 Comments
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
More Answers (0)
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!