首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将向量划分成不同的矩阵

将向量划分成不同的矩阵
EN

Stack Overflow用户
提问于 2015-04-29 00:57:52
回答 3查看 46关注 0票数 1

我有两个长向量。向量一包含0,1,2,3,4's,0表示不作用力,1表示动作1,2表示第二个动作,以此类推。每个动作都是720个样本点,这意味着您可以找到720个连续的两倍,然后是720个连续的4s。向量二包含对应于每个动作的原始数据。我需要为每个动作( 1、2、3和4)创建一个矩阵,其中包含第二个向量的相应数据。例如,矩阵1应该拥有所有发生在同一行动指数上的数据(向量2数据)。有帮助吗?

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-04-29 01:24:46

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

代码语言:javascript
复制
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}
票数 2
EN

Stack Overflow用户

发布于 2015-04-29 05:05:55

由于Vector 1中有一个规则的组长度模式,所以在提出解决方案时,可以利用这种模式来实现vectorize的许多事情。这里有一个这样的实现-

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

给定输入的样本运行-

代码语言:javascript
复制
>> 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
票数 1
EN

Stack Overflow用户

发布于 2015-04-29 01:28:16

以下是另一个解决方案:

代码语言:javascript
复制
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, [])'

编辑:David的解决方案更灵活,而且可能更高效。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29932548

复制
相关文章

相似问题

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