首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何根据特定行(Matlab)中包含的条件对列进行排序?

如何根据特定行(Matlab)中包含的条件对列进行排序?
EN

Stack Overflow用户
提问于 2012-09-17 02:27:49
回答 1查看 854关注 0票数 2

我的数据如下:A=2 5 10 4 10;2 4 5 12;6 2 1 5 4;

A=

代码语言:javascript
复制
 2     5    10     4    10
 2     4     5     1     2
 6     2     1     5     4

我想根据以下条件按最后一行对排序:

如果第一个元素(在第三行中)和第二个元素(在第三行中)之间的差值小于或等于2 --则将该列(在本例中为第二列)向右移动两列。然后对所有列执行此操作,直到(最后一行的)没有两个元素在差2内。)

B=

代码语言:javascript
复制
 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。

有什么建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-17 05:46:29

这是一种可能的解决方案:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12449510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档