%sample program to read and write binary files clear all; %produce an array to write out foo = rand(5,5); %write out file using float32 type with no skip and forced little-endian %output fid = fopen('binary_write_1.txt','w'); fwrite(fid,foo,'float32',0,'l'); fclose(fid); %write out array of 8-bit integers using big-endian ordering foo = round(foo); fid = fopen('binary_write_2.txt','w'); fwrite(fid,foo,'int8',0,'b'); fclose(fid); %now read in the above files fid = fopen('binary_write_1.txt','r'); bar = fread(fid); size(bar) %fread defaults to uint8, or an 8-bit unsigned integer %thus the file is read incorrectly here to 100 8-bit values, rather than 25 %32-bit floating point values %try reading file into shaped array, rather than a vector %clear variable bar from before clear bar; %can reset file pointer from fread without closing and reopeing file using %frewind or fseek frewind(fid); %read file bar = fread(fid,[5 5],'float32',0,'l'); fclose(fid); %try reading using wrong byte ordering fid = fopen('binary_write_2.txt','r'); bar = fread(fid,[5 5], 'int8',0,'b'); %if you look at the original input array and bar, they are different %try using correct byte ordering frewind(fid); bar = fread(fid, [5 5], 'int8',0','l');