按 Octave 中的列对矩阵进行排序

Sort a matrix by a column in Octave

我必须在 Octave(类似于 Matlab)中创建一个递归函数(使用 'if',不允许 'for' 或 'while')对数组的 n 行进行排序(该条目只是数组)的其中一列。我卡在递归步骤了。

function Msorted=sort_array(M)
  [n,m]=size(M);
  if n<2
    Msorted=M
  else

基本上我的问题是,我应该如何编写递归步骤,我应该如何继续?

如果我们按照m列对数组进行排序:

% This is a recursive function, too:
function min_index = get_min_index(column_vec)
   if size(column_vec, 1)<2
      min_index = 1;
   else % `column_vec` contains at least 2 elements
      first = column_vec(1);
      new_vec = column_vec(2:end); % `new_vec` is `column_vec` without the first element
      min_index_new = get_min_index(new_vec); % get the index of the min number of `new_vec`
      if first<=new_vec(min_index_new)
         min_index = 1;
      else
         min_index = min_index_new + 1; % we need to add 1 becuase `new_vec` does not include the first element of `column_vec`
      end
   end
end

function Msorted = sort_array(M)
   n = size(M, 1);
   if n<2
      Msorted = M;
   else
      min_index = get_min_index(M(:, m)); % Find the index of the minimum value in the m_th column
      M_new = M(1:n~=min_index, :); % `M_new` is `M` without the "minimum row" that should be the first row in `Msorted`
      M_new_sorted = sort_array(M_new); % Sort `M_new`
      Msorted = [M(min_index, :); M_new_sorted]; % Add back the "minimum row" to `M_new`
   end
end

示例(对于m = 2):

代码:

a = [200 -4; 400 -100; -50 -1000]
a_sort = sort_array(a)

输出:

a =

    200     -4
    400   -100
    -50  -1000

a_sort =

    -50  -1000
    400   -100
    200     -4

请注意,您可以在不递归的情况下使用 sortrows 函数,例如 Msorted = sortrows(x, m)