# Find index of Array Element in Matlab, an Efficient Way

This tutorial introduce a quick and efficient way to find index of array element in matlab.

Suppose all elements in array1 are contained in array2, now we want to get the indices of array1’s elements in array2.

Here is a simple and neat solution, using Matlab’s arrayfun function, which applies a function to each element of an array.

array1=[1,6,2,3,7];
array2=[3,6];
arrayfun(@(x)find(array1==x,1),array2)

The key in this method is using the arrayfun() function, which applies the specified function to each element of the array.

The syntax of the arrayfun() function is

[B1,...,Bm] = arrayfun(func,A1,...,An)
[B1,...,Bm] = arrayfun(func,A1,...,An,Name,Value)

Here func is a handle to the specified function that accepts n input arguments and returns m output arguments.

For example:

arrayfun(@(x,y)sqrt(x^2+y^2),3,4)

gives the output of 5.

Similarly, the cellfun function serves the same purpose but works for cells.

Subject
Category
Coding language