MATLAB: Write loop for read then write multiple files

binaryfopenfor looplooploopsmultiple

Hi!
I've wrote a script for read a binary float32 file, then write it into a txt file. I works for one file, but i have several binary files. The file names are 001001.bin,001002.bin…etc.
Here is the original loop:
fname='D:\001001.bin';
fid = fopen(fname);
data = fread(fid,'float32');
dlmwrite('001001.bin.txt',data,'precision','%10.5f','newline','pc')
I tried to make a loop, but it has an error message: "In an assignment A(:) = B, the number of elements in A and B must be the same."
Here is the loop:
v=dir('*.bin')
for i=1001:v
fname(i)='D:\00(i).bin';
fid(i) = fopen(fname(i));
data(i) = fread(fid(i),'float32');
dlmwrite('00(i).bin.txt',data(i),'precision','%10.5f','newline','pc')
end
Thanks for helping!

Best Answer

This is not meaningful:
v=dir('*.bin')
for i=1001:v
dir replies a struct, which contains file names, dates, sizes and a flag, if it is a file or folder. Then 1001:v is not an option.
fname(i)='D:\00(i).bin';
This tries to assign the char vector 'D:\00(i).bin' to the scalar element fname(i). But this cannot work, because you cannot store a vector in a scalar. In addition "(i)" is not, what you want, but you want to replace the "i" by a number. Use sprintf for this.
data(i) = fread(fid(i),'float32');
Again a vector is assigned to a scalar.
Folder = cd; % Better define this explicitly
FileList = dir(fullfile(Folder, '*.bin'));
for iFile = 1:length(FileList)
FileIn = fullfile(Folder, FileList(iFile).name);
[fid, msg] = fopen(FileIn);
if fid == -1
error('Cannot open file: %s', FileIn);
end
data = fread(fid, 'float32');
fclose(fid); % Close the file - important!
FileOut = [FileIn, '.txt'];
dlmwrite(FileOut, data, 'precision', '%10.5f', 'newline', 'pc');
end
By the way: Text files are a bad option for storing numerical data. The limited precision reduces the accuracy, the conversion to numbers is expensive, the files are larger and the advantage of text files does not matter here: that a human can edit the file.
Instead of taking the file names from dir, you can create them also:
for iFile = 1001:1000 + numel(FileList)
File = fullfile(Folder, sprintf('%.6d.bin', iFile));
...
The '%.6d' format specifier inserts leading zeros such that the output has 6 digits.