2

次の行列のようなデータがあります。A=[25 10 4 10; 2 4 5 1 2; 6 2 1 5 4];

A =

 2     5    10     4    10
 2     4     5     1     2
 6     2     1     5     4

次の基準に基づいて、最後の行で並べ替えたいと思います。

最初の要素(3行目)と2番目の要素(3行目)の差が2以下の場合、その列(この場合は2番目の列を右に2列)を移動します。次に、(最後の行の)2つの要素が2の差の範囲内になくなるまで、すべての列に対してこれを実行します。

B =

 2     5     4    10    10
 2     4     1     5     2
 6     2     5     1     4

ここで(6-2 = 4)(2-5 = 3)(5-1 = 4)(1-4 = 3)

最終的に、最後の行のすべての要素とその隣の要素の差は2より大きくなります。

助言がありますか?

4

1 に答える 1

2

これは1つの可能な解決策です:

A = [2 5 10 4 10; 2 4 5 1 2; 6 2 1 5 4];

B = A;

MatrixWidth = size(A, 2);

CurIndex = 1;

%# The second-last pair of the bottom row is the last pair to be compared.
while(CurIndex+2 <= MatrixWidth)
    Difference = abs(A(3,CurIndex) - A(3,CurIndex+1));

    %# If the right side of comparison is not yet the second-last index.
    if ((Difference <= 2) && (CurIndex+3 <= MatrixWidth))
        B = [ B(:, 1:CurIndex), B(:, CurIndex+2), B(:, CurIndex+1), B(:, CurIndex+3:end) ];
    %# If the right side of the comparison is already the second-last index.
    elseif (Difference <= 2)
        B = [ B(:, 1:CurIndex), B(:, CurIndex+2), B(:, CurIndex+1) ];
    end

    CurIndex = CurIndex + 1;
end
于 2012-09-16T21:46:28.790 に答える