How to sort a matrix's columns by using indexes

25 ビュー (過去 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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by