user3503856
user3503856

Reputation: 15

Matlab, define submatrix

I got a 10x10 matrix with a bunch of zeroes and an element of the value 1. I'm trying to create a submatrix with the element of 1 and its surrounding.

Problem:

enter image description here

This is just an example, the element "1" is placed anywhere within the matrix. I do realise I can find my element using find find(MATRIX==1).

How do I define my 3x3 submatrix?

Upvotes: 0

Views: 284

Answers (1)

E. Valencia
E. Valencia

Reputation: 457

You need to use 'find' to get the indices of that '1' element, and construct the desired matrix from them. Something like:

[row, col] = find(MATRIX==1);
subMatrix = MATRIX(row-1:row+1, col-1:col+1);

Of course, you might need to check that the '1' element is not in a border of the MATRIX (i.e. row-1, row+1, col-1, col+1 are not out of bounds).

Best.

Upvotes: 1

Related Questions