1
votes

I have 2 matrices, with one having floating point numbers and the other, integer numbers. Both the matrices have the same number of rows but different number of columns.

I want to write both the matrices together to a file with each single line consisting of a single row from each matrix printed side-by-side.

How should I do this?

My try (unsuccessful) :

    fid = fopen(nameF, 'w'); % Open for writing
    fprintf('%d\n',fid);
    for i=1:size(FloatMat,1)
        fprintf(fid, '%f %d ', FloatMat(i,:),IntMat(i,:));
        fprintf(fid, '\n');
    end
    fclose(fid);
3
What exactly is wrong with it? One thing I would suggest though is to get rid of that trailing space per row: fprintf(fid, '%f %d ', FloatMat(i,:),IntMat(i,1:end-1)); fprintf(fid, '%d\n', IntMat(i,end)); - Dan
Well, as @BlackAdder says in his answer below, alternate float and integer values were getting printed as opposed to all the columns of FloatMat (as float type) and then all the columns of IntMat (as int type). repmat solved the issue for me. - creativesol

3 Answers

1
votes

Your problem is that the %f and %d of your fprintf only refers to the first and second columns. If there are more columns Matlab will repeat the pattern.

So you are saving the first column of FloatMat as float, the second column of FloatMat as Integer, etc...

You must specify the type of each column, but don't worry, you don't have to do it manually, use repmat instead

fprintf(fid, [repmat('%f ',1,size(FloatMat,2)) ' ' ...
              repmat('%d ',1,size(IntMat,2)) '\n'], ...
              FloatMat(i,:), IntMat(i,:));

PD: Note that I have separated the columns with space, as you did. Feel free to use \t or comma to separate them if needed.

PD: Also you can include the \n in the same line, so you can save one line of code.

0
votes

This one actually writes both in float format with 8 digits precision, you will not get %d effect here but is only two lines:

BothMat = [FloatMat IntMat]
save(nameF, 'BothMat', '-ascii')
0
votes

You don't need to complicate things using repmat int his case, just fprintf the float matrix first followed by the int matirx:

nRows = 5;
Mint = magic(nRows);
Mfloat = rand(nRows, 3);
fid = fopen('test.txt','w');
for row = 1:nRows
    fprintf(fid,'%f\t', Mfloat(row,:));
    fprintf(fid,'%d\t',Mint(row,1:end-1)); % only go to end to prevent trailing delimiter after final value of the row
    fprintf(fid,'%d\n',Mint(row,end));
end
fclose(fid);

example output

0.392227    0.276923    0.317099    17  24  1   8   15
0.655478    0.046171    0.950222    23  5   7   14  16
0.171187    0.097132    0.034446    4   6   13  20  22
0.706046    0.823458    0.438744    10  12  19  21  3
0.031833    0.694829    0.381558    11  18  25  2   9