loading txt files into matlab structure - matlab

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.

Related

How can I write a csv line by line?

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

How can I import this data and export it to an excel file?

I have 672 samples like these in a .txt file:
{
sleep:1360.36,
eat:4.36,
live:16.37,
travel:22.18,
work:22,
school:0.84,
vt:386.87
},
I want to put them in an excel file where {sleep, eat, live, travel, work, school, vt} are represented in a row and each sample represented in columns, with the correspondent number matching each. I've never dealt with text files following this format on matlab so I have no idea how to do this. Can anyone help me?
You can import data from Excel into Matlab using xlsread and export data using xlswrite. See the documentation
Syntax
xlswrite(filename,A,sheet,xlRange)
where A might be a cell array where the cells contain number of strings, sheet is the name of the Excel sheet and xlRange is the range in the Excel sheet (example: A1:B5).
Code example:
A = {'Column1', 'Column2', 'Column3'; 1, 2, 3};
xlswrite('example.xls', A, 'ExampleSheet', 'A1:B3');
Some hints:
If you know the number of rows and columsn of your data only at runtime but still want to give a range you must somehow assemble the range string yourself (rows are easy with sprintf, column names are more difficult (A, B, C, .., Z, AA, AB, ...))
If you do not have Excel on your computer, you will get csv files (see documentation)
Although each call to xlswrite returns quite fast, the system is still working. If another call to xlswrite comes too soon you might get unexpected (delay dependent) errors with no way to avoid them then to wait for sufficient time. I usually collect my data and then write everything to an excel file in one go.
very possible, you can do it in Matlab if you are familiar with it (although it is also quite easy to do in excel). To load in your file (no need to convert it, Matlab reads txt Files). you can do something like:
fileID = fopen('test2.txt'); %//Your file name
Input = textscan(fileID,'%s %f','Delimiter',':');
GoodRows = find(~isnan(Input{2} ));
column1 = Input{1}(GoodRows,:); //Column 1 is in the format of Cells (since you are storing Strings
column2 = Input{2}(GoodRows,:); //Column 2 is in the format of a Matrix, which will allow you to take numbers and do averages etc.
The cell and the matrix share indexes, so you can reformat your data eventually in to a Cell and export it in Matlab.
column1 =
'sleep'
'eat'
'live'
'travel'
'work'
'school'
'vt'
column2 =
1.0e+003 *
1.3604
0.0044
0.0164
0.0222
0.0220
0.0008
0.3869
==============EDIT===============
If you have multiple columns after the String, i.e.:
sleep,1.5,1.4,1.3
If you want to keep using textscan, you will need to specify how many columns there are. This is done by either:
Input = textscan(fileID,'%s %f %f %f %f','Delimiter',':'); //% add %f for each numeric column.
Or
Input = textscan(fileID,'%s repmat('%f',[1,N])]','Delimiter',':'); %// where N is the number of numeric columns you have.

Import text file in MATLAB

I have a tab delimited text file with suffix .RAW.
How can I load the data from the file into a matrix in MATLAB?
I have found readtable, but it doesn't support files ending with suffix .RAW.
Do I really have to use fread, fscanf, etc. to simply load a text file into a matrix?
You can use the dlmread() function. It will read data from an ASCII text file into a matrix and let you define the delimiter yourself. The delimiter for tabs is '\t'.
>> M = dlmread('Data.raw', '\t')
M =
1 2 3
4 5 6
7 8 9
Just for your information there is also the tdfread() function but I do not recommend using it except in very specific cases. dlmread() is a much better option.
.RAW is a generic file extention. You should know the format of your RAW file (especially if your file contains a combination of numbers, data structures etc). If it is a simple text file with a single 2D table, you can easily read it with fscanf, fread, fgetl, fgets, etc
Here is a simple example for a 2D table (matrix):
Let's assume that each row of your table is separated by a carriage return from its following rows. We can read each row by fgetl() and then extract numbers using str2num().
fid=fopen('YourTextFile.RAW');
Data=[];
i = 0;
while 1
i = i + 1;
tline = fgetl(fid);
if ~ischar(tline), break, end
Data(i,:) = str2num(tline);
end
fclose(fid);
disp(Data)
For more complex data structure, the code should be changed.
For a 2D table (a special case) the above simple code can be easily exchanged by dlmread() function.

load txt dataset into matlab in a matrix structure

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 '-'.

how to export data that contain both number and text columns to csv file in matlab?

I have a dataset containing one column of datestring, one column of model name (in char format), and a bunch of numerical data columns. How can i export them into csv file? The output file i want is that first it has two rows of headers and units and then comes to my dataset. Is this doable? Thanks.
My old code is like this that works well only for export numerical data. But now i have text column to add in, so i don't know how to modify it.
f=fopen('filename.csv','w');
fprintf(f,'hearders\n units\n');
fclose(f);
dlmwrite('filename.csv',dataset,'-append','precison','%.8f');
you can continue with fprintf, something like:
f=fopen('filename.csv','w');
fprintf(f,'hearders\n units\n');
formatspec = '%s ... %.8f %6.2f %12.8f %whatever ... \n';
fprintf(f,formatspec,dataset{:});
fclose(f);
you'll need to edit the format of the 3rd line according to the data types in each cell row...
play with fprintf(formatSpec,dataset{:}) option to print to screen to see that you got it right.