Error in matlab function

조회 수: 2 (최근 30일)
Leonardo Tommasini
Leonardo Tommasini 2017년 11월 7일
답변: Image Analyst 2017년 11월 7일
Hi,
does anybody knows why matlab doesn't calculate the correct value of a function?
I have the function: err_acc = err_acc + (err_corr * dt);
where: err_acc = 0; dt = 0.02; err_corr = -6
and the answer is always 0.
Everything is in int32 type.
Thanks for any help.
Best Regards.
  댓글 수: 2
Leonardo Tommasini
Leonardo Tommasini 2017년 11월 7일
Now I have tried to use typecast(----, 'double'); on every variable, but it goes back to int32 and set the answer to 0.
Do you maybe know why?
Steven Lord
Steven Lord 2017년 11월 7일
Show your exact code. My guess is that you're assigning the result of that computation in double back into an element of an int32 array.

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

채택된 답변

Image Analyst
Image Analyst 2017년 11월 7일
Cast to double:
err_acc = int32(0)
dt = 0.02
err_corr = int32(-6)
err_acc = double(err_acc) + (double(err_corr) * dt)
whos err_acc
In the command window you'll see
err_acc =
int32
0
dt =
0.02
err_corr =
int32
-6
err_acc =
-0.12
Name Size Bytes Class Attributes
err_acc 1x1 8 double
Notice that err_acc is now a double, NOT an int32 anymore.

추가 답변 (2개)

Cam Salzberger
Cam Salzberger 2017년 11월 7일
편집: Cam Salzberger 2017년 11월 7일
Hello Leonardo,
If all variables are of int32 datatype, then they can only contain integer values. Thus, dt would contain 0, rather than 0.02, because when a floating point number is cast to an integer datatype, the non-integer part is dropped.
Even if dt is actually a floating point datatype, if you do a double*integer, MATLAB will make the result an integer datatype:
0.02*int32(-6)
ans =
int32
0
Sounds like you might want to cast everything to double before doing your computation.
-Cam
  댓글 수: 2
Leonardo Tommasini
Leonardo Tommasini 2017년 11월 7일
Now I have tried to use typecast(----, 'double'); on every variable, but it goes back to int32 and set the answer to 0.
Do you maybe know why?
Image Analyst
Image Analyst 2017년 11월 7일
Use double(). See my answer.

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


Geoff Hayes
Geoff Hayes 2017년 11월 7일
Leonardo - if you are expecting a non-integer answer, then the fact that all variables are int32 will prevent this. If the variables are doubles, then
err_acc = 0;
dt = 0.02;
err_corr = -6
the answer is
err_acc = err_acc + (err_corr * dt)
err_acc =
-0.1200

카테고리

Help CenterFile Exchange에서 LEGO MINDSTORMS EV3 Hardware에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by