Page 1 of 1

Find the index of an element that equal * in a matrix

Posted: Mon Oct 17, 2016 8:25 am
by NikitaG
Is there a command that finds the index of a certain element that equals some value from a matrix (or a vector, or series).
Or the index of the row in which column1 = some value and column2 = some other value.

Re: Find the index of an element that equal * in a matrix

Posted: Mon Oct 17, 2016 8:38 am
by EViews Gareth
There is not. You'll have to loop through the elements.

Re: Find the index of an element that equal * in a matrix

Posted: Mon Oct 17, 2016 9:38 am
by EViews Glenn
I think there are some tricks you can do to make it a bit easier. We'll do an example with vector objects since it's easier, you can do similar things with matrices, using the @vec and @vech and a tiny bit of math.

Here, we create a 10 element vector A and fill it with random normals, but then set A(3)=2. To find the index element containing that value, we can use the @imin function on the squares of the deviations from the desired value. We can then look up the value to make certain that it meets the test.

vector(10) a
nrnd(a)
a(3)=2

!minid =@imin(@epow(a-2,2))
!minval = a(!minid)

For matrices, you can either loop over the columns, or better yet, use the @vec operator to convert into a matrix, then find the minimum vec index and convert that index back into matrix indices.

Note that in all of these cases, the identified value is not unique if there is more than one value meeting the test criterion.

Many other things can be done as a variant of the basic idea.

Re: Find the index of an element that equal * in a matrix

Posted: Wed Oct 19, 2016 9:48 pm
by NikitaG
Thank you!

Re: Find the index of an element that equal * in a matrix

Posted: Thu Nov 03, 2016 2:52 pm
by EViews Glenn
One thing to note: this will give you the index of the closest value so there will be a match, even if there is no value that is equal.