How to sort a matrix's columns by using indexes

36 次查看(过去 30 天)
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 个评论
Bruno Luong
Bruno Luong 2019-8-25
编辑:Bruno Luong 2019-8-25
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

请先登录,再进行评论。

回答(2 个)

Bruno Luong
Bruno Luong 2019-8-25
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 2019-8-25
编辑:dpb 2019-8-25
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 个评论
Bruno Luong
Bruno Luong 2019-8-25
Why do you rearrange rows with sorted column indexes?
dpb
dpb 2019-8-25
Why? 'Cuz I didn't read the Q? carefully enough... :)
Good catch, Bruno!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by