Colon input to anonymous function

If I define a function:
F = @(x,y) (x^2-y)
If I call the function with two scalar inputs it works as expected,
F(2,3) = 1,
Calling with a single colon input returns an "index exceeds matrix dimensions" error, and calling with two colon inputs
F(:,:) = 3306
evaluates the function as if each input was the seemingly arbitrary scalar 58.
Can someone explain this behavior or link me to some documentation explaining this behavior? There doesn't seem to be anything about colon inputs on the anonymous functions doc page
Thanks.

 采纳的回答

If you create the above as a function/script, and step through the code, it will reveal something
function [v] = test(x,y)
v = (x^2-y);
Put a breakpoint at the initialization of v. In the Command Window type
test(:,:)
Now when the debugger pauses at the first line, look at the inputs for x and y. They are 1x1 char with the colon value.
The decimal ASCII value for a colon is 58, so there is an implicit conversion from the character to the decimal/numeric equivalent before the evaluation.
Hope that this helps!

更多回答(1 个)

Matt J
Matt J 2014-7-27
编辑:Matt J 2014-7-27
Colons are treated as char variables throughout MATLAB and the ASCII code for ':' is 58. In general, it is possible to do arithmetic and other numerical operations with character variables, in which case MATLAB assumes you want to do the arithmetic with the underlying ASCII values, e.g.,
>> ':'+':'
ans =
116
Want to know what you get when you cross a dog with a cat?
>> cross('dog','cat')
ans =
2885 -1403 -1289

类别

帮助中心File Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by