colon operator returns different answer in command window and script

조회 수: 2 (최근 30일)
Dhaval Shah
Dhaval Shah 2022년 1월 7일
댓글: Stephen23 2022년 1월 8일
function trialpoints = fixnode(min, max, gridfine)
if min<0
min_= min - rem(min,gridfine);
else
min_= min - rem(min,gridfine) + gridfine;
end
max_= max -rem(max,gridfine);
trial1 = min_:gridfine:max_;
trialpoints = [min trial1 max];
end
When I call fixnode function with fixnode(0.0261,0.0341,0.005), it will lead to;
trial1 = 0.03:0.005:0.03; which ends up as empty trial1.
While, if I run Variable= 0.03:0.005:0.03 in command line it gives;
Variable=0.03; --> Why difference in behavor between command line and script
Moreover, When I call fixnode function with fixnode(0.0157,0.0207,0.005), it will lead to;
trial1 = 0.02:0.005:0.02;
trial1= 0.02; --> Why this works? but above not above case.

답변 (1개)

Stephen23
Stephen23 2022년 1월 7일
편집: Stephen23 2022년 1월 7일
"colon operator returns different answer in command window and script"
Yes, because you called COLON with different values.
"Why this works? but above not above case."
When you run
0.03:0.005:0.03
ans = 0.0300
in the command windows then the first and last values are exactly the same, so the output is a scalar.
But with your function the first and last values are not the same. You cannot rely on the five or so significant figures displayed in the command window to tell you if some values are the same or not. Once we show the values to higher precision, we can see that they are clearly different:
[out,mn,mx] = fixnode(0.0261,0.0341,0.005)
out = 1×0 empty double row vector
mn = 0.0300
mx = 0.0300
fprintf('%.40f\n',mn,mx); % forty decimal places
0.0300000000000000023592239273284576484002 0.0299999999999999988897769753748434595764
Are those the same value? NO. Lets double check:
mx - mn % same (hint: no)
ans = -3.4694e-18
The value max_ is clearly less than min_, so COLON correctly returns an empty vector for those values.
So far COLON is working exactly as expected and documented.
function [trial1,min_,max_] = fixnode(min, max, gridfine)
if min<0
min_= min - rem(min,gridfine);
else
min_= min - rem(min,gridfine) + gridfine;
end
max_= max -rem(max,gridfine);
trial1 = min_:gridfine:max_;
end
  댓글 수: 2
Stephen23
Stephen23 2022년 1월 8일
@Dhaval Shah: my pleasure! Please click the accept button to tell other users that your query has been answered.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by