如何将矢量提取到具有连续范围的子矢量

时间:2016-07-13 07:01:57

标签: matlab vector

我有一个向量行,如下所示:

rows=[1 2 3 5 6 7 10 11 12 13 14]

我想将矢量提取到一些具有连续范围的子矢量,例如

vec1=[1 2 3];
vec2=[5 6 7];
vec3=[10 11 12 13 14];

我正在使用MATLAB来完成这项任务。这是我的代码。但它看起来很复杂。如果您有其他方式或短MATLAB功能。请让我知道

for i=1:length(rows)-1
   if((rows(i)+1)==rows(i+1)) %% The different of each element is 1
       index_length=index_length+1;       
   else
       sub_ranges=[sub_ranges index_length];
       index_length=0;
   end
end
%% For last element in rows
if((rows(end-1)+1)==rows(end))
   sub_ranges=[sub_ranges index_length];
   index_length=0;
end
%% Extract for each range
low_bound=0;
high_bound=0;
sub_ranges=sub_ranges+1;
sub_rows_extract=[];
for i=1:length(sub_ranges)-1
    if i==1
        result=rows(1:sub_ranges(i))'
        filename=sprintf('row_%d.mat',i);
        save(filename,'result');
        low_bound=sub_ranges(1)+1;
    else
        high_bound=low_bound+sub_ranges(i)-1;
        result=rows(low_bound:high_bound)'
        low_bound=high_bound+1;
        filename=sprintf('row_%d.mat',i);
        save(filename,'result');
    end
end

1 个答案:

答案 0 :(得分:3)

使用diff()更简单:你只需找到两个条目之间的距离大于1的位置。然后在这些点上拆分矩阵。

rows=[1 2 3 5 6 7 10 11 12 13 14];
drows=[ find(diff(rows)>1) numel(rows)]; 
n_1=1;
nn=1;
res={};
for n=drows
   res{nn}=rows(n_1:n); 
   n_1=n+1;
   nn=nn+1;
end

结果应该是包含子向量的单元格数组。 迁移是一种更优雅的分裂方式......但现在无法想到一个方法