How to obtain the outermost elements of a 2D matrix ?

3 ビュー (過去 30 日間)
Mehmet
Mehmet 2022 年 10 月 12 日
コメント済み: Akira Agata 2022 年 10 月 12 日
Hello everyone,
How can I obtain the outermost elements of a 2D matrix ?
(For example, the elements that are highlighted in the following picture)

採用された回答

Akira Agata
Akira Agata 2022 年 10 月 12 日
How about the following?
% Sample matrix
M = magic(5);
% Replace non-outermost element as NaN
M(2:end-1, 2:end-1) = nan;
% Extract the outermost elements
idx = isnan(M);
OuterElements = M(~idx)
OuterElements = 16×1
17 23 4 10 11 24 18 1 25 8
  2 件のコメント
Mehmet
Mehmet 2022 年 10 月 12 日
Thank you Akira,
I actually wanted know how to obtain the outermost elements in a given 2D matrix in clockwise manner or anti-clockwise manner?
Akira Agata
Akira Agata 2022 年 10 月 12 日
OK, then how about the follwing solution?
% Sample matrix
M = magic(5)
M = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
% Extract the outermost elements in anti-clockwise manner
OuterElements = M(1:end-1, 1);
for kk = 1:3
M = rot90(M, -1);
OuterElements = [OuterElements; M(1:end-1, 1)];
end
% Show the result
OuterElements
OuterElements = 16×1
17 23 4 10 11 18 25 2 9 3

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by