Exporting data from for loop into text file

3 views (last 30 days)
Currently I have a for loop running and I'm trying to export the data from the for loop into a text file. I tried the following but it gives me all the data in a row:
x = (1:size(BOLD,1))./1.16E6;
y = BOLD;
xy = [x(:), y(:)];
dlmwrite('YourOutputFile.txt', xy, 'delimiter', ',');
(BOLD is the variable that I plotted which I need the numerical data for)
Is there a way to export the data in a way so that it gives me all the data sets in separate files (one file per graph produced)?
Thank you in advance!

Accepted Answer

per isakson
per isakson on 3 Apr 2019
Edited: per isakson on 3 Apr 2019
"gives me all the data in a row:" This script produces two columns
%%
BOLD = reshape( (1:6), [],1 );
x = (1:size(BOLD,1))./1.16E6;
y = BOLD;
xy = [x(:),y(:)];
%%
dlmwrite('d:\tmp\YourOutputFile.txt', xy, 'delimiter', ',');
%%
type('d:\tmp\YourOutputFile.txt')
outputs
8.6207e-07,1
1.7241e-06,2
2.5862e-06,3
3.4483e-06,4
4.3103e-06,5
5.1724e-06,6
"all the data sets in separate files" You need a new filename for each iteration of the loop
In response to comment:
"the data from the for loop into a text file"
To append new data to an existing file use
dlmwrite(filename,M,'-append')
See dlmwrite, (Not recommended) Write matrix to ASCII-delimited file. (If the file doesn't exist a new file is created.)
"all the data sets in separate files", "have a new filename for each iteration?"
My way
%%
for jj = 1 : 3
name = sprintf( 'YourOutputFile_%04d.txt', jj );
ffs = fullfile( 'd:\tmp', name );
dlmwrite( ffs, xy, 'delimiter',',' );
end
outputs
name =
'YourOutputFile_0001.txt'
name =
'YourOutputFile_0002.txt'
name =
'YourOutputFile_0003.txt'
and there are others
  2 Comments
Hima Sheth
Hima Sheth on 3 Apr 2019
Hi! I'm fairly new to MATLAB so how would I program it so that I have a new filename for each iteration?

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!