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.

 Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 27 Jul. 2014

1 Stimme

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!

Weitere Antworten (1)

Matt J
Matt J am 27 Jul. 2014
Bearbeitet: Matt J am 27 Jul. 2014

0 Stimmen

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

Gefragt:

am 27 Jul. 2014

Bearbeitet:

am 27 Jul. 2014

Community Treasure Hunt

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

Start Hunting!

Translated by