2

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?

Kuba
  • 136,707
  • 13
  • 279
  • 740

3 Answers3

4

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) &])

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.

Nasser
  • 143,286
  • 11
  • 154
  • 359
  • 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[,{d,f}] to equalize decimals. If not, InputForm[] is used to accommodate symbolic entries. – Carlos Felippa Jan 27 '15 at 22:57
2

Does this fit your needs?

RealVector = MatchQ[#, {__Real}] &
Kuba
  • 136,707
  • 13
  • 279
  • 740
0

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 &];
David G. Stork
  • 41,180
  • 3
  • 34
  • 96
  • 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 08:11
  • An integer is a real number. – David G. Stork Jan 27 '15 at 17:31