matlabFunction: Why the extra ".0" and why only sometimes?
    조회 수: 5 (최근 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에서 Matrix Indexing에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!







