Reading binary files with fread

조회 수: 13 (최근 30일)
jnaumann
jnaumann 2013년 12월 10일
답변: Image Analyst 2013년 12월 10일
Hi everyone,
I am trying to read a signal from a binary file. After lots of head scratching I have found a way of doing this. This is my current code.
fid=fopen(filename);
A=fread(fid,'bit8');
New1a=reshape(New1,2,numel(New1)/2);
New1a(1,:)=New1a(1,:)*0.000305176;
ispositive=New1a(1,:)>=0;
New1a(1,ispositive)=(New1a(1,ispositive))+(New1a(2,ispositive)*0.078125056);
New1a(1,~ispositive)=(New1a(1,~ispositive))+((New1a(2,~ispositive)+1)*0.078125056);
Although this works, the method seems a bit convoluted. Have I missed a trick somewhere and is there a easier (and possibly quicker) way of doing the same thing? Here the 0.000305176 is the resolution and the signal range is +/-10V.

답변 (1개)

Image Analyst
Image Analyst 2013년 12월 10일
You don't need to do all that. Just read it in as a 2D array initially. Here, see this snippet from my code:
% Read in image2D image data
% Get original, full-sized 2-D slice.
% Note: fread() requires that x_size and y_size be doubles.
% Note: fread() will return a 2D array if you pass in a 2D array for the number of bytes, as in [x_size y_size].
if stHeader.BytesPerVoxel == 1
oneSlice = fread(fileHandle, [x_size y_size], '*uint8');
elseif stHeader.BytesPerVoxel == 2
oneSlice = fread(fileHandle, [x_size y_size], '*int16'); % It will be a 2D array after this.
else
error('Unsupported BytesPerVoxel %d', stHeader.BytesPerVoxel);
end

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by