Juanito
Juanito

Reputation: 133

Outputting a word file using Matlab

I want to write a function that takes number n as input, then outputs a tab separated word document that looks like 5 rows of:

1 2 3...n n n-1 n-2 ..1

Let me tell you what I have tried already: It is easy to create a vector like this with the integers I want, but if I save a file in an ascii format, in the output the integers come out in a format like " 1.0000000e+00". Now I googled to find that the output can be formatted using %d and fprintf, but given the row length is part of the input, what would be the most efficient way to achieve it?

Upvotes: 0

Views: 103

Answers (2)

Peter Hristov
Peter Hristov

Reputation: 50

If you mean a normal *.txt kind of file, I would normally use a for loop with fprintf(fileid,'%d things to print',5), with the appropriate fopen(.) statement. You'd be surprised what a good job fopen with 'w' and 'a' does. Try it and let us know!

In response to rayryeng: You are right! Here is a sample of code for writing a matrix to file using fprintf, without a for-loop.

A=rand(5);
fid=fopen('Rand_mat.txt','w');
fprintf(fid,'%0.4f %0.4f %0.4f %0.4f %0.4f\n',A');
fclose (fid);

where A is transposed because MATLAB reads the columns of the matrix first.

Thanks!

Upvotes: 1

mathcow
mathcow

Reputation: 71

maybe something like this:

Nrow = 5;
N = 10;
dlmwrite('my_filename.txt', repmat([1:N, N:-1:1], Nrow, 1), 'delimiter', '\t', 'precision', '%d');

Upvotes: 3

Related Questions