使用子向量行过滤矩阵

时间:2013-06-19 18:30:18

标签: matlab

我有一个表格矩阵:

m = 1, 0, 10, 20, 30, 40, 50;
    2, 1, 11, 20, 30, 40, 50;
    3, 0, 12, 20, 30, 40, 50;
    4, 1, 12, 21, 30, 40, 50;

对于给定的列索引(比如3)和行索引(比如说1),我想过滤掉该行中该列右侧具有相同值的所有行。使用上面的m,columnIndex = 3和rowIndex = 1的例子(用星号表示):

                  **
f(m, 3) = * 1, 0, 10, 20, 30, 40, 50;    % [20, 30, 40, 50] matches itself, include
            2, 1, 11, 20, 30, 40, 50;    % [20, 30, 40, 50] matches the subvector in row 1, include
            3, 0, 12, 20, 30, 40, 50;    % [20, 30, 40, 50] matches the subvector in row 1, include
            4, 1, 12, 21, 30, 40, 50;    % [21, 30, 40, 50] does NOT match the subvector in row 1, filter this out

我该如何实现这种行为?我试过这个,但是我遇到了尺寸不匹配错误。

key = data( rowIndex, columnIndex:end );
filteredData = ( data( :, columnIndex:end ) == key );

2 个答案:

答案 0 :(得分:3)

== bsxfun()中保存的内容编入索引:

r = 3;
c = 2;

idx = all(bsxfun(@eq, m(:,c:end),m(r,c:end)),2);
m(idx,:)

答案 1 :(得分:0)

我认为您希望使用isequal运算符,记录为here

isequal(m(1,columnIndex:end),key)

这是一种效率低下的单线: - )

cellfun(@(x) isequal(key,x),mat2cell(m(:,columnIndex:end),ones(1,size(m,2)-columnIndex+1)))

这是怎么回事

  1. 将矩阵更改为我们感兴趣的子向量的单元格数组:mat2cell(m(:,columnIndex:end),ones(1,size(m,2)-columnIndex+1))
  2. 在每个单元格元素上运行的匿名函数:@(x) isequal(key,x)
  3. 使每个单元格元素传递给匿名函数cellfun
  4. 的函数

    我的答案使用上面的m作为示例:

    cellfun(@(x) isequal(key,x),mat2cell(m(:,columnIndex:end),ones(1,size(m,2)-columnIndex+1)))
    
    ans =
    
         1
         1
         1
         0
    

    HTH!