I have a .img file of unformatted (I think binary) data that I want to read as floats into a 4D array in Matlab. I noticed that the 'fread' function in Matlab used to read binary data can only read into 1D or 2D arrays automatically, so I tried something like this:
function fileArr4D= load4DFile(dim1, dim2, dim3, dim4, filename)
fileArr4D= zeros(dim1, dim2, dim3, dim4); %initialize array
fid= fopen(strcat('files/', filename));
for l= 1:dim4
for k= 1:dim3
fileArr4D(:, :, k, dim4)= fread(fid, [dim1, dim2], 'float');
end
end
fclose(fid);
fileArr4D= flipdim(fileArr4D, 2); %flips along dimension 2 (of 4)
end
The last line is to flip the data (something specific to the data), and the only reason I included it is in case it is the source of a bug.
Anyways, this function gives me a 4D array, but not with the values I want. I am actually translating some code from IDL to Matlab, and in IDL, the implementation is:
pp=fltarr(dim1,dim2,dim3,dim4)
file='pathto/filename.img'
openr,1,file
readu,1,pp
pp=reverse(pp,2)
close,1
However, comparing the array returned by fileArr4D in Matlab with pp in IDL, the 开发者_JAVA百科min, max, and mean of the arrays are all different. Any ideas as to what is being done differently in the two cases, or of a more natural way to read binary data into a 4D array in Matlab?
Btw, if I switch the order of looping in the Matlab function (for k= 1:dim3, for l= 1:dim4, ...
instead of for l= 1:dim4, for k= 1:dim3, ...
), I get the correct min and max but wrong mean (which is the same mean as before).
Any help in getting the behavior of the IDL snippet into Matlab would be greatly appreciated.
Since you want to use fread
to access the data and it can only read 1D or 2D arrays, I'd suggest loading the data in as a 1D array. Once you have the data as a 1D array, as long as you know what the dimensions are supposed to be, you could call the reshape
function on the 1D array to reformat it as a 4D array of the appropriate size.
精彩评论