Matlab确定矩阵中的索引位置

时间:2016-11-02 04:56:30

标签: matlab matrix indexing

大家好..我有矩阵

col = [1 2 3 9 10 15 16 17]

我需要将A分为3,长度为B = [3 2 3], 结果要求:

col1 = [1 2 3] -> from col(1:3)
col2 = [9 10] -> from col(4:5)
col3 = [15 16 17] -> from col(6:8)

非常感谢你......

2 个答案:

答案 0 :(得分:2)

mat2cell可以使用:

A = [1 2 3 9 10 15 16 17];
B = [3 2 3];
mat2cell(A,1, B)

结果:

{
  [1,1] =

     1   2   3

  [1,2] =

      9   10

  [1,3] =

     15   16   17

}

答案 1 :(得分:1)

我假设B中的长度匹配col长度,因此每个元素都被考虑在内。如果是这样,你可以使用简单的for循环来完成它,如下所示:

col = [1 2 3 9 10 15 16 17];

B = [3 2 3];

start_idx = 1;
for b = B
    col_part = col(start_idx : start_idx+b-1)
    start_idx = start_idx+b;
end

结果:

col_part =

     1     2     3


col_part =

     9    10


col_part =

    15    16    17