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

3,888 次查看(过去 30 天)
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
Walter Roberson 2018-2-15
编辑:MathWorks Support Team 2020-2-27
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.
  2 个评论
Walter Roberson
Walter Roberson 2022-7-20
find() can never return 0. Perhaps you are looking at ans for a different operation?


更多回答(4 个)

Bhagyesh Shiyani
Bhagyesh Shiyani 2019-12-5
what if i want both 8 positions, any code?
  2 个评论
Walter Roberson
Walter Roberson 2020-1-15
This will not return value and index, it will return row and column numbers.


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

Sorne Duong
Sorne Duong 2021-7-21
a = 1, 3, 6, 9, 10, 15
We know the fourth value is 9, but how to find the fourth value in MATLAB?
  4 个评论


Nilesh Kumar Bibhuti
编辑:Walter Roberson 2021-10-15
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
int arr[MAX_SIZE] ,brr[MAX_SIZE] ;
int size, i, toSearch, found ,k=0;
/* Input size of array */
printf("Enter size of array: ");
scanf("%d", &size);
/* Input elements of array */
printf("Enter elements in array: ");
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
printf("\nEnter element to search: ");
scanf("%d", &toSearch);
for (i = 0; i < size; i++)
if (arr[i] == toSearch)
brr[k] = i+1 ;
printf("%d ",brr[k]);
k++ ;
return 0;
  1 个评论
Walter Roberson
Walter Roberson 2021-10-15
In C, int size should really be size_t size and your scanf() should be using %lu instead of %d . i and k should also be size_t
You should be checking the return status of each scanf() call .
int main()
should be
int main(void)
unless you are using K&R C from before C was standardized.
The user is expecting the positions to be returned, rather than displayed.
You probably shouldn't be assuming integer for the array, but that would be an acceptable limitation if specifically documented.
You do not use or initialize found.



Help CenterFile Exchange 中查找有关 Whos 的更多信息


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by