# How to find the position of a number in an array?

6,436 views (last 30 days)
Arnab Pal on 15 Feb 2018
Commented: Walter Roberson on 21 Jul 2021
If I have a vector, a = [7 8 8 2 5 6], how do I compute the positions of the value 8?
I expect 2 and 3 or (1,2) and (1,3).

Walter Roberson on 15 Feb 2018
Edited: MathWorks Support Team on 27 Feb 2020
You can use the “find” function to return the positions corresponding to an array element value. For example:
a = [7 8 8 2 5 6];
linearIndices = find(a==8)
linearIndices =
2 3
To get the row and column indices separately, use:
[row,col] = find(a==8)
row =
1 1
col =
2 3
If you only need the position of one occurrence, you could use the syntax “find(a==8,1)”. You can also specify a direction if you specifically want the first or last occurrence, such as “find(a==8,1,’first’). For more information on these options, see find.

Bhagyesh Shiyani on 5 Dec 2019
what if i want both 8 positions, any code?
##### 2 CommentsShowHide 1 older comment
Walter Roberson on 15 Jan 2020
This will not return value and index, it will return row and column numbers.

Ujjawal Barnwal on 7 Jun 2020
a = [7 8 8 2 5 6];
position = find(a==8)

Sorne Duong on 21 Jul 2021
a = 1, 3, 6, 9, 10, 15
We know the fourth value is 9, but how to find the fourth value in MATLAB?
Walter Roberson on 21 Jul 2021
a = [1, 3, 6, 9, 10, 15]
a = 1×6
1 3 6 9 10 15
a(4)
ans = 9
Unless you mean how to predict the 4th value -- that is, how to find a rule or formula for the values.
Legendré (and others) proved that for any finite set of finite values, that there is a polynomial that goes through all of the values exactly (to within computation error.) So you can construct a polynomial that goes through all of the points. There are an infinite number of expressions that can be used... but because any list of values can be fit, if what you were given was
a = [1, 3, 6, X, 10, 15]
and you were asked to figure out what X is, then the technique of constructing polynomials cannot decide -- there are an infinite number of polynomials that go through (1,1), (2,3), (3,6), (5,10), (6,15) and an infinite number of them have a different value at X = 4. There is a polynomial for [1,3,6,-8,10,15]. There is a polynomial for [1,3,6,10,10,15]. There is a polynomial for [1,3,6,72432015,10,15] .
Because of this, if the question is to figure out what X is given a = [1, 3, 6, X, 10, 15] then the answer has to be "It could be any finite number".