划分向量以形成不同的矩阵

  • 本文关键字:向量 划分 matlab
  • 更新时间 :
  • 英文 :


我有两个长向量。向量 1 包含 0,1,2,3,4 的值,0 表示无动作,1 表示动作 1,2 表示第二个动作,依此类推。每个动作都是 720 个采样点,这意味着您可以找到 720 个连续的 2,然后找到 720 个连续的 4。向量二包含对应于每个动作的原始数据。我需要为每个动作(1、2、3 和 4)创建一个矩阵,其中包含第二个向量的相应数据。例如,矩阵 1 应该具有在动作 1 的相同索引处发生的所有数据(向量 2 数据)。有什么帮助吗??

Example on small amount of data:
Vector 1: 0 0 1 1 1 0 0 2 2 2 0 0 1 1 1 0 0 2 2 2 
Vector 2: 6 7 5 6 4 6 5 9 8 7 9 7 0 5 6 4 1 5 8 0
Result:
Matrix 1:
5 6 4 
0 5 6
Matrix 2:
9 8 7 
5 8 0

这里有一种方法。我使用单元格数组来存储输出矩阵,硬编码此类变量的名称不是一个好的计划。

V1=[0 0 1 1 1 0 0 2 2 2 0 0 1 1 1 0 0 2 2 2]
V2=[6 7 5 6 4 6 5 9 8 7 9 7 0 5 6 4 1 5 8 0]
%// Find length of sequences of 1's/2's
len=find(diff(V1(find(diff(V1)~=0,1)+1:end))~=0,1)
I=unique(V1(V1>0)); %// This just finds how many matrices to make, 1 and 2 in this case
C=bsxfun(@eq,V1,I.'); %// The i-th row of C contains 1's where there are i's in V1
%// Now pick out the elements of V2 based on C, and store them in cell arrays
Matrix=arrayfun(@(m) reshape(V2(C(m,:)),len,[]).',I,'uni',0);
%// Note, the reshape converts from a vector to a matrix
%// Display results
Matrix{1}
Matrix{2}

因为,在Vector 1内组的长度中存在一个规则的模式,可以利用该模式在提出解决方案时vectorize许多事情。这是一个这样的实现 -

%// Form new vectors out of input vectors for non-zero elements in vec1
vec1n = vec1(vec1~=0)
vec2n = vec2(vec1~=0)
%// Find positions of group shifts and length of groups 
df1 = diff(vec1n)~=0
grp_change = [true df1]
grplen = find(df1,1)
%// Reshape vec2n, so that we end up with N x grplen sized array 
vec2nr = reshape(vec2n,grplen,[]).'  %//'
%// ID/tag each group change based on their unique vector 2 values
[R,C] = sort(vec1n(grp_change))
%// Re-arrange rows of reshaped vector2, s.t. same ID rows are grouped succesively
vec2nrs = vec2nr(C,:)
%// Find extents of each group & use those extents to have final cell array output
grp_extent = diff(find([1 diff(R) 1]))
out = mat2cell(vec2nrs,grp_extent,grplen)

给定输入的示例运行 -

>> vec1
vec1 =
     0     0     1     1     1     0     0     2     2     2  ...
             0     0     1     1     1     0     0     2     2     2
>> vec2
vec2 =
     6     7     5     6     4     6     5     9     8     7  ...
             9     7     0     5     6     4     1     5     8     0
>> celldisp(out)
out{1} =
     5     6     4
     0     5     6
out{2} =
     9     8     7
     5     8     0

这是另一种解决方案:

v1 = [0 0 1 1 1 0 0 2 2 2 0 0 1 1 1 0 0 2 2 2];
v2 = [6 7 5 6 4 6 5 9 8 7 9 7 0 5 6 4 1 5 8 0];
m1 = reshape(v2(v1 == 1), 3, [])'
m2 = reshape(v2(v1 == 2), 3, [])'

编辑:大卫的解决方案更灵活,可能更有效。

最新更新