2017-02-01 74 views
0

行列の各列から2つの最小要素を選択します。どのように行の数を表示することができますか? 入力:matlabの行数を取得するには?

a1 a2 a3 
    -------- 
b1 2 4 8 
b2 8 5 3 
b3 1 5 9 

出力:

a1 a2 a3   a1 a2 a3 
--------   ---------- 
1 4 3 => b3 b1 b2 
2 5 8   b1 b2 b1 

私のコード:

for i = 1:3 
    MINN(:,i)=getNElements(distance(i,:), 1); 
end 

function [smallestNElements smallestNIdx] = getNElements(A, n) 
    [ASorted AIdx] = sort(A); 
    smallestNElements = ASorted(1:n); 
    smallestNIdx = AIdx(1:n); 
end 
+0

は、正確に、所望の入力と出力は何ですか?各列から2つの値はどのように選択されますか?それらの 'a1'などは何ですか? –

+0

私の入力はa1-a3の行とb1-b3の列を持つ行列です。 getNElements()によって選択された値。 –

答えて

0

は私は推測してみましょう、これはあなたが何をしたいのですか?

x = [2 4 8; 8 5 3; 1 5 9]; % data 
n = 2; % desired number of smallest values per column 
[y, ind] = sort(x,1); % sort each column and get indices of that sorting 
y = y(1:n,:); % keep n smallest 
ind = ind(1:n,:); % keep their indices 

結果:

y = 
    1  4  3 
    2  5  8 

ind = 
    3  1  2 
    1  2  1 
関連する問題