MATLAB中对cell数组排序

    科技2026-08-21  7

    近期在干啥

    差不多有24天没写推送了。。。。一直干活,期间好几晚都没回宿舍,太惨了,净在干些没啥用的事情。

    虽然不想干,但确实学到了一些东西(大半个月没找工作了,更想找工作来着)。

    MATLAB中,如何对cell数组排序?

    问题背景

    如下图所示,我有一个 1 * n 的cell数组,这个cell的每一个元素是一个 1 * 2 的向量,表示一个坐标点(x, y):

    现在要根据坐标的 x 值对这个 cell 数组进行排序!

    解决办法

    我本来以为可以和C++ STL中的sort算法一样 指定一下排序方法就行。但是查看MATLAB的帮助文档,发现他们的sort函数没法用在我这个cell数组上!

    直接放解决办法吧:

    先把cell数组(coors)中的每个小单元的第一个元素拿出来,就是把所有的x坐标拿出来,放到一个行或者列向量中,记为 x 。

    [~, ind] = sort(x); 获取排序后的索引(把这些索引对应的元素排起来就是有序的)。还是看MathWorks给的解释吧:[B,I] = sort(_) also returns a collection of index vectors for any of the previous syntaxes. I is the same size as A and describes the arrangement of the elements of A into B along the sorted dimension. For example, if A is a vector, then B = A(I).

    coors = coors(ind); 这样就对coors这个cell数组排序了

    clc clear %% 原来的 待排序的 cell(保存了坐标点的cell数组) coors = {[180, 37], [60, 39], [120, 38], [0, 40], [420, 32], [300, 35]}; disp('Source: ') dispCoorCell(coors) %% 获取每个小cell的第一个元素的值(即获取所有的x坐标) x = zeros(1, length(coors)); for i = 1 : length(coors)         x(i) = coors{i}(1); end %% 对x坐标排序,获取排序索引 [~, ind] = sort(x); %% 对这个cell数组排序  coors = coors(ind); disp('Sorted: ') dispCoorCell(coors) function dispCoorCell(coors) x = zeros(1, length(coors)); y = zeros(1, length(coors)); for i = 1 : length(coors)         x(i) = coors{i}(1);         y(i) = coors{i}(2); end disp(x) disp(y) end

    输出:

    C++中,类似的问题怎么实现

    我就直接写代码了,也没啥可比性。实际就是创建一个:

    vector<pair<double, double>> coors;

    这样就类似于上面MATLAB中的那个cell了。

    #include <iostream> #include <vector> #include <utility> /// for pair #include <algorithm> #include <iomanip> using namespace std; using COOR = pair<double, double>; /// 定义 COOR 的输出 ostream& operator<<(ostream& os, pair<double, double>& c) {     os << "(" << c.first << ", " << c.second << ")";     return os; } /// 定义比较函数,根据 x 的值比较 bool MySortFunc(const COOR& c1, const COOR& c2) {     return c1.first < c2.first; } int main() {     vector<COOR> coors{{180, 37},                        {60, 39},                        {120, 38},                        {0, 40},                        {420, 32},                        {300, 35}};     /// 打印 原始坐标     for (auto ele : coors)         cout << setw(10) << ele;     cout << endl;     /// 排序 坐标vector     sort(coors.begin(), coors.end(), MySortFunc);     /// 打印 排序后的vector     for (auto ele : coors)         cout << setw(10) << ele;     cout << endl; }

    输出


    Processed: 0.009, SQL: 10