How to sort a matrix's columns by using indexes

27 views (last 30 days)
phdcomputer Eng
phdcomputer Eng on 25 Aug 2019
Edited: dpb on 25 Aug 2019
I wrote some codes to sort an array (a) descendingly. I want to use the indexes (indA) to sort the data matrix's columns.
close all;
clc
load lung.mat
data=lung;
[n,m]=size(data);
l=1;
t=1;
data1=[];
data2=[];
for i=1:n
if data(i,m)==1
data1(l,:)=data(i,:);
l=l+1;
else
data2(t,:)=data(i,:);
t=t+1;
end
end
if t>l
data1(l:t-1,:)=0;
else
data2(t:l-1,:)=0;
end
for i=1: m
thisCol1=data1(:,i);
thisCol2=data2(:,i);
a(i)=fHammingDist(thisCol1,thisCol2);
end
[A,indA]=sort(a,'descend');
I'll be very greatfull to have your opinions how to sort a matrix's columns by using an array of indexes.
Thank you
  1 Comment
Bruno Luong
Bruno Luong on 25 Aug 2019
Edited: Bruno Luong on 25 Aug 2019
Are you sure to compute the distance of the last column which seems to contain special values
...
if data(i,m)==1
...
end
...
for i=1: m
...
a(i)=fHammingDist(thisCol1,thisCol2);
end

Sign in to comment.

Answers (2)

Bruno Luong
Bruno Luong on 25 Aug 2019
Short answer
data = data(:,indA);
Long answer
load lung.mat
data=lung;
b = data(:,end) == 1;
data1 = data(b,:);
data2 = data(~b,:);
n1 = size(data1,1);
n2 = size(data2,1);
if n1 < n2
data1(n2,1) = 0;
elseif n2 < n1
data2(n1,1) = 0;
end
a = arrayfun(@(j) fHammingDist(data1(:,j),data2(:,j)), 1:size(data,2));
[A,indA] = sort(a,'descend');
data1 = data1(:,indA);
data2 = data2(:,indA);
data = data(:,indA);

dpb
dpb on 25 Aug 2019
Edited: dpb on 25 Aug 2019
See
doc sortrows
Not clear which array it is you wish sorted but mayhaps can accomplish directly -- altho the auxiliary array and distances may be needed to have been computed, not knowing exactly the problem trying to solve.
But, given the index vector you've built, simply
A=A(indA,:);
if we presume this mystery array is 'A' will rearrange rows in that order.
ERRATUM:
As Bruno points out, I mixed metaphors/switched horses midstream...
A=A(:,indA);
to sort the columns instead, of course.
  2 Comments
Bruno Luong
Bruno Luong on 25 Aug 2019
Why do you rearrange rows with sorted column indexes?
dpb
dpb on 25 Aug 2019
Why? 'Cuz I didn't read the Q? carefully enough... :)
Good catch, Bruno!

Sign in to comment.

Categories

Find more on Shifting and Sorting 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!