How to combine 2 matrices conditionally and use short circuiting

3 views (last 30 days)
Teddy Fisher
Teddy Fisher on 20 Feb 2020
Commented: Walter Roberson on 21 Feb 2020
I have 2 matrices of the same size, A & B, containing only 1s and 0s.
I want to combine these matrices into a new matrix, C, so that the 1s in B go into C only if they overlap or follow (in a column) 1s from A, and otherwise, turn to 0s. And, the 1s from A stay in C only if they are followed by 1s from B. I think I have to use short circuiting, but I'm not sure how to use it to combine these matrices.
For example:
A=[1 0 0 1 0;
1 0 0 0 0;
0 0 0 1 0]
B=[0 0 1 1 0;
0 1 0 1 0;
1 1 0 0 0]
%and I want to C to be:
C=[1 0 0 1 0;
1 0 0 1 0;
1 0 0 0 0]
I tried a for loop with if else loops nested in it, that I thought would loop through A & B column by column and then change values in C based on the conditions:
for x=1:size(A,1)
for y=1:size(B,1)
if A(x)=1 & B(y)=1 || A(x)=1 & B(y)=0 %error here
C(x,y)=1
else C(x,y)=0
if A(x)=1 & B(y(A(x)+1))=0
C(x,y(x+1))=0 %here I'm not sure how to make the 1s in B that are more than 1 removed from the 1 in A change to 0
end
end
end
end
But it gives me the error:
if A(x)=1 & B(y)=1 || A(x)=1 & B(y)=0
Error: The expression to the left of the equals sign is not a valid target for an assignment
Is this the right way to go about it? And if it is, how do I fix this error?
Please help, and thanks!!
  1 Comment
Walter Roberson
Walter Roberson on 21 Feb 2020
= is always assignment, except in some contexts involving quoted strings and the symbolic toolbox.
Comparisons are ==
You cannot short circuit a matrix calculation. You can find() the locations that the first applies for and only do the second test for those locations, but this is very likely slower.
Your test can be simplified. B is always 0 or 1 so A==1&B==0 or A==1&B==1 logically reduces to A==1 alone. That would not be the case if there was a third B value.
If you used logical() then A==1 would be the same as A without further explicit tests for 1

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by