I know that one can find the index of an element in a List.
However, is there a way to get the positions of an element in a Matrix in the form of {{r1,c1},{r2,c2},…{rn,cn}} where {r1,c1} and {r2,c2} … {rn,cn} are the rows and columns where the element is found.
I was hoping that PositionIndex applied to a matrix would do the job, but the results did not make sense to me.
Can someone tell me if there is a built-in function or a way to use PositionIndex to get the indices of where a particular number can be found.
In fact, because an element may not exactly match an entry in the matrix, I really would like a function to do the following; Return a list of all the {row,col} that are within x% (like 5%) of a number.
I would like F[mat,y,p] to return a list of coordinates (row, col) that are within p% of y.
Hi Henrick.
SeedRandom[1];
data = RandomInteger[10, {10, 2}]
(* {{6, 0}, {2, 6}, {4, 5}, {4, 3}, {0, 1}, {3, 5}, {3, 0}, {3, 2}, {3, 9}, {5, 1}} *)
Position[data, 3]
(* {{4, 2}, {6, 1}, {7, 1}, {8, 1}, {9, 1}} *)
Three is at {4, 2} - row 4 column 2, {6, 1} row 6 column 1 etc.
To find values that are within some range of a number take a look at Nearest.
Hi Richard,
A more functional implementation of your solution.
lowerB = 99.434; upperB = 105.566;
MapIndexed[If[Between[#1, {lowerB, upperB}], {#2, #1}, Nothing] &, exampleMat, {2}] //
Flatten[#, 1] &
(*
{{{5, 37}, 104.}, {{5, 59}, 100.}, {{5, 181}, 100.}, {{5, 629}, 104.}, {{5, 785}, 100.},
{{9, 113}, 102.}, {{9, 295}, 102.}, {{9, 419}, 100.}, {{9, 439}, 102.},
{{12, 99}, 100.}, {{12, 303}, 100.}, {{12, 653}, 100.}, {{12, 707}, 100.},
{{12, 803}, 100.}}
*)
Thank you Rohit! That is perfect! And you anticipated my next question which was how to locate entries that are within a range.
Thanks Rohit,
I will take a look at this other approach.
While browsing through the FunctionRepository I came across PositionedCases which used a Pattern for matching. It does not work with SparseArray, so Normal is required.
ResourceFunction["PositionedCases"][Normal@exampleMat, _?(lowerB < # < upperB &), {2}]
or
ResourceFunction["PositionedCases"][Normal@exampleMat, _?(Between[#1, {lowerB, upperB}] &), {2}]
(*
<|{5, 37} -> 104., {5, 59} -> 100., {5, 181} -> 100., {5, 629} -> 104.,
{5, 785} -> 100., {9, 113} -> 102., {9, 295} -> 102., {9, 419} -> 100.,
{9, 439} -> 102., {12, 99} -> 100., {12, 303} -> 100., {12, 653} -> 100.,
{12, 707} -> 100., {12, 803} -> 100.|>
*)