How to sort a matrix's columns by using indexes

35 vues (au cours des 30 derniers jours)
phdcomputer Eng
phdcomputer Eng le 25 Août 2019
Modifié(e) : dpb le 25 Août 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 commentaire
Bruno Luong
Bruno Luong le 25 Août 2019
Modifié(e) : Bruno Luong le 25 Août 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

Connectez-vous pour commenter.

Réponses (2)

Bruno Luong
Bruno Luong le 25 Août 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 le 25 Août 2019
Modifié(e) : dpb le 25 Août 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 commentaires
Bruno Luong
Bruno Luong le 25 Août 2019
Why do you rearrange rows with sorted column indexes?
dpb
dpb le 25 Août 2019
Why? 'Cuz I didn't read the Q? carefully enough... :)
Good catch, Bruno!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by