2

How to save this data (i and a) to a .txt file or .xls file in MATLAB?

for i=1:10
   i
   a=i*2
end

3 Answers 3

4

Use csvwrite to write coma separated values to a text file. You can read it in Excel, and it is a text file at the same time

i=1:10;
a=i*2;
csvwrite('data.csv', [i; a]);
Sign up to request clarification or add additional context in comments.

5 Comments

it is in row form how i can convert it into colume (lets say A1 only). The above code only saved i value and not the a value.how i can save a value?
@t3st I have fixed that already, it saves both i and a now. The second parameter is a matrix. You can save it with any dimensions: csvwrite('data.csv', [i; a]'); will save the data as two columns.
@anginor still its saving in row only, i know that logically [i;a] its a transponse of a matrix,but in excel its still in row form..is csvwrite() can overwrite existing file?
@t3st You probably did not transpose it. Copy the line from the comment above and execute it. Look at the csv file - it now has two columns. If it has two rows it means you did not transpose the matrix.
@anginor hey thanxs, when i run that line alone it worked..once more thank you
2

Matlab provides an file I/O interface similar to that of C: you open a file, output data or formatted text, and close it:

f = fopen( "file.txt", "w" );
for i=1:10,
  a=i*2
  fprintf( f, "%d ", a );
end
fclose( f );  

Comments

2

To save to a text file, there is fprintf, example (from documentation):

x = 0:.1:1;
A = [x; exp(x)];

fileID = fopen('exp.txt','w');
fprintf(fileID,'%6s %12s\n','x','exp(x)');
fprintf(fileID,'%6.2f %12.8f\n',A);
fclose(fileID);

To save to an excel file, there is xlswrite, example (from documentation):

filename = 'testdata.xlsx';
A = [12.7, 5.02, -98, 63.9, 0, -.2, 56];
xlswrite(filename,A)

If you do not have excel installed, this will not work. An alternative is then csvwrite, which you later on can easily import in excel (on another pc eg).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.