How do I read data from a textfile in MATLAB?

Many students ask me how do I do this or that in MATLAB.  So I thought why not have a small series of my next few blogs do that.  In this blog, I show you how to read data from an external data file.  We will use the simplest command to read from a text file, that is, the fgets command.

The MATLAB program link is here and the text file is here.

So let us look at an example.  Let’s suppose someone asks you to find the dot product of two vectors: A=[7  11  13  23] and B=[3   5    17   29].   The program for that simply is

A=[7  11   13  23]
B=[3  5   17   29]
n=length(A)
dot_product=0
for i=1:1:n
dot_product=dot_product+A(i)*B(i)
end

What if now the data for the vectors are given in an external text file?  How does MATLAB read the data and assign it properly to A and B.

The first thing is to make the text file.  Let’s save this data in the file called /blog/vectordata.txt.  The text file is here.
7    11   13    23
3    5     17   29

Now how is this data read from the data file.
First you tell MATLAB what the name of the file is
filen=’W:/blog/vectordata.txt’

Now the file needs to be opened by using the fopen command.  This also assigns an integer to the file called the filehandler.  This integer is automatically assigned by MATLAB and is a unique integer for any open file.  The ‘r’ stands for the file being opened for reading.  The other choices are ‘w’ for writing and ‘a’ for appending.
fh=fopen(filen,’r’)

Now we need to get the data from the file which is identified through the file identifier variable.  The fgets command does this and every time fgets is used, it reads the next line.

A_vector=fgets(fh)

However, this reads the whole line of data as a single string.  How do we now get it to be a vector A with the 4 entries.  We do this by using the sscanf command that parses the string variable into the format used by sscanf.  The format used here is %f which is a floating point format.  The other formats for reading numbers include %e for scientific format and %d for integers.
A=sscanf(A_vector,’%f’)

Similarly, one can now read the B vector via fgets command and parse it using the sscanf command.

The MATLAB program link is here and the text file is here.

__________________________________________

This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://nm.mathforcollege.com, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://nm.mathforcollege.com/videos and http://www.youtube.com/numericalmethodsguy

Subscribe to the blog via a reader or email to stay updated with this blog. Let the information follow you.

MATLAB code for bubble sort

In the previous blog, we spelled out the bubble sort algorithm for putting an array of numbers in an ascending order.   In this post, I am posting the matlab program. It is better to download the program as single quotes in the pasted version do not translate properly when pasted into a mfile editor of MATLAB or see the html version for clarity and sample output.

%% PUTTING AN VECTOR OF NUMBERS IN AN ASCENDING ORDER?
% Language : Matlab 2007a
% Authors : Autar Kaw
% Last Revised : November 8, 2009
% Abstract: This program shows you how to put a vector
% of numbers in an ascending order using the bubble sort method
clc
clear all
disp(‘This program shows the bubble sort method’)
disp(‘to put a vector of numbers in an ‘)
disp(‘ascending order’)
disp(‘Matlab 2007a’)
disp(‘Authors : Autar Kaw’)
disp(‘Last Revised : November 8, 2009’)
disp(‘http://nm.mathforcollege.com’)
disp(‘  ‘)
%% INPUTS
% The vector of numbers
disp (‘INPUTS’)
disp(‘Input the vector of numbers’)
A=[18  7  6  15  4  13];
disp(A)
%% SOLUTION
% Number of entries, n
n=length(A);
% making (n-1) passes
for j=1:1:n-1
    % comparing each number with the next and swapping
    for i=1:1:n-1
    if A(i)>A(i+1);
        % temp is a variable where the numbers are kept
        % temporarily for the switch
        temp=A(i);
        A(i)=A(i+1);
        A(i+1)=temp;
    end
    end
end

%% OUTPUT
disp(‘  ‘)
disp (‘OUTPUT’)
disp (‘The ascending matrix is’)
disp(A)

_______________________________________________________

This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://nm.mathforcollege.com, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://nm.mathforcollege.com/videos and http://www.youtube.com/numericalmethodsguy

Subscribe to the blog via a reader or email to stay updated with this blog. Let the information follow you.

Bubble sorting

Last week, I was teaching how to randomly pick lotto numbers using MATLAB.  The problem was that some of the numbers that were getting picked were identical.  We solved this by using comparisons until the current number picked is different from the previously selected numbers.  We blogged on this a few months ago.  But there is still an aesthetic problem of how the numbers are presented.  The numbers are not in an ascending or descending order.  This is a good time to show how to do this using the simplest (if not the most efficient) procedure called the bubble sort.

Let’s suppose someone asks you to put [8 7  9  5   4] in an ascending order.  

Starting from the first number, you compare the number with the next number, and see if it is greater.  If it is, you swap the numbers.  You continue to do this with the second number, third number and so on until the second last number.  What this does is bubble the largest number to the end. 

[8  7  9  5  4 ] -> [7  8  9  5  4]  (as 8>7) -> [7  8  9  5  4]  (as 8 is not > 9)-> [7  8  5   9   4]  (as 9 is >5) -> [7  8   5  4  9]  (as 9>4).  See how the largest number is at the end. 

Now repeat this.  [7  8   5  4  9]  -> [7  8  5  4  9] (as 7 is not >8] -> [7   5  8  4  9] (as 8>5) -> [7  5  4  8 9]  (as 8>4) ->  [7  5  4  8  9 ] (as 8 is not >9)

Now repeat this.  [ 7  5  4  8  9] -> [5  7  4  8  9] -> [ 5  4  7  8  9] -> [ 5  4  7  8  9]  -> [  5  4  7  8  9]

Now repeat this.  [5  4  7  8  9] -> [ 4  5  7  8  9] -> [ 4  5  7  8 9] -> [ 4  5  7  8   9]  -> [  4 5  7  8  9]

It looks like we are done.  If n is the number of the numbers in the array, it takes (n-1) swaps within each of the (n-1) repetitions.  So we do not have to guess how many swaps it takes or how many repetitions it takes. 

To make the bubble sort efficient, we can do the following: 1) Since with each repetition the largest number bubbles up, we may need to do less swaps.  For the first repetition, we will do (n-1) swaps, for the next repetition, we do the first (n-2) swaps, and so on.  2) We can also keep track of number of swaps taking place in a repetition.  If no swaps take place in a repetition, no more repetitions are needed.

_______________________________________________________

This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://nm.mathforcollege.com, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://nm.mathforcollege.com/videos and http://www.youtube.com/numericalmethodsguy

Subscribe to the blog via a reader or email to stay updated with this blog. Let the information follow you.