Extract submatrix from matrix.

7 views (last 30 days)
Giura Ionut
Giura Ionut on 15 Nov 2019
Commented: Giura Ionut on 15 Nov 2019
Let's say that we have a matrix ( m x n ). This matrix contains values of 0 and 1. There is a "square shape" inside that matrix that is filled with 1. And another "shape" let's say filled with 1. How can i extract those "shapes" and create 2 separate matrices from them?
0 0 0 0 0 1 1 1
0 1 1 0 0 1 1 1
0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0
Something like this . How can i create from this matrix only this matrix:
1 1
1 1
And this:
1 1 1
1 1 1

Answers (1)

Matt J
Matt J on 15 Nov 2019
Edited: Matt J on 15 Nov 2019
>> S=regionprops(yourMatrix>0,'Image');
>> S.Image
ans =
2×2 logical array
1 1
1 1
ans =
2×3 logical array
1 1 1
1 1 1
  1 Comment
Giura Ionut
Giura Ionut on 15 Nov 2019
Thank you for your answer sir, but i would like to find out an algorithm for that, not to use the Image Processing Toolbox.
I'm thinking about something like this: The values are 0 or 1. If the next value is higher than the previous value it means that here starts my shape and i should put those values ( while my previous value is smaller than the next one ) in another matrix, or simpler if value equals 1, but the problem is that i have no ideea how to do that because the size of my new matrix is unknown. The shape can vary in size. And i have no ideea how to count how many 1s are there on width and height. I tried with contors but i always end up with something like the aria.
This would be the code for values transfer:
for i=1:width
for i=1:height
if (matrix(i,j)==1)
newmatrix(x,y)=matrix(i,j);
end
end
end

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!