how to check if two arrays intersect within a matrix?

i have a 10x10 matrix of zeros.
three ships called destroyer,aircraft_carrier and cruiser:
destroyer=[2,2] %placed either vertically or horizontally within the matrix
cruiser=[4,4,4,4]%placed either vertically or horizontally within the matrix
aircraft_carrier=[5,5,5,5,5] %placed either vertically or horizontally within the matrix
i wrote the code so that the ships are placed randomly and also in a random alignment,vertical or horizontal.i want to check weather they intersect with each other so i can write code to prevent it.
i tried using intersect(a,b) command but it gave me back an empty matrix even when the point where intersecting..i dont know what i am doing wrong or if there is some other command to help me do this.....

 Accepted Answer

Try this:
blankElements = (matrix1 == 0) & (matrix2 == 0);
matrixIntersections = (matrix1 ~= matrix2) & ~blankElements;

4 Comments

If you have two 10x10 matrices and you've go a line of 4's in one matrix and a line of 5's in the other matrix, the first line determines where they are both zeros.
Then the (matrix1 ~= matrix2) finds out where they don't match. They won't match as points there the line of 5's crosses the line of 4's. But they also don't match where you have a 5 in one matrix and a 0 in the other matrix, and you don't want to count that as an intersection, so I AND it with the blank (0) elements to erase the non-matches in that situation.
roshan's 'Answer' moved here:
Brilliant! thank you very much!
OK, if we're done, then please go ahead and mark it Accepted.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!