Replacing a group of values in a matrix
19 views (last 30 days)
Show older comments
I am having some trouble with a problem I am trying to solve. I want to take the values in matrix M that = 1. When a value equals 1 in matrix M, I need to create an 8x8 square of 1's, replacing the zeros that surround that value of 1. A shortened example is listed, the data set I am working with is much larger.
For example, my table would look like this with a few ones scattered about: 

But I would like to transform those areas around the 1's to look like this:

My thinking is to write a for loop that replaces the area around the singular 1 with a matrix of ones in an 8x8 fashion (like in the second figure). So I would be replacing the area of matrix M with matrix a but I am not sure if this is possible or there is a better way to replace these values for every appearance of a 1 in my matrix. I've been googling for hours but not familiar with matlab enough to know how to work this out. Any steps in the right direction would be appreciated, thank you.
M = zeros(100,100);
M(8,8) = 1; % example data point
M(15,22) = 1; % example data point
a = ones(8,8)
0 Comments
Accepted Answer
Matt J
on 25 Jun 2021
If you don't have the Image Processing Toolbox, you can also do,
M=conv2(M,ones(8),'same');
2 Comments
More Answers (2)
Sulaymon Eshkabilov
on 25 Jun 2021
You can start with a logical indexing approach to locate where 1's located, e.g.:
[Rn, Cn] = find(AM); % Initial Matrix with some 1s and many 0s
%% E.g.
A=zeros(8);
A(3,3)=1;
[Rn,Cn] = find(A==1);
A([(Rn-2):(Rn+2)], [(Cn-2):(Cn+2)])=1; % Creates 5-by-5 1s in A.
2 Comments
Sulaymon Eshkabilov
on 25 Jun 2021
To make this run within a loop, you'd need to care of special cases when the index values (Rn and Cn) residing along the corner or edge or closer to the edges of the given matrix. That would create a problem with indexes end up being outside of the given matrix or negative indexes.
See Also
Categories
Find more on Matrix Indexing 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!