Iimport data in Matlab from Excel with string label - matlab

I am new in Matlab and I want to import an Excel file in matrix format. My columns are all numerical except the last column, which is a string and it's my labels. When I import my data set Matlab says that label column is unimportable and replaces it to zero! How can I do about it?

Please use following code:
[num, txt, raw] = xlsread(excelpath, sheetname, A00:C20)
Excep path, sheetname and A00:C20 are arbitrary. You can find table containing all items in specified cells in raw variable. num contains numeric values and txt contains string values.

Related

loading txt files into matlab structure

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.

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.

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.

Matlab: reading from a .csv file

I am trying to import some data from a .csv file, I have search for solutions but no one seems to solve my problem. My .csv is just one column of numbers, but when I try to read it with csvread('myfile.csv') it says that it cannot convert from string. When I double click on the .csv file in matlab I can see that every number from the .csv has this aspect:
"996.47"
So every number is between double commas, and whatever I do I can not get just the number between them. I am trying also opening the file and with textscan but I find no way. Thank you very much in advance.
You can try this workaround:
V = dlmread('myfile.csv','"');
v = V(:,2)
According to your description you have one column of values formatted like "996.47". The first line creates a matrix where columns are delimited by '"' - you get three columns where the middle one is filled with your values. The second line extracts the middle column.
what about using
importdata('yourfile.csv')
It should work if you are only interested in data.
If you want a more generic solution that doesn't need to deal with indexing, you can use MATLAB's built-in function importdata.
x = importdata('yourfile.csv'); % reads in the file as text surrounded by double quotes
x = cellfun(#str2num,strrep(v,'"','')); % removes the double quotes and changes text to numbers