由多个列筛选矩阵值W / O型圈(Matlab的)? [英] Filter matrix by multiple column values w/o loops (Matlab)?
问题描述
说我有以下几点:
- 数据矩阵的 M ( M 的-by-的 N 的);
- 匹配行的 V ( 1 的-by-的 N 的);
- 匹配位置我( 1 的-by-的 N 的逻辑);
我要过滤的所有行的 M ,在匹配位置的有作为的 V 相同的价值观我。我相信,Matlab的索引,如果足够强大的做,没有循环。但如何?
目前的解决办法:虽然运行中的所有列,并更新过滤行位置的˚F( M 的-by-的 1 的逻辑)。 p>
F =真(男,1);
对于k = 1:N;
如果我(K);
F = F&安培; (M(:,K)== V(K));
结束;
结束;
M = M(男,:);
下面是一种方法:
结果= M(所有(bsxfun(@eq,M(:,I),V(I)),2),:);
工作原理
的 m每个行(:我)
比较逐元素与行向量 V(I)
使用 bsxfun
。行,从而 所有
一>列匹配的选择。由此产生的逻辑载体用于指数 M
行。
示例
M = [8 3 6 9
5 4 9 8
8 9 6 9]。
I = [真假真真]。
V = [8 1 6 9];>>结果= M(所有(bsxfun(@eq,M(:,I)中,V(I)),2),:)
结果=
8 3 6 9
8 9 6 9
Say I have the following:
- Data matrix M (m-by-n);
- Matching row V (1-by-n);
- Matching positions I (1-by-n logical);
I want to filter all rows of M that have the same values as V at the matching positions I. I believe that Matlab indexing if powerful enough to do that without loops. But how?
Current solution: run though all the columns and update the filtered row positions F (m-by-1 logical).
F = true(m,1);
for k = 1:n;
if I(k);
F = F & (M(:,k)==V(k));
end;
end;
M = M(F,:);
Here's one way:
result = M(all(bsxfun(@eq, M(:,I), V(I)), 2), :);
How it works
Each row of M(:,I)
is compared element-wise with the row vector V(I)
using bsxfun
. Rows for which all
columns match are selected. The resulting logical vector is used to index the rows of M
.
Example
M = [ 8 3 6 9
5 4 9 8
8 9 6 9 ];
I = [ true false true true ];
V = [ 8 1 6 9 ];
>> result = M(all(bsxfun(@eq, M(:,I), V(I)), 2), :)
result =
8 3 6 9
8 9 6 9
这篇关于由多个列筛选矩阵值W / O型圈(Matlab的)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!