I am performing a simulation many many times, and would like to store the result in a csv file.
I could just save the results in an array and write the array to a csv, but the array would be very large and a big strain on my system.
I was thinking it could be easier to simulate, save the result of one simulation in a csv, complete a new simulation, and then store the new result in the second line of the csv.
How can I write csv lines one by one in matlab?
Easy, use: dlmwrite(filename,M,'-append')
For example:
simulation_results = [1,2,3,4]
dlmwrite('C:\<Your Directory Path>\simulaton_results.csv', simulation_results, '-append');
This will append the simulation_results matrix to the end of the file you specify. The default delimiter is a comma ... perfect for writing csv files.
Try fprintf
%save to file
%save using fprintf function
fid_out = fopen('file_out.csv','w'); %open file and create fid
%save tab-separated column headers
%define column format and names and save to file
fprintf(fid_out,'%s\t%s\t%s\t%s\n','a_name','b_name','c_name','d_name');
%save tab-separated columns of data
for i = 1:size(data,1) %loop trough each line of each data variable and save to file line by line
%define column format and date to be saved.
%use () for numeric data, and {} for strings
fprintf(fid_out,'%s\t%s\t%d\t%.5f\n',a{i},b{i},c(i),d(i));
end
fclose(fid_out); %close file
%NOTE: fprintf cannot save structured data
Related
I have a txt file below as shown in the attached figure:
a 0.15
ne 1e25
density 200
pulse_num 2
Is has n rows, 2 data on each row. The first data is a sting that contains the field name, and the second data contains the value. The two data is separated by a space. How do I load this txt file into a matlab structure? Basically I want something like:
whatIwant = struct('a', 0.15, 'ne', 1e25, 'density', 200, 'pulse_num', 2)
I only know how to load it to a table (using readtable), and I can convert the table to a cell, then to a structure. Problem is that I don't know how to append a structure. I don't want to input the field names in my code, so if I change the field names (or don't know the field names) the final structure will have the appropriate field names.
Or are there other simple ways to load it directly?
This can be done using:
fid = fopen('info.txt'); %Opening the text file
C = textscan(fid, '%s%s'); %Reading data
fclose(fid); %Closing the text file
%Converting numeric data stored as strings in a cell to numeric data using cellfun
s=cell2struct(cellfun(#str2double,C{2},'un',0),C{1},1); %Converting into a structure array
Read the documentation of fopen, textscan, fclose, cellfun and cell2struct for details.
I have created a script to create ~300 variable names in my workspace. I need to save these .mat files to .txt files - is there any way to call these variables in some sort of loop or just save them all at once to .txt files?
They are all cells of varying size, about 1000x5 on average.
The first row of the data contains strings, the other elements are all non integer numbers.
Here is an example of one of the .mat files-
http://www.yourfilelink.com/get.php?fid=1065782
I don't know a whole lot about Matlab so any help would be really appreciated! Thank you.
A possible solution could be:
to load the .matfiles through a loop (the name of the file can be either dynamically generated or read from a list)
to extract the first row of the cellarray (the string) and write it in a .txt file by using the dlmwrite function
to remove the first row and write (again with dlmwrite) the numerical values in the .txt having converted them using the cell2mat function.In the writing of the numerical values, the precision has to carefully set.
file_name_root='x2413';
% dummy loop (one iteration) just to test dynamic filename generation
for i=3:3
% generate the name of the input file
input_file_name=[file_name_root int2str(i)];
% generate the name of the output file
output_file_name=[file_name_root int2str(i) '.txt'];
% extract the name of the cellarray and assign it to "the_cell" variable
tmp=load(input_file_name);
var_name=char(fieldnames(tmp));
eval(['the_cell=tmp.' var_name ';'])
[r,c]=size(the_cell);
str='';
% get the first row string (probably a cleaver way to do it exists)
for i=1:c
str=[str ' ' char(the_cell(1,i))];
end
% print the first row in a ".txt" file
dlmwrite(output_file_name,sprintf('%s',str),'delimiter','')
% remove the first row
the_cell(1,:)=[];
% write the numerical values in the ".txt" file
% the "precision" shall be carefully set
dlmwrite(output_file_name,cell2mat(the_cell),'precision','%13.9f','delimiter',' ','-append')
end
I need to read a txt dataset and do some analytics by matlab. the structure of the txt file is like this:
ID Genre AgeScale
1 M 20-26
2 F 18-25
So, I want to load this txt file and build a matrix. I was wondering if someone could help me with this. I used fopen function but it gives me a single array not a matrix with 3 columns.
MATLAB has an interactive data importer. Just type uiimport in the command window. It allows you to:
Name the variable based on heading as shown in your example. You can also manually change them.
Specify variable (column) type, e.g. numeric, cell array of strings, etc.
Auto generate an import script for next use (if desired)
If it works for you then congratulations, you don't need to waste hours to write an data import script :)
Function fopen only returns the file ID and not the content of the file. Once you open the file you use the file ID to read line by line and then parse each line with strsplit using space as the delimiter.
Here's one simple way of doing so:
fid = fopen('textfile.txt');
tline = fgetl(fid);
n = 1;
while ischar(tline)
data(n,:) = strsplit(tline(1:end-1),' ');
n=n+1;
tline = fgetl(fid);
end
fclose(fid);
Keep in mind that the matrix data is type string and not numeric, so if you want to use the numeric values of your dataset, you'll need to take a look at the functions str2num (str2double in newer versions) and strtok to split the AgeScale strings with delimiter '-'.
I have a very large matrix (M X N). I want to divide matrix into 10 equal parts (almost) and save each of them into a separate file say A1.txt, A2.txt, etc. or .mat format. How can I do this ?
Below is a code to divide a matrix into 10 equal parts and data_size is (M / 10).
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
save data(i).mat data
% What should I write here in order to save data into separate file data1.mat, data2.mat etc.
end
You said you wanted it in either txt format or mat format. I'll provide both solutions, and some of this is attributed to Daniel in his comment in your post above.
Saving as a text file
You can use fopen to open a file up for writing. This returns an ID to the file that you want to write to. After this, use fprintf and specify the ID to the file that you want to write to, and the data you want to write to this file. As such, with sprintf, generate the text file name you want, then use fprintf to write data to your file. It should be noted that writing matrices to fprintf in MATLAB assume column major format. If you don't want your data written this way and want it done in row-major, you need to transpose your data before you write this to file. I'll provide both methods in the code depending on what you want.
After you're done, use fclose to close the file noting that you have finished writing to it. Therefore, you would do this:
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
filename = sprintf('A%d.txt', i); %// Generate file name
fid = fopen(filename, 'w'); % // Open file for writing
fwrite(fid, '%f ', data.'); %// Write to file - Transpose for row major!
%// fwrite(fid, '%f ', data); %// Write to file - Column major!
fclose(fid); %// Close file
end
Take note that I space separated the numbers so you can open up the file and see how these values are written accordingly. I've also used the default precision and formatting by just using %f. You can play around with this by looking at the fprintf documentation and customizing the precision and leading zero formatting to your desire.
Saving to a MAT file
This is actually a more simpler approach. You would still use sprintf to save your data, then use the save command to save your workspace variables to file. Therefore, your loop would be this:
for i=1:10
if i==1
data = DATA(1:data_size,:);
elseif i==10
data = DATA((i-1)*data_size+1:end,:);
else
data = DATA((i-1)*data_size+1: i*data_size,:);
end
filename = sprintf('A%d.mat', i); %// Generate file name
save(filename, 'data');
end
Take note that the variable you want to save must be a string. This is why you have to put single quotes around the data variable as this is the variable you are writing to file.
You can use
save(['data' num2str(i) '.mat'], 'data');
where [ ] is used to concatenate strings and num2str to convert an integer to a string.
I have a question about outputting some results to a text file in MATLAB. Essentially I have read in data from 50000 files (numbered sequentially from 1 to 50000) and I have plotted it. Only those files which meet a certain condition are plotted. I now want to add some code which will allow me to write text to a data file. The specific text I want to write is the file numbers (from 1 to 50000) which meet the certain condtions and have been plotted.
When I try and do this the plots work fine but the text file only contains the last file number. For example if the last file number to fulfil the conditions to be plotted is 50000, then the text file only contains 50000. I am unsure how to change the code - any help/advice/tips would be appreciated.
start_sim=1;
end_sim=50000;
h = zeros (1,10000);
for i=start_sim:end_sim
a=int2str(i);
File =strcat('result_', 'simulation', '_', a, 'I_byCal_totale.out');
est_tot=importdata(File, '\t', 1);
cal_tot=est_tot.data;
magnitude=1;
t1=cal_tot(:,1)+1750;
model=cal_tot(:,3)+cal_tot(:,5);
if (model(211)>=25)
if (model(211)<=150)
h(a)=plot(t1,model);
xlim([1910 1970]);
ylim([0 500]);
hold all
clickableLegend(h(a),a,'Location','BestOutside')
%Generate OutputFile
fid = fopen('Modeloutputs.in','w+');
%Generate some text to write in the file (e.g. the simulation number)
% Print the text in the file
fprintf(fid,h(a),'\t','\n');
%close the file
fclose(fid);
end
fid = fopen('Modeloutputs.in','a+');
should do your job. Your initial attempt using 'w+' will
Delete the contents of an existing
file or create new file, and open it
for reading and writing.
as the documentation says. Another option is to move fopen & fclose outside of your loop which I would favor.