How to sort a matrix's columns by using indexes

조회 수: 15 (최근 30일)
phdcomputer Eng
phdcomputer Eng 2019년 8월 25일
편집: dpb 2019년 8월 25일
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