替换矩阵中的线(Matlab)
我有一个n乘3的矩阵。像这样:替换矩阵中的线(Matlab),matlab,matrix,Matlab,Matrix,我有一个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”进行比较。如果没
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”与之相等,则第1行将更改为[0]。但是如果有另一个'a'与之相等,例如第2行中的瞬间,我将比较'b'1和'c'2。如果它们相等,则这些行保持不变。如果不是,第1行将更改为[0]。等等 我会通过这种方式进行搜索,针对每一行测试您的两个标准
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
看看这对你有用吗-
%// 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
中的&
的位置。解释起来有点复杂。我正在编辑一些评论,让我们看看这是否更有意义。我的观点是:以OP的mtx
为例,但使用mtx(2,3)=4
。您的代码将使第1行和第4行等于零,但OP规范要求第3行也为零。是的,我将这样做:&
在任何
之前