how can i extract this matrix ?

1 view (last 30 days)
diadalina on 17 Oct 2017
Answered: Walter Roberson on 17 Oct 2017
i have a square matrix M of size 12x12 containing the integers from 1 to 144 rows, i want to extract the submatrix containing the coefficients m(i,j) for i + j even, can anyone help me ?

Answers (2)

Image Analyst
Image Analyst on 17 Oct 2017
I offer two methods, one brute force, and one vectorized where the sum of the row index and the column index equals an even number. (Note, this extracts a totally different set of numbers than Guillaume.)
yourMatrix = randi(9, 12, 12) % Create sample data.
% Mathod 1: brute force method:
[rows, columns] = size(yourMatrix);
% See which rows and columns we'll extract out:
index = 1;
for i = 1 : rows
for j = 1 : columns
if rem(i+j, 2) == 0
fprintf('Extracting i=%d, j=%d\n', i, j);
out(index) = yourMatrix(i,j);
index = index + 1;
out = reshape(out, [12,6])
% Method 2: vectorized:
checkerBoardPattern = logical(mod(toeplitz(1:12, 1:12), 2))
out2 = yourMatrix(checkerBoardPattern)
out2 = reshape(out, [12,6])
isequal(out, out2) % Prove that out and out2 are the same.

Walter Roberson
Walter Roberson on 17 Oct 2017
indices_both_even = M(1:2:end,1:2:end)
indices_both_odd = M(2:2:end,2:2:end)
but then what? You have not defined the order of the output. Should it be 12 x 6? Should it be 6 x 12?
If you look at the submatrix [A B; C D] then A and D are both in positions where the sum of the indices is even, but you have not said whether this should result in [A, D] or in [A; D]

Community Treasure Hunt

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

Start Hunting!

Translated by