How do I crop out a certain part within a matrix of numbers?
2 views (last 30 days)
Show older comments
This example is a small matrix, but I would like to crop out part of this matrix.
The part I want to crop out is: a(2,3:5) and a(3,3:5) which is part of row 2: 639 and underneath it is row 3: 413.
A = [1 2 3 4 5 ;
4 9 6 3 9;
2 5 4 1 3
];
I want to achieve this using the following function below.
Input parameters:
origImageMatrix = A
rowTopLeft = a(2, 3:5) => 6 3 9
colTopLeft = a(2:3, 3) => 6 4
rowBotRight = a(3,5:-1:3) => 3 1 4
colBotRight = a(3:-1:2,5) => 3 9
function [resultMatrix] = cropImg( origImageMatrix, rowTopLeft, colTopLeft, rowBotRight, colBotRight)
Accepted Answer
Chunru
on 18 Apr 2022
Edited: Chunru
on 18 Apr 2022
Are you looking for this?
A = [1 2 3 4 5 ;
4 9 6 3 9;
2 5 4 1 3
]
B = A(2:3, 3:5)
%% More general
X = [1 2 5 9 2 7
4 8 4 2 3 0
2 7 8 2 3 0
2 4 6 9 1 3
2 7 9 1 7 2
4 8 9 2 1 3];
% My input would be the borders:
% Are you sure you want to have border numbers (which you need to search
% from X) instead of the corner coordinates?
%
% Anyway, here you can search the matrix for border numbers (it may not be
% robust if there are multiple matches)
%
% You just need two borders actually
rowTop = [8 4 2 3];
rowBot = [7 9 1 7];
colLeft = [8 7 4 7];
colRight = [3 3 1 7];
[mx, nx] = size(X)
for i=1:mx
k = strfind(X(i, :), rowTop);
if ~isempty(k)
r1 = i; c1 = k;
break
end
end
for i=1:mx
k = strfind(X(i, :), rowBot);
if ~isempty(k)
r2 = i; c1 = k;
break
end
end
c2 = c1 + length(rowBot) - 1;
Y = X(r1:r2, c1:c2)
3 Comments
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!