Ozg
Ozg

Reputation: 391

Find the indices of a specific element in a 2D matrix

I want to find a specific value's indices in a 2D matrix. For example there is a matrix such as:

A = 
    0 0 8 8 1
    0 6 7 1 1
    5 1 1 1 1

Here, I want to get the indices of "0". So, there should be an array like:

indices = [(1,1) (1,2) (2,1)]

How can I do that? I tried to use find() function but it just returns one coordinate. However, I want to get all coordinates of "0".

Upvotes: 3

Views: 26631

Answers (1)

Dan
Dan

Reputation: 45752

You need to use two outputs for find:

[row,col] = find(A==0)

The single output you got was the linear index. This is the element number by counting down the columns e.g. for your matrix these are the linear indices:

1  4  7  10
2  5  8  11
3  6  9  12

which you could also use to locate an element in a matrix (so for your example the zeros are at linear index 1, 2 and 4). But what you're asking for is the subscript index, for that you need to provide find with 2 output variables.

but if you want to get a matrix exactly like your indices you need to concatenate my row and col matrices:

indices = [row, col]

Upvotes: 4

Related Questions