Vinod
Vinod

Reputation: 4352

How can I quickly write a fixed point matrix to a file in matlab?

I have a piece of code in matlab to write a fixed point matrix to a text file. One element of the matrix B must in one line of the text. Each line of the 'binary.txt' file will contain one element of B. Let r1,r2,...,r100 be the rows of matrix B. Suppose that the (i,j)th element of B is x and its binary respresentation be 1101110111011110. Then in the (i*N + j)th line of 'binary.txt', the string 1101110111011110 must be written. Basically stack the rows of B into a long row vector, then transpose the resultant row vector (into a column vector) and write that column vector into a file.

M = 100,N = 10000;
A = rand(M,N);
B = fi(A,1,16,15);
fid = fopen('binary.txt','w');
for i = 1:M
    for j = 1:N
        cval = B(i,j);
        fprintf(fid,'%s\n',cval.bin); % write binary value to the file.
    end    
end
fclose(fid);

The file write portion of the code is slow. How can I make the file writing fast?

Upvotes: 0

Views: 405

Answers (1)

rayryeng
rayryeng

Reputation: 104503

If I understand this problem correctly, B is a matrix of structures where each structure has a field called bin which contains a 16 character string of 0s and 1s. You are trying to write each string in this structure as a separate line in the output file.

You can take all of the strings and form them into a comma-separated list and write all of the strings simultaneously with one string per line.

Do this instead:

% // Your code
M = 100,N = 10000;
A = rand(M,N);
B = fi(A,1,16,15);
fid = fopen('binary.txt','w');

%// New code
B = B.';
fprintf(fid, '%s\n', B.bin);
fclose(fid);

Take note that I had to transpose the matrix B before writing all of the strings simultaneously. The reason why is because when we collect all of the strings into a comma-separated list, this is done in column-major order. Your code is writing the strings in row-major order, and so if you want to process things in row-major order, you need to transpose the matrix before you start working on the data.

Example

clear B
B(1,1) = struct('bin', char(48 + randi(2, 1, 16) - 1));
B(1,2) = struct('bin', char(48 + randi(2, 1, 16) - 1));
B(2,1) = struct('bin', char(48 + randi(2, 1, 16) - 1));
B(2,2) = struct('bin', char(48 + randi(2, 1, 16) - 1));
fid = fopen('binary.txt', 'w');
fprintf(fid, '%s\n', B.bin);
fclose(fid);

I get this for the text file:

1100011111111010
0101110110010110
1100001101110000
1100011110000101

Upvotes: 2

Related Questions