Hello, i was writing the following piece of code, in order to get names for some files and at specific numbers seems that sprintf produces wrong results
wv=0:0.2:4;
for i=1:length(wv)
sprintf('%.2d', wv(i)*10)
end
and the resultus i am getting
ans =
04
ans =
6.00e+00
ans =
08
ans =
10
ans =
1.20e+01
ans =
1.40e+01
ans =
16
so it seems wrongly formatted (which causes me problem , because i am constructing filenames with those)
i am using matlab 2013a at a macbook pro (2015)
i found a simple solution by having another variable (wvv=0:2:40) and avoid to multiple in sprintf
so i am just reporting this problem i think it is a bug

댓글 수: 1

Walter Roberson
Walter Roberson 2017년 1월 27일
The problem is that the values are not integers because of floating point round off. Just like 0.33 added 3 times does not add up to 1, if you add up the representation of 0.2 multiple times you do not always get an integer. Numbers are not represented in decimal.

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

답변 (2개)

Adam
Adam 2017년 1월 27일
편집: Adam 2017년 1월 27일

0 개 추천

The help suggests this if you want true integers from floats:
wv=0:0.2:4;
for i=1:length(wv)
sprintf('%.2d', round( wv(i)*10) )
end
If you create the vector e.g.
wv2 = wv * 10;
and look at it in the variable editor you will see this same behaviour, arising from floating point maths. sprintf does similarly.
the cyclist
the cyclist 2017년 1월 27일
편집: the cyclist 2017년 1월 27일

0 개 추천

Others were quicker than I was to point out why this is expected behavior, so please see those responses. I'll just add that if you type
format long
10*wv'
then you'll see the issues immediately.
I think you can probably get what you intended if you use the format spec
sprintf('%2g', wv(i)*10)
instead.

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

질문:

2017년 1월 27일

편집:

2017년 1월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by