2

I'd like to write several messages and tables on the same .txt file.

For example:

x=[23.9,10.9,8.9,14.2]
y=[9.83,8.04,7.47,8.32]

file=fopen('Results.txt','wt');
fprintf(file,'Results1\n');
fprintf(file,'%.2f %.2f\r\n',x,y);
fprintf(file,'Results2\n');
fclose(file);

I get this result as .txt:

Results1
23.90  10.90

8.90  14.20

9.83   8.04

7.47   8.32

Results2

But I should get this one:

Results1
23.90 9.83

10.90 8.04

8.90 7.47

14.20 8.32

Results2

Instead of fprintf(file,'%.2f %.2f\r\n',x,y);), I was trying to use:

ResultsTable2 = table(x,y);
writetable(file,ResultsTable2);

but didn't succeed. How to write the required .txt file?

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58

2 Answers2

2

Careful examination of your output shows that all the elements of x were printed before all the elements of y.

The documentation confirms that this is the expected behavior. Check out this example

A1 = [9.9, 9900];
A2 = [8.8,  7.7 ; ...
      8800, 7700];
formatSpec = 'X is %4.2f meters or %8.3f mm\n';
fprintf(formatSpec,A1,A2)

X is 9.90 meters or 9900.000 mm

X is 8.80 meters or 8800.000 mm

X is 7.70 meters or 7700.000 mm

Even though the arguments to fprintf are in the order A1, A2. It first prints all the values from A1, and then it prints all the values from A2 going in single index order.

Therefore, if you want to alternate values from x and y during printing, you need to interleave them in a new variable. There are several possible ways to do so.

One example,

XY = reshape([x;y], 1, []);

Then everything should print as expected

fprintf(file, '%.2f %.2f\r\n', XY);
% or if you want to print to command window
% fprintf('%.2f %.2f\r\n', XY);

23.90 9.83

10.90 8.04

8.90 7.47

14.20 8.32

Cecilia
  • 4,512
  • 3
  • 32
  • 75
2

The correct answer for how to output data with fprintf is given by Cecilia: each argument will be iterated completely through in the order it appears in the argument list, so you have to combine the data into one matrix argument that will be iterated through column-wise to generate the desired output.

You also mentioned trying to use a table and the writetable function, so I though I'd add the correct way to do that in case you were curious:

ResultsTable2 = table(x(:), y(:));  % Pass data as column vectors
writetable(ResultsTable2, 'Results.txt', 'WriteVariableNames', false);
gnovice
  • 125,304
  • 15
  • 256
  • 359