2
$\begingroup$

Sorry for the most basic of questions. How would I find the positions of a list of elements which are empty, for example I have the list

a = {1, 2, {}, {}, 3, 5};

and I want to find the indices of the empty elements.

$\endgroup$
5
  • 6
    $\begingroup$ Position[{1, 2, {}, {}, 3, 5}, {}] yields {{3}, {4}} $\endgroup$
    – Artes
    Jun 13, 2013 at 11:02
  • 5
    $\begingroup$ Additionally you can get all elements of the list that are not {} using Cases[{1, 2, {}, {}, 3, 5}, Except[{}]]. $\endgroup$
    – mmal
    Jun 13, 2013 at 11:25
  • 1
    $\begingroup$ This is better DeleteCases[{1, 2, {}, {}, 3, 5}, {}]. $\endgroup$
    – Artes
    Jun 13, 2013 at 12:55
  • $\begingroup$ @Artes I would say its equivalent. $\endgroup$
    – mmal
    Jun 13, 2013 at 15:05
  • $\begingroup$ @mmal It is not. $\endgroup$
    – Artes
    Jun 13, 2013 at 15:47

1 Answer 1

8
$\begingroup$

If you want to find the position of something in a given expression, you should use Position.

In this example, you could simply write:

Position[{1, 2, {}, {}, 3, 5}, {}]
(*{{3}, {4}}*)

I have to mention that this not the whole power of Position: the second parameter of Position can be a "pattern"(which may be not known by a matlab coder:)), look up the doc for more imformation.

$\endgroup$
4
  • $\begingroup$ Great thanks, I know a little about regexp $\endgroup$
    – mor22
    Jun 13, 2013 at 11:28
  • 1
    $\begingroup$ @mor22 a Pattern in Mathematica is different from a regular expression. They're similar in some respects, but a pattern is more broad. $\endgroup$
    – rcollyer
    Jun 13, 2013 at 12:11
  • $\begingroup$ @rcollyer Thanks, I'm still learning! $\endgroup$
    – mor22
    Jun 14, 2013 at 7:22
  • $\begingroup$ Thank you, this is helpful. In some cases, i.e. when importing data, one might need to use {""} instead of {}. $\endgroup$ Sep 13, 2015 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.