【问题标题】:Matlab- moving numbers to new row if condition is metMatlab-如果满足条件,将数字移动到新行
【发布时间】:2015-01-22 17:58:20
【问题描述】:

我有一个像这样的变量,都是一行:

1 2 3 4 5 6 7 8 9 2 4 5 6 5

我想编写一个 for 循环,它会找到一个数字小于前一个数字的位置,并将其余数字放在一个新行中,就像这样

1 2 3 4 5 6 7 8 9
2 4 5 6 
5

我试过这个:

test = [1 2 3 4 5 6 7 8 9 2 4 5 6 5];
m = zeros(size(test));
for i=1:numel(test)-1;
   for rows=1:size(m,1)
     if test(i) > test(i+1);
     m(i+1, rows+1) = test(i+1:end)
   end % for rows
end % for

但这显然不对,就挂了。

【问题讨论】:

    标签: arrays matlab if-statement for-loop jagged-arrays


    【解决方案1】:

    x 成为您的数据向量。你想要的可以很简单地完成如下:

    ind = [find(diff(x)<0) numel(x)]; %// find ends of increasing subsequences
    ind(2:end) = diff(ind); %// compute lengths of those subsequences
    y = mat2cell(x, 1, ind); %// split data vector according to those lenghts
    

    这会在元胞数组y 中产生所需的结果。使用元胞数组,以便每个“行”可以有不同的列数。

    例子:

    x = [1 2 3 4 5 6 7 8 9 2 4 5 6 5];
    

    给予

    y{1} =
         1     2     3     4     5     6     7     8     9
    y{2} =
         2     4     5     6
    y{3} =
         5
    

    【讨论】:

      【解决方案2】:

      如果您正在寻找数字数组输出,则需要用一些东西填充“空白”,并用zeros 填充似乎是一个不错的选择,就像您在代码中所做的那样。

      所以,这里有一个基于 bsxfun 的方法来实现同样的效果 -

      test = [1 2 3 4 5 6 7 8 9 2 4 5 6 5] %// Input
      idx = [find(diff(test)<0) numel(test)] %// positions of row shifts
      lens = [idx(1) diff(idx)] %// lengths of each row in the proposed output
      m = zeros(max(lens),numel(lens)) %// setup output matrix
      m(bsxfun(@le,[1:max(lens)]',lens)) = test; %//'# put values from input array
      m = m.' %//'# Output that is a transposed version after putting the values
      

      输出 -

      m =
           1     2     3     4     5     6     7     8     9
           2     4     5     6     0     0     0     0     0
           5     0     0     0     0     0     0     0     0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-15
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 1970-01-01
        • 2020-04-19
        • 1970-01-01
        • 2017-03-24
        相关资源
        最近更新 更多