Reputation: 19
I have a problem using Matlab. How can I remove one or more columns if all elements in these columns less than all elements of the other columns?
For example:
A=[ 1 1 4 3;
0 -1 1 2;
-1 1 6 4]
I want to remove the 1st and 2nd column because all of the elements in the 1st and 2nd columns are less than the elements in the 3rd and 4th columns, so the output will be
B=[4 3;
1 2;
6 4]
Upvotes: 1
Views: 128
Reputation: 3511
If I understood well the problem stated in the question :
We have a Matrix A
(say of size mxn
).
We want to remove a group of columns so that, if we take any of the column in the group, its elements will be smaller than the corresponding coefficients in the remaining columns of the matrix A
.
In other words, we want the biggest submatrix of A, in which there exist no column whose elements would all be smaller than the elements in another column.
Let's try find an equivalent problem to this one, first with your example :
A=[1 1 4 3;0 -1 1 2;-1 1 6 4];
Let's now look at what happens when you sort your matrix along the second dimension in descending order and fetch the corresponding indexes :
[~,I]=sort(A,2,'descend');
I =
3 4 1 2
4 3 1 2
3 4 2 1
We can see two separate sets of indexes showing off, namely {3,4} and {1,2}. That tells us exactly that every elements in columns 1 and 2 are smaller than the corresponding elements in 3 and 4.
Now we just need to find an efficient way to extract the smallest disjoint group of indexes on the left of the index array.
This can be achieved with :
Ind1=I(:,1);
Ind2=I(:,2:end);
while(any(ismember(Ind1,Ind2)))
Ind1=[Ind1 Ind2(:,1)];
if numel(Ind2)>=2
Ind2=Ind2(:,2:end);
else
Ind2=[];
end
end
Indexes2keep=sort(Ind1(1,:));
ExtractedA=A(:,Indexes2keep);
Upvotes: 0