Question

Another question on fprintf

I have a matrix s(n,5) that I want to shorten (just take columns 3,4 and 5) into s1(n,3) and save with a different name.

s1=s(:,3:5);
txtfilename = [Filename '-1.txt'];
% Open a file for writing
fid = fopen(txtfilename, 'w');
% print values in column order
% two values appear on each row of the file
fprintf(fid, '%f %f %f\n', s1);
fclose(fid);

I don't think I understood the way to use fprintf and rewrite my new matrix, because it is sorting the values.

Thanks for your help

Était-ce utile?

La solution

The problem is that MATLAB stores data in column-major order, meaning that when you do s1(:), the first three values are the first three values in the first column not the first row. (This is how fprintf will read values out of s1.) For example:

>> M = magic(3)
M =
     8     1     6
     3     5     7
     4     9     2
>> M(:)
ans =
     8
     3
     4
     1
     5
     9
     6
     7
     2

You can simply transpose the matrix to output the way you want:

fprintf(fid, '%f %f %f\n', s1.');
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top