zsljulius
zsljulius

Reputation: 4113

How to subset a matrix by index

A = [1 2 3; 4 5 6]
r_idx = [1 2]
c_idx = [1 2]
A(r_idx,c_idx) = [1 nan nan; nan 5 nan]

In other words, it should return the (1,1) and (2,2) elements of A and setting all other entries to be nan.

Is this possible to do?

Upvotes: 0

Views: 65

Answers (2)

Divakar
Divakar

Reputation: 221684

One approach with sparse -

A(full(sparse(r_idx,c_idx,1,size(A,1),size(A,2)))==0) = nan

Or with setdiff -

A(setdiff(1:numel(A),sub2ind(size(A),r_idx,c_idx))) = nan

Upvotes: 2

hiandbaii
hiandbaii

Reputation: 1331

A = [1 2 3; 4 5 6];
r_idx = [1 2];
c_idx = [1 2];
B = nan(size(A));
B(sub2ind(size(A),r_idx,c_idx)) = A(sub2ind(size(A),r_idx,c_idx));

then, desired result is in B

Upvotes: 4

Related Questions