Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i want to find the location of a number in a matrix in matlab

Tags:

matlab

I have a matrix lets say

x =
 2     2     3
 4     3     2
 6     4     8

now I want to get the location of a number 4.
I want ans like this :

ans=(2,1) (3,2)

as these are the locations for 4 in matrix.

like image 382
chee Avatar asked Oct 02 '10 18:10

chee


2 Answers

Use find:

[i,j] = find(x == 4)
like image 160
Alex Avatar answered Oct 03 '22 23:10

Alex


ismember will return an array of 1 or 0 depending on if the cell value there is or isn't the value you're searching for:

octave:9> x
x =

   2   2   3
   4   3   2
   6   4   8

octave:10> ismember(x,4)
ans =

   0
   1
   0
   0
   0
   1
   0
   0
   0

And then you can use find and ind2sub to get the array indicies of the 1s:

octave:11> [i,j] = ind2sub(size(x),find(ismember(x,4)))
i =

   2
   3

j =

   1
   2

So that the indicies are (2,1) and (3,2).

like image 27
Jonathan Dursi Avatar answered Oct 03 '22 23:10

Jonathan Dursi