How to select specific entries of a matrix?

5 views (last 30 days)
Let the matrix A be
A=[a_11 a_12 a_13 a_14;a_21 a_22 a_23 a_24;a_31 a_32 a_33 a_34; a_41 a_42 a_43 a_44];
how to select the following entries
a_12, a_14, a_21, a_23, a_32, a_34, a_41, a_43
In general, how to select the entries in the above pattern for large size of matrix.
The above entries can be obtaind by
for odd rows and even columns
B=A(1:2:end,2:2:end)
for even rows and odd columns
C=A(2:2:end,1:2:end)
but I want the combine results of B and C i.e.,
Ans1=[a_12 a14;a_21 a_23;a_32 a_34;a_41 a_43]
Ans2=[a_12 a14;a_23 a_21;a_32 a_34;a_43 a_41]
how can we obtained Ans 1 and Ans 2 for large square matrix.

Accepted Answer

Awais Saeed
Awais Saeed on 21 Aug 2021
I am writing a generic code so you can get an idea how to do what you need (which is how do you pick elements in particular manner).
clc;clear all;close all;
A = sym('A', [4 4])
% A = (symbolic 4×4 matrix)
%
% ⎡A₁₁ A₁₂ A₁₃ A₁₄⎤
% ⎢ ⎥
% ⎢A₂₁ A₂₂ A₂₃ A₂₄⎥
% ⎢ ⎥
% ⎢A₃₁ A₃₂ A₃₃ A₃₄⎥
% ⎢ ⎥
% ⎣A₄₁ A₄₂ A₄₃ A₄₄⎦
result = sym('result', [4 2])
for row = 1:1:size(A,1)
if (mod(row,2) ~= 0) % check if row number is even or odd
result(row,:) = [A(row,2:2:4)]
else
result(row,:) = [A(row,1:2:3)]
end
end
% result = (sym 4×2 matrix)
%
% ⎡A₁₂ A₁₄⎤
% ⎢ ⎥
% ⎢A₂₁ A₂₃⎥
% ⎢ ⎥
% ⎢A₃₂ A₃₄⎥
% ⎢ ⎥
% ⎣A₄₁ A₄₃⎦
  5 Comments
Awais Saeed
Awais Saeed on 21 Aug 2021
You are welcome. All three snippets are actually doing the same thing. Its just the form of answers that are different (separate or combined or generic etc). Accepting this thread means you have been answered.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by