I'll define a sizeFunc
to play with:
Clear[sizeFunc]
sizeFunc[a] = {1, 1}; sizeFunc[b] = {1, 1}; sizeFunc[c] = {3, 2};
sizeFunc[d] = {2, 4}; sizeFunc[e] = {1, 1}; sizeFunc[f] = {1, 1};
UPDATE:
OP mentioned the desired behavior when all elements return {1, 1}. Taking that into consideration, one can define the following function:
firstnonscalar[l_List] := Module[
{position},
If[(position = First@FirstPosition[l, el_ /; sizeFunc[el] != {1, 1}]) != "NotFound",
position,
Length[l]
]
]
As requested, this will return the position of the first element whose sizeFunc
does not return {1, 1}, or alternatively the Length
of the list, which is the position of the last element.
Original answer:
In my understanding of your question, you want the (position of) the first element whose sizeFunc
is not {1,1}
.
If you want the element itself, then the following would work:
SelectFirst[{a, b, c, d, e}, sizeFunc[#] != {1, 1} &]
(* Out: c *)
If you want the position of that element in the list, then the following would work instead:
First@FirstPosition[{a, b, c, d, e}, el_ /; sizeFunc[el] != {1, 1}]
(* Out: 3 *)
Here is what happens to these functions if there are no elements for which sizeFunc
is different from {1, 1}
:
Clear[sizeFunc]
sizeFunc[a] = {1, 1}; sizeFunc[b] = {1, 1}; sizeFunc[c] = {1, 1};
sizeFunc[d] = {1, 1}; sizeFunc[e] = {1, 1}; sizeFunc[f] = {1, 1};
SelectFirst[{a, b, c, d, e}, sizeFunc[#] != {1, 1} &]
First@FirstPosition[{a, b, c, d, e}, el_ /; sizeFunc[el] != {1, 1}]
(* Out:
Missing["NotFound"]
"NotFound"
*)
You didn't specify what to do in that case, so I'll leave the handling of those cases to whatever is best to your application.
=!=
might be useful. $\endgroup$Dimensions[ ]
? $\endgroup$Dimensions[]
has nothing to do with it, I have my own functionsizeFunc[]
and I'm searching for the first element from the left whose size is not{1,1}
$\endgroup$LengthWhile[list, sizeFunc[#] == {1,1}&]+1
. I thinkFor
is pretty awful in Mathematica and can always be avoided. If you do need a procedural loop, useDo
which at least localizes the iterator, and is more compact and more readable. $\endgroup${1,1}
, the returned value exceeds list dimensions by 1. How do I bound the value to the length of the list? $\endgroup$