matlabFunction: Why the extra ".0" and why only sometimes?
2 次查看(过去 30 天)
显示 更早的评论
f = @(x)2.^x.*x.^2
f = sym(f)
f = matlabFunction(f)
While functionally irrelevant, it makes formulae difficult to read. Why does it happen, and why only sometimes? More importantly, is there any way to stop it?
0 个评论
采纳的回答
John D'Errico
2023-1-18
编辑:John D'Errico
2023-1-18
Does it really, really, really matter? Actually, there is a (subtle) reason for the 2.0.
You should recognize there is some potential ambiguity in the subexpression
2.*x
Was that intended to be seen as the number 2. multiplied by x using the .* operator, or the integer 2, multipled, using the * operator? And yes, you might decide the difference is not relevant. But might it be relevant? For example:
x = 1:5;
How should this line be evaluated?
x*2.*x'
In terms of the order of operations, MATLAB will multiply x. by 2. Then it needs to multiply that result by the vector transpose(x). But should it use the .* operator? Or the * operator? That is, should the result be:
(x*2).*(x')
In MATLAB, this operation would yield a 5x5 array. But the alternative would be written as
(x*2.) * (x')
And that operation yields a scalar.
The thing is, it very much matters how you interprret that line. Now, consider the expression:
x*2.0.*x
Now there can be no ambiguity, since we know that 2.0 is the number 2. AND that the operator that follows is the .* operator.
Looking at the code you have, again, the 2.0 should always eliminate any confusion.
4 个评论
John D'Errico
2023-1-19
The problem is, 2. is an entirely valid way to write a number. You may not love it. As Per points out, some languages use that as a way to distinguish an integer from a floating point number. MATLAB does not really care in that respect, because 2 and 2. are both used to represent the same number, in both cases stored in a double. Regardless, MATLAB needs to use that form to resolve an ambiguity in MATLAB. If the cost lies in some people not liking the way it looks, it was a choice TMW made and therefore something we need to accept. Oh well.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Function Creation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!