How to select (and assign) values within a specific subregion of a matrix

4 views (last 30 days)
Hello, I am struggling with a problem and I cannot find the solution anywhere, I hope someone could help me out. A is a matrix, specifically A = zeros(81,81); and A(32,32)=1. I am trying to select the values within a square-shaped region with center in A(32,32) and radius 2 (i.e. from the center to +- 2 rows and to +-2 columns, please see the example below), and assign them the value of 2. So, if this is the original matrix (here smaller for practical reasons): A = zeros(7); A(4,4) = 1 A =
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
I would like this to be the result: A =
0 0 0 0 0 0 0
0 2 2 2 2 2 0
0 2 2 2 2 2 0
0 2 2 1 2 2 0
0 2 2 2 2 2 0
0 2 2 2 2 2 0
0 0 0 0 0 0 0
Does anyone know how I could assign the value of 2 to the values within that region, without doing it manually for each element?
Any help would be very appreciated. Thank you in advance!

Answers (1)

Andrei Bobrov
Andrei Bobrov on 20 Nov 2015
Edited: Andrei Bobrov on 20 Nov 2015
use function bwdist from Image Processing Toolbox
out = (bwdist(A,'chessboard')<3)*2-A;

Categories

Find more on Shifting and Sorting 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!