简体   繁体   English

在Matlab中将单元格与向量进行比较

[英]Comparing a cell with a vector in Matlab

I have a cell A in Matlab of dimension 1x3 , eg 我在Matlab中有一个尺寸为1x3的单元格A ,例如

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

A contains all the integers from 1 to n in increasing order. A包含从1n所有整数(按升序排列)。 In the example n=9 . 在示例中n=9 However, the number of elements within each sub-cell can be different. 但是,每个子小区内的元素数量可以不同。 Each sub-cell is non-empty. 每个子单元都是非空的。

Consider the vector B of dimension nx1 containing some integers from 1 to n in increasing order (repetitions are allowed), eg 考虑维数为nx1的向量B ,其中包含从1n一些整数, n是递增的(允许重复),例如

B=[1 1 2 2 4 7 7 8 9]'

I want to construct (without using loops) the vector C of dimension nx1 such that each C(i) tells which sub-cell of A B(i) belongs to. 我想构造(不使用循环)尺寸为nx1的向量C ,以使每个C(i)知道A B(i)哪个子单元属于。 In the example 在这个例子中

C=[1 1 1 1 1 3 3 3 3]'

I don't know whether it's faster than for loops, but how about 我不知道它是否比for循环要快,但是怎么样

C = arrayfun(@(b) find(cellfun(@(a) any(cell2mat(a) == b), A)), B);

Explanation: pick each element b in B ; 说明:选择B每个元素b then pick every sub-cell a in A and check for equality with b , return the index of sub-cell b is a member of. 然后挑选每子电池aA和检查与平等b ,返回子小区的索引b是其成员。

通过这种结构, A由其每个单元格的元素数唯一确定,结果可以得到

C = sum(bsxfun(@gt, B, cumsum(cellfun(@numel, A))), 2)+1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM