# Testing for a vector of reals [closed]

Suppose I define:

RealVector[expr_]:=VectorQ[expr,NumberQ[#]&&Head[#]===Real)];


Then:

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


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

• 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! – user9660 Jan 27 '15 at 5:51
• – Kuba Jan 27 '15 at 9:48
• The reason is you need a &: RealVector[expr_] := VectorQ[expr, NumberQ[#] && Head[#] === Real &] – Michael E2 Jan 27 '15 at 12:05

In Mathematica, Element[1,Reals] returns True since integers are subset of the reals. But Head 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) &])


Now

 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.

• 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. – Carlos Felippa Jan 27 '15 at 22:57

RealVector = MatchQ[#, {__Real}] &

realVector[expr_] := VectorQ[expr, # \[Element] Reals &];

• 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. – Nasser Jan 27 '15 at 8:11