Replace numbers in a matrix depending on neighbor numbers
Show older comments
Hi community,
I have a 14x9 matrix that contains as values NaN, 1 or 2. I need to "clean" this matrix regarding cells containing number 1. If cells containing number 1 are neighbor to NaN cells (both up, down, left, right and diagonal), I need to change this number to a NaN. However, more than checking individually, I need to check that if I have a block of numbers 1 connected to a NaN, all these numbers 1 must be replaced to a NaN. If a cell containing a number 1 is surrounded in all 8-directions by numbers 2, this cell must remain with a number 1.
For example, my input is a matrix like this one:
[2 2 2 1 2 1 NaN NaN NaN;
2 2 2 1 2 1 NaN NaN NaN;
2 2 2 1 1 1 NaN NaN NaN;
2 2 2 1 1 1 NaN NaN NaN;
2 2 2 1 1 1 NaN NaN NaN;
2 2 2 2 1 1 NaN NaN NaN;
2 2 2 2 1 1 NaN NaN NaN;
2 2 2 2 1 1 NaN NaN NaN;
2 2 2 2 1 1 NaN NaN NaN;
2 2 2 2 1 1 NaN NaN NaN;
2 2 2 2 1 1 NaN NaN NaN;
2 2 2 2 2 1 NaN NaN NaN;
2 1 2 2 2 1 NaN NaN NaN;
2 2 2 2 2 1 NaN NaN NaN];
And the output I´m expecting is:
[2 2 2 NaN 2 NaN NaN NaN NaN;
2 2 2 NaN 2 NaN NaN NaN NaN;
2 2 2 NaN NaN NaN NaN NaN NaN;
2 2 2 NaN NaN NaN NaN NaN NaN;
2 2 2 2 NaN NaN NaN NaN NaN;
2 2 2 2 NaN NaN NaN NaN NaN;
2 2 2 2 NaN NaN NaN NaN NaN;
2 2 2 2 NaN NaN NaN NaN NaN;
2 2 2 2 NaN NaN NaN NaN NaN;
2 2 2 2 NaN NaN NaN NaN NaN;
2 2 2 2 2 NaN NaN NaN NaN;
2 1 2 2 2 NaN NaN NaN NaN;
2 2 2 2 2 NaN NaN NaN NaN];
Thank you very much for your help!!!.
2 Comments
Geoff Hayes
on 23 Aug 2018
Diego - to be clear, If cells containing number 1 are neighbor to NaN cells (both up, down, left, right and diagonal), I need to change this number to a NaN), does this mean that at least one neighbour is a NaN or do all neighbours have to be NaN?
Image Analyst
on 25 Aug 2018
Diego, Geoff's comment is NOT the 1 Answer you see on the previous page. There is an answer below. Did you scroll down to see it?
Accepted Answer
More Answers (1)
Diego Gómez
on 26 Aug 2018
0 votes
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!