Suppose I define:



RealVector[{1,2,3}];  RealVector[{1.,2.,3.}];

should evaluate to False and True, resp. But I get False and False. Why?

  • $\begingroup$ Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the faq! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! $\endgroup$ – user9660 Jan 27 '15 at 5:51
  • $\begingroup$ related: Real Numbers in the Wolfram Language $\endgroup$ – Kuba Jan 27 '15 at 9:48
  • 2
    $\begingroup$ The reason is you need a &: RealVector[expr_] := VectorQ[expr, NumberQ[#] && Head[#] === Real &] $\endgroup$ – Michael E2 Jan 27 '15 at 12:05

In Mathematica, Element[1,Reals] returns True since integers are subset of the reals. But Head[1] is Integer. So, since you need to check for Head of each element. One way might be

realVector[x_List] := VectorQ[x, NumericQ] && (AllTrue[x, (Head[#] === Real) &])


 realVector[{1., 2., 3.}]  (*True*)
 realVector[{1, 2, 3}]  (*False*)
 realVector[{1., 2., 3}] (*False, since one element is not Real*)
 realVector[{Pi, 1., 2.}] (*False*)

btw, you do not need VectorQ[x, NumericQ] in the above, but I thought it might be faster to short circuit the test. You can also just use

 realVector[x_List] := AllTrue[x, (Head[#] === Real) &]

And this should work also.

  • $\begingroup$ Thanks! The & at the end does the trick. BTW, I dont have AllTrue in the Mathematica version I am using, but it is not needed. The function is used in 8 print modules in a finite element program. If the vector is all reals, entries are printed using PaddedForm[<entry>,{d,f}] to equalize decimals. If not, InputForm[<entry>] is used to accommodate symbolic entries. $\endgroup$ – Carlos Felippa Jan 27 '15 at 22:57

Does this fit your needs?

RealVector = MatchQ[#, {__Real}] &

You have syntax errors (e.g., no & for making a function). Moreover, there is no need to check if an element is a number if you're also checking whether it is in the set of Reals.

This should work for you:

realVector[expr_] := VectorQ[expr, # \[Element] Reals &];
  • $\begingroup$ David, your solution returns True for realVector[{1, 2, 3}], I think the OP wants this to return False. This happens because integer also returns True for Element[#,Reals], so a Head test is needed. $\endgroup$ – Nasser Jan 27 '15 at 8:11
  • $\begingroup$ An integer is a real number. $\endgroup$ – David G. Stork Jan 27 '15 at 17:31

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