problem of reading a double from .mat file in C
이전 댓글 표시
Hi All,
I have a .mat file named "test.mat" which contains an array D=[1,0.2]. I wrote a C program to read the second element (0.2) into a double variable x, and then to store 1000*x into another int variable n. My code follows:
double x;
int n;
pmat = matOpen("test.mat", "r");
pa = matGetVariable(pmat, "D");
x = *(mxGetPr(pa) +1);
cout << "x = " << x << endl;
n = (int)(1000*x);
cout << "n = " <<n << endl;
mxDestroyArray(pa);
return 0;
Surprsingly, the output is:
x = 0.2
n = 199
Why n is 199 instead of 200? What may be the cause?
Many Thanks!
채택된 답변
추가 답변 (1개)
Chirag Gupta
2011년 4월 21일
It might be something to do with precision and and how the floating number was stored. On my MATLAB (R2011a) on mac (64 bit), I get: x =0.2000 n =200
My code is as follows:
#include <stdio.h>
#include "mat.h"
int main()
{
MATFile *pmat;
double x;
mxArray *pa;
int n;
pmat = matOpen("test.mat", "r");
pa = matGetVariable(pmat, "D");
x = *(mxGetPr(pa) +1);
printf("\nx=%lf",x);
n = (int)(1000*x);
printf("\nn = %d\n",n);
mxDestroyArray(pa);
return 0;
}
카테고리
도움말 센터 및 File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!