How do I crop out a certain part within a matrix of numbers?

5 次查看(过去 30 天)
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)

采纳的回答

Chunru
Chunru 2022-4-18
编辑:Chunru 2022-4-18
Are you looking for this?
A = [1 2 3 4 5 ;
4 9 6 3 9;
2 5 4 1 3
]
A = 3×5
1 2 3 4 5 4 9 6 3 9 2 5 4 1 3
B = A(2:3, 3:5)
B = 2×3
6 3 9 4 1 3
%% 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)
mx = 6
nx = 6
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)
Y = 4×4
8 4 2 3 7 8 2 3 4 6 9 1 7 9 1 7
  3 个评论
Steven Gangano
Steven Gangano 2022-4-19
Thank you! But I just realized that it just needs to be corner coordinates and it can be one line of code. How do you do that? Top left and bottom right coordinates.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by