Wouter Kuijsters
Wouter Kuijsters

Reputation: 840

Retrieve column and row elements based on single element

Given a m x n matrix, how can I obtain the ordered (top-left to bottom-right) entries from the column and row corresponding to a given index without the indexed element itself?

For example, given the 5 x 5 magic square matrix A I'd like to retrieve the column and row elements corresponding to the (4,2) element:

A =
    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

This should yield:

B =
    24     5     6    10    19    21     3    18

alternatively, requesting the (5,5) element would yield:

B =
    15    16    22     3    11    18    25     2

or, for (3,2) we'd have:

B =
    24     5     4    13    20    22    12     18

Upvotes: 2

Views: 39

Answers (1)

Divakar
Divakar

Reputation: 221514

If the order of elements in output B isn't important you can use this -

B = setdiff([A(:,col_id).' A(row_id,:)],A(row_id,col_id),'stable')

If the order is important, this messy solution looks fit -

B = [A(1:row_id-1,col_id).' A(row_id,1:col_id-1) ...
                                    A(row_id,col_id+1:end) A(row_id+1:end,col_id).']

Upvotes: 3

Related Questions