How to determine outside perimeter of an array?

6 次查看(过去 30 天)
For example, a matrix, a:
a = randi(10,5)
a = 5×5
3 2 6 6 4 1 7 10 4 7 8 5 1 8 3 7 10 10 3 8 9 10 4 8 1
How would I obtain the elements of the matrix into an row vector, minus the center 3 x 3?
So in this case:
a_perim = [6 9 2 8 7 8 3 4 10 6 8 5 8 2 4 6]
a_perim = 1×16
6 9 2 8 7 8 3 4 10 6 8 5 8 2 4 6
A previous method I tried was defining the center as new matrix, and using ismember(). However, this did not work when elements in the center 3 x 3 were the same as the perimeter.

采纳的回答

Dyuman Joshi
Dyuman Joshi 2022-8-3
Note - a_perim vector doesn't correspond to the outer elements of a in the example you mentioned.
Here's how you can achieve that
y=spiral(5) %random matrix
y = 5×5
21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13
z=ones(5);
z(2:end-1,2:end-1)=0;
y(z==1)'
ans = 1×16
21 20 19 18 17 22 16 23 15 24 14 25 10 11 12 13

更多回答(1 个)

Image Analyst
Image Analyst 2022-8-3
I'm not sure how you're getting
a_perim = [6 9 2 8 7 8 3 4 10 6 8 5 8 2 4 6] ;
from this:
a = [...
3 2 6 6 4
1 7 10 4 7
8 5 1 8 3
7 10 10 3 8
9 10 4 8 1];
Anyway, you can get the perimeter values as [top row, right column, bottom row, left column] like this
topRow = a(1,:);
rightCol = a(2:end-1, end);
bottomRow = a(end, end-1 : -1 : 2);
leftCol = a(end-1 : -1 : 2, 1);
% Get perimeter clockwise from upper left (1,1) element.
a_perim = [topRow, rightCol', bottomRow, leftCol']
a_perim = 1×14
3 2 6 6 4 7 3 8 8 4 10 7 8 1
If you want a different ordering, let me know what it is.

类别

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

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by