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

2 Ansichten (letzte 30 Tage)
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)

Akzeptierte Antwort

Chunru
Chunru am 18 Apr. 2022
Bearbeitet: Chunru am 18 Apr. 2022
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 Kommentare
Steven Gangano
Steven Gangano am 19 Apr. 2022
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by