Read text file in MATLAB

If you would like to analyze data generated from other sources, you will most likely need to import the data from a text, csv, or xls file.  Here we’ll provide different methods you can use to import this data.

First, you will need to select the file of interest, with the filename stored in the variable ‘file’:

% Select file
[filename, pathname] = uigetfile ('*.*', 'Pick a file');
file = [pathname, filename];

In our example, we will be importing a tab-delimited textfile generated by Sensor Data. The data file we are playing with is test_gyroscope_t3.txt.  As you can see, this file has 13 header lines (two of which are blank lines) and 110 lines of data (consisting of time, x axis, y axis, z axis).

Now that your file has been selected, you have several options through which to import.  First let’s look at textread. While this function will soon be decremented, it still serves a nice purpose. We can specify a delimiter, and then parse out the header and data using cellfun.

% Using textread, which will be removed in later MATLAB releases
% Read in file
allData = textread(file, '%s', 'delimiter', '\n');
% Make allData cells empty if numerical 
numericalArray = cellfun(@(s) sscanf(s,'%f').' ,allData, 'un', 0);
% Get Header
header = allData(cellfun('isempty',numericalArray));
% Get Data
data = vertcat(numericalArray{:});

With this piece of code, you will have a 11×4 cell array for the header and a 110×4 double for the numerical data. What if we were to use textscan as recommended by MATLAB rather than textread? Well now the code is a little bit longer, and you need to specify before hand how many columns of data you want as well as how many header lines are in the file. This method might be useful if you want to manually select only certain columns and even start at a later row, but does require knowledge of your data file. Here we’ll initialize the values for the headerlength and columnlength to 13 and 4, respectively. You’ll also notice our usage of the command repmat, which comes in very handy here and elsewhere.

% If you know the header and column length using textscan
headerLength = 13;
numColumns = 4;
fid = fopen(file);
% this is error message for reading the file
if fid == -1 
    error('File could not be opened, check name or path.')
end
% Get header
header = cell(headerLength, 1);
for i = 1:headerLength
    header{i} = fgetl(fid);
end
fclose(fid);
fid = fopen(file);
% Read in numerical data
data = textscan(fid, repmat('%f',1,numColumns), 'headerlines', headerLength);
data = cell2mat(data);
fclose(fid);

Again, our data has been stored into 11×4 cell array for the header and a 110×4 double for the numerical data. So this is great, now you can read in data… but wait, MATLAB also has a great function, which we just found that allows you to do all this with just a single line of code!

% importdata
A = importdata(file);

Importdata! This command will output the data to a struct, with a field for the data (110×4 double), textdata (11×4 cell) and colheaders (1×4 cell). The colheaders is simply the title for each column of data, in our case ‘Time’, ‘X’, ‘Y’, ‘Z’. You can even specify the delimiter for the file as the second argument to importdata, though the default character is interpreted from the file.

Regardless of which method you choose, you should now have access to your all-important data within MATLAB, so you can now begin analysis.

If you have found any other methods for importing data into MATLAB, please let us know.

Android Apps

Sorry for the long break, but the MatlabGeeks members have been working on several interesting side projects including the development of a few Android Apps. The first one we are proud to release is named SensorData. This app allows for the recording, analyzing and saving (locally or to Google Drive) of sensors found on your smartphone or tablet. Sensors include accelerometers, gyroscopes, magnetometers, pressure, light, temperature, proximity and humidity. You can install and test it for free in the Google Play store.

Analysis options available to date in SensorData include re-sampling and filtering, both of which we will discuss in upcoming posts here, if you would like to perform similar analyses in MATLAB.

In our next post, we will discuss how to read in data into MATLAB from a tab-delimited file, as is created by SensorData to further analyze any of your sensor data.

Check convexity of polygon

As we demonstrated in our previous post, we can generate polygons by tracing a circle around a given center and placing vertices at randomly spaced angles and radii.

MATLAB irregular polygon

While on visual inspection it should be clear whether some polygons are convex or concave, we want to find a way to check for this property mathematically. We will do so by checking the direction that each internal angle takes around the polygon, as by definition, convex polygons will have all internal angles of less than 180 degrees (additional rules include the fact that all diagonals are contained within the polygon and a line drawn through a convex polygon in any direction will intersect at exactly two points).

Continue reading

Creating 2-D polygons in MATLAB

The basic premise of computational geometry is to calculate distances, areas, intersections and other geometrical calculations on basic objects such as points, lines and polygons. To begin this series on computational geometry in MATLAB, we’ll discuss the creation of random polygons in MATLAB.

Continue reading

Caustic Art in MATLAB. New posts coming soon.

The Matlabgeeks team has been busy working on several interesting projects the last couple of years and have unfortunately been unable to post many updates. Here’s a quick look at one of these projects:

In late 2014, the Matlab Geeks created software that produces caustic art for Harry Sanderson, a fellow at Near Now, which is an art production company specializing in technological art in Nottingham, UK. Caustic art is the design of a surface that projects a desired image onto a screen from a light source. Here is an example of the final image generated using our scripts.

Caustics in MATLAB

Using CGAL, we created an optimal transport map (OTM) to find the most efficient mapping from a source image to a target image. Then, using MATLAB, we interpolated points on a triangular mesh of incident light rays to a target mesh using natural neighbor interpolation with the OTM. Next, we computed surface normal vectors that directed the light rays to the interpolated positions on the screen. Finally, we created a surface with these normal vectors via optimization using the Ceres framework by Google and saved the results as an STL mesh.

We have produced several pieces of caustic art for Harry Sanderson, which are being shown in art shows throughout Europe.

Much of the code was written in MATLAB and as the project used computational geometry, optimization and other interesting techniques extensively, we’ll try and tailor some upcoming posts on these topics.

Check back soon for new updates or feel free to contact us if you have more questions about this project or any projects you would like the Matlab Geeks team to work on.