Info

此问题已关闭。 请重新打开它进行编辑或回答。

Dont get the required answer..please help

1 次查看(过去 30 天)
Aarach Sap
Aarach Sap 2017-4-4
关闭: MATLAB Answer Bot 2021-8-20
A=[2 5 3 1 1 ; 4 2 5 1 1];
[r,c]=size(A);
B=[1 0 1 1 1; 1 0 1 1 1 ];
[m,n]=size(B);
for row=1:r
for col=1:c
for ii=1:m
for jj=1:n
if (A(row,col)==5)&&(B(ii,jj)==1)
A(row,col)=5+1;
end
end
end
end
end
In the above code, if A has 5 and B has 1 then it should be 6 but if A has 5 but B has 0 then it should be 5. I know its simple. But i am not getting where i am wrong.

回答(2 个)

Guillaume
Guillaume 2017-4-4
编辑:Guillaume 2017-4-4
Is
A=[2 5 3 1 1 ; 4 2 5 1 1];
B=[1 0 1 1 1; 1 0 1 1 1 ];
A(A == 5 & B) = 6
what you're looking for?
edit, or maybe:
B = logical(B);
A(B) = A(B) + 1
  2 个评论
John D'Errico
John D'Errico 2017-4-4
Note that the second solution shown will increment ALL values of A where B == 1. That may or may not be the desired goal. But in that case, it would be as simple to write A=A+B.
Guillaume
Guillaume 2017-4-4
Indeed! I was too focused on demonstrating logical indexing that I missed the simple addition.

Rik
Rik 2017-4-4
I am going to assume you want the following: A should stay the same, except for some positions. On the positions that A is 5 and B is 1, then A should be 6.
You can solve this without the hassle of 4 nested loops if you use logical indexing.
A(A==5 & B==1)=6;
(Technically, B==1 can be replaced with B, because it already contains only ones and zeros, but this is a more general case)
If this is not what you need, please elaborate on your question. If it is, please mark this answer as accepted answer.

此问题已关闭。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by