colon operator returns different answer in command window and script

2 views (last 30 days)
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.

Answers (1)

Stephen23
Stephen23 on 7 Jan 2022
Edited: Stephen23 on 7 Jan 2022
"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

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!