Reputation: 8570
I've just accidentally typed the following in Octave:
sqrt 25
and got back:
ans =
7.0711 7.2801
With parentheses, sqrt(25)
returns the correct result. What is happening without the parentheses? Does MATLAB share the same behaviour or is specific only to Octave? I don't have MATLAB so I cannot check.
Upvotes: 1
Views: 452
Reputation:
This is due to the dual way that functions can be called in matlab. For example, load, save, etc, all these tools can be called as a function or as a command. Thus,
load('foo.bar')
load foo.bar
Both are valid ways to use load.
When a function is used as a command, it assumes the input is a string. So
sqrt 25
will in theory try to take the square root of the vector elements in the string it is passed, AFTER converting them to doubles from char. A simple way to see what happens is to convert the string '25' to its ascii equivalent.
+'25'
ans =
50 53
And of course it now should be no surprise that
sqrt([50 53])
ans =
7.0711 7.2801
That it failed in MATLAB but not Octave merely says that TMW has now inserted an error check for character input to sqrt (so that exactly this results in an error, instead of a difficult to debug problem for those who have not ever seen this happen. After all, the square root of a character has no meaning. And there can be little reason to want to compute the square root of the ascii equivalent of a character. So an error is logically what should happen when you use sqrt in the command form.)
Upvotes: 5
Reputation: 2519
Octave is interpreting it as a length-2 char array, and converting these to their ASCII representation (50 and 53), then getting the square root. This can be done in MATLAB by using:
sqrt(double('25'))
MATLAB produces an error that sqrt
isn't defined for char inputs when used without parentheses.
Upvotes: 7