Eric Morgan
Eric Morgan

Reputation: 11

How do I find the indices of the elements of one vector in a matrix in Matlab?

Suppose I have a 9x9 matrix A that that consists of integers. I have another matrix IDX that's 2500x4 and consists of the same integers in A. I want to find the indices of all the values in IDX in the matrix A.

Here's what I have:

for ii=1:length(IDX)
     Mat_idx=ismember(A,IDX(ii,:));
     [StatIdxX StatIdxY] = find(Mat_idx);
end

Now for each ii the StatIdxX and StatIdxY are the row and col indices of IDX in the matrix A. This is slow, and the culprit is ismember

Any thoughts on speeding this up?

Thanks.

Upvotes: 0

Views: 100

Answers (1)

user2212608
user2212608

Reputation:

first flatten A with A=A(:), that will make a single linear index instead of row,col. Then just use logical indexing. For example:

B=zeros(size(IDX));
for n=1:numel(A)
B(IDX==A(n))=n;
end

Upvotes: 3

Related Questions