【问题标题】:Replacing lines in matrix (Matlab)替换矩阵中的行(Matlab)
【发布时间】:2015-01-25 17:41:46
【问题描述】:

我有一个 n×3 矩阵。像这样:

  mtx =  [3 1 3;
          2 2 3;
          2 3 2;
          5 4 1]

我希望最终结果是:

mtx2 = [0 0 0;
        2 2 3;
        2 3 2;
        0 0 0]

所以我想将零放在没有第一个数字的行上,并且它们的第二个数字不等于另一个数字的第三个。

想象任何行的第一个数字是“a”,第二个是“b”,第三个是“c”。对于第 1 行,我会将它的“a”与所有其他“a”进行比较。如果没有另一个 'a' 等于那个值,那么第 1 行将更改为 [0 0 0]。但是如果有另一个 'a' 等于那个,对于第 2 行的瞬间,我将比较 'b' #1 和 'c' #2。如果它们相等,则这些行保持不变。如果不是,第 1 行更改为 [0 0 0]。等等。

【问题讨论】:

    标签: matlab matrix


    【解决方案1】:

    看看这是否适合你 -

    %// Logical masks of matches satisfying condition - 1 and 2
    cond1_matches = bsxfun(@eq,mtx(:,1),mtx(:,1).')  %//'
    cond2_matches = bsxfun(@eq,mtx(:,3),mtx(:,2).')  %//'
    
    %// Create output variable as copy of input and use the conditions to set
    %// rows that satisfy both conditions as all zeros
    mtx2 = mtx;
    mtx2(~any( cond1_matches & cond2_matches ,1),:)=0
    

    【讨论】:

    • 据我了解,OP 希望条件 2 仅应用于在第 1 列中具有相同值的行(条件 1)在您的代码中,这两个条件似乎是独立检查的?
    • @LuisMendo 这就是cond1 & cond2 中的& 出现的地方。解释起来有点复杂。我正在用几个 cmets 进行编辑,让我们看看这是否更有意义。
    • 我的意思是:使用 OP 的 mtx,但使用 mtx(2,3)=4。您的代码会使第 1 行和第 4 行等于 0,但 OP 规范要求第 3 行也为零。
    • 是的,我会这样做:&any 之前
    【解决方案2】:

    我会通过这种方式进行搜索,针对每一行测试您的两个条件。

    Izeros=[];  % here is where I'll store the rows that I'll zero later
    for Irow = 1:size(mtx,1) %step through each row
    
        %find rows where the first element matches
        I=find(mtx(:,1)==mtx(Irow,1));
    
        %keep only those matches that are NOT this row
        J=find(I ~= Irow);
    
        % are there any that meet this requirement
        if ~isempty(J)
            %there are some that meet this requirement.  Keep testing.
    
            %now apply your second check, does the 2nd element
            %match any other row's third element?
            I=find(mtx(:,3)==mtx(Irow,2));
    
            %keep only those matches that are NOT this row
            J=find(I ~= Irow);
    
            % are there any that meet this 2nd requirement
            if ~isempty(J)
                %there are some that meet this 2nd requirement.
                % no action.
            else
                %there are none that meet this 2nd requirement.
                % zero the row.
                Izeros(end+1) = Irow;
            end
        else
            %there are none that meet the first requirement.
            % zero the row.
            Izeros(end+1) = Irow;
        end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-24
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 2017-02-27
      • 2012-10-25
      相关资源
      最近更新 更多