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.

How do I numerically solve an ODE in MATLAB?

The other day a student came to ask me for help in solving a second order ordinary differential equation using the ode45 routine of MATLAB.  To use ode45, one needs to be familiar with how the inputs are required by MATLAB.  The understanding of these inputs is important to use ode45 successfully in problems that are more complex than solving a second order ODE.

The ordinary differential equation was
2y”+3y’+5y=7 exp(-x), y(0)=11, dy/dx(0)=13
This has to put in the state variable form by reducing it by using
y’=z
That gives
y’=z with the corresponding initial conditions as y(0)=11
Then
2y”+3y’+5y=7 exp(-x)
reduces to
2z’ + 3z+5y=7exp(-x)
z’ =(7exp(-x)-3z-5y)/2 with the corresponding initial conditions as z(0)=13

So as needed by MATLAB, call y as y(1) and z as y(2)
dy(1)=y(2), y(1) at x=0 is 11
dy(2)=(7exp(-x)-3y(2)-5y(1))/2, y(2) at x=0 is 13

These equations are now put in a MATLAB function we call odestate.m
dy=zeros(2,1);
dy(1)=y(2);
dy(2)=(7*exp(-x)-3*y(2)-5*y(1))/2;

To solve the ODE, the
The inputs are
1) the function odestate
2) The outputs are required between x=0 and x=17,
hence entered as [0 17]
3) The initial conditions are y(0)=11 and dy/dx(0)=13,
hence entered as [11  13]

The outputs are
1) X= array of x values between 0 and 17
2) Y= matrix of 2 columns;
first column is the y(x)
second column is dy/dx(x)
The MATLAB code then is
[X,Y]=ode45(@odestate,[0  17],[11 13]);

Click the links for the MATLAB mfiles for the function odestate.m and the ODE solver odetest.m

_________________________________________________________________________________

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

The break statement in MATLAB

The break statement in MATLAB is used to break out of a loop – a for or while statement, that is, it terminates the execution of the loop.  Let’s suppose someone wants to find the value of k^2-50 for all integers in [-10,10] domain.  The mfile for that is given below.

% For integers k=-10,-9,….,9,10,
% the function k^2-50 will take positive as
% well as negative values. 
%For example, for k=-9, k^2-50=31; for k=1,
% k^2-50=-49; for k=8, k^2-50=14.
% The loop below will calculate values of k^2-50 for all values of requested k.
for k=-10:1:10
    val=k^2-50;
end

___________________________________________________________

Let’s suppose now you are asked to calculate value of k^2-50 for all integers in [-10,10] domain but only until k^2-50 becomes negative.

% The loop below will calculate values of k^2-50
% for all values of the requested k
% until it turns negative
for k=-10:1:10
    if (k^2-50<0)
        break;
    end
    val=k^2-50;
    fprintf(‘\n k=%g  val=%g’,k,val)
end

____________________________________________________________

Can you do what you did above using the while statement.  Yes, the MATLAB code is given below.

% Equivalent in while
% The loop below will calculate values of k^2-50
% for all values of the requested k until it turns negative
k=-10;
while (k<=10) & (k^2-50>0)
    val=k^2-50;
    fprintf(‘\n k=%g  val=%g’,k,val)
    k=k+1;
end

_______________________________________________________

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.

Are software bugs categorised as “that is the way it is”

For a few years, I thought that the shame was only on financial companies to have dragged us through the economic mess.  Whether the mess is now affecting our software industry or if it is the new attitude of software companies, remains to be seen.  Three different pieces of software that I use for teaching and research in a large university in the Southeast USA, have serious flaws which the companies are taking semi-seriously or as a matter of “life goes on”. 

One of them is a finite element program.  Running the input file in a new version gives segmentation fault and the company acknowledges that it is a problem.  To stop wasting our time and not having to use the features of the new version, we requested that they give us the license for the older version until they fix the problem.  It took more than a couple of weeks of reminders (what else our IT group had to do) to get the older version.  Then they did not give us the parallel version of the program and we are still waiting for that.

Second is a program that makes interactive quizzes for mathematics courses.  This software gives the result as incorrect even for correct answers if the correct answer is a negative number.  This makes the program useless for what I want to do.  Their take on it – we cannot update it right away.  Hey, this is making your program useless to me – wake up.  Even after pointing out to them where the potential bug can be (without looking at the program) and which it was, they still did not help me.  I even told them how to fix it.  Only after much wrangling and waiting for two months, they are promising the update in October.  I hope they test it with the test file I sent them; otherwise, I am at square one until December.

Third is a computational package.  They updated their symbolic package with a different package and my students now get two different sets of answers using two different versions.  The answers are correct but one version gives only one solution while the other version gives multiple solutions.  I need the multiple solutions so that students can pick the most appropriate answer.  What I heard from them was -“That is the way it is”.  Only after much wrangling and calling their reply a “cop out” did they acknowledge it as a problem and gave me an alternate solution.  See I am teaching the first programming course to engineers and I cannot teach them to work around the bugs of the software itself.  Their confidence is shaken and I have to be extra vigilant now – is it the software or is it the students.  Nothing can be taken at face value anymore.  And these students are the future industrial users of the software.

Bugs are part of life for any software but when you are making millions of dollars of profit, you have an obligation to work on the bugs that make your software unusable.  What I am finding out is the software companies attitude is that they are safe in treating their customer any way they like – they may not be “too big to fail” but they are “too entrenched to fail”.  Good day!

 _________________________________________________________________________________________________________________________

This post is brought to you by

You can watch the numerical methods videos on a mobile device

We are in the process of putting appropriate content of the numerical methods website so that it can be viewed on mobile devices.  So far we have checked that it works on the Itouch, Iphone, Blackberry, LG New.

The mobile website is at http://nm.mathforcollege.com/mobile.  Let me know what you think about this development.

_________________________________________________________________________________________________________________________

This post is brought to you by

How do I solve simultaneous linear equations given in equation form?

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 solve simultaneous linear equations given in equation form.

  • The MATLAB program link is here.
  • The HTML version of the MATLAB program is here.
  • DO NOT COPY AND PASTE THE PROGRAM BELOW BECAUSE THE SINGLE QUOTES DO NOT TRANSLATE TO THE CORRECT SINGLE QUOTES IN MATLAB EDITOR.  DOWNLOAD THE MATLAB PROGRAM INSTEAD

%% HOW DO I DO THAT IN MATLAB SERIES?
% In this series, I am answering questions that students have asked
% me about MATLAB.  Most of the questions relate to a mathematical
% procedure.

%% TOPIC
% How do I solve a set of simultaneous linear equations
% given in equation form?

%% SUMMARY

% Language : Matlab 2008a;
% Authors : Autar Kaw;
% Mfile available at
% http://nm.mathforcollege.com/blog/sle_equations.m;
% Last Revised : August 22, 2009;
% Abstract: This program shows you how to solve a set of
%     simultaneous linear equations given in equation form?
%           .
clc
clear all
clf

%% INTRODUCTION

disp(‘ABSTRACT’)
disp(‘   This program shows you how to solve a’)
disp(‘   set of simultaneous linear equations given in equation form’)
disp(‘ ‘)
disp(‘AUTHOR’)
disp(‘   Autar K Kaw of http://autarkaw.wordpress.com’)
disp(‘ ‘)
disp(‘MFILE SOURCE’)
disp(‘   http://nm.mathforcollege.com/blog/sle_equations.m’)
disp(‘ ‘)
disp(‘LAST REVISED’)
disp(‘   August 22, 2009’)
disp(‘ ‘)

%% INPUTS
% Enter the equations
eqn1=’12*a+23*b+39*c=29′;
eqn2=’13*a+17*b+19*c=37′;
eqn3=’21*a+23*b+29*c=59’;
%% DISPLAYING INPUTS
disp(‘  ‘)
disp(‘INPUTS’)
disp(‘________________________’)
disp(‘Equations’)
disp(‘________________________’)
disp(eqn1)
disp(eqn2)
disp(eqn3)

%% THE CODE
% The solution
X=solve(eqn1,eqn2,eqn3);
% Assigning the output
a=double(X.a);
b=double(X.b);
c=double(X.c);
%% DISPLAYING OUTPUTS
disp(‘  ‘)
disp(‘OUTPUTS’)
disp(‘________________________’)
disp(‘Solution Vector’)
disp(‘________________________’)
fprintf(‘\nValue of a= %g’,a)
fprintf(‘\nValue of b= %g’,b)
fprintf(‘\nValue of c= %g’,c)
disp(‘  ‘)
disp(‘________________________’)

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.

How do I solve a set of simultaneous linear equations given in matrix form?

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 solve simultaneous linear equations given in matrix form.

  • The MATLAB program link is here.
  • The HTML version of the MATLAB program is here.
  • DO NOT COPY AND PASTE THE PROGRAM BELOW BECAUSE THE SINGLE QUOTES DO NOT TRANSLATE TO THE CORRECT SINGLE QUOTES IN MATLAB EDITOR.  DOWNLOAD THE MATLAB PROGRAM INSTEAD

%% HOW DO I DO THAT IN MATLAB SERIES?
% In this series, I am answering questions that students have asked
% me about MATLAB.  Most of the questions relate to a mathematical
% procedure.

%% TOPIC
% How do I solve a set of simultaneous linear equations?

%% SUMMARY

% Language : Matlab 2008a;
% Authors : Autar Kaw;
% Mfile available at
% http://nm.mathforcollege.com/blog/sle.m;
% Last Revised : August 12, 2009;
% Abstract: This program shows you how to solve a set of simultaneous linear
% equations?
%           .
clc
clear all
clf

%% INTRODUCTION

disp(‘ABSTRACT’)
disp(‘   This program shows you how to solve a’)
disp(‘   set of simultaneous linear equations’)
disp(‘ ‘)
disp(‘AUTHOR’)
disp(‘   Autar K Kaw of http://autarkaw.wordpress.com’)
disp(‘ ‘)
disp(‘MFILE SOURCE’)
disp(‘   http://nm.mathforcollege.com/blog/sle.m’)
disp(‘ ‘)
disp(‘LAST REVISED’)
disp(‘   August 12, 2009’)
disp(‘ ‘)

%% INPUTS
% Enter the coefficient matrix of the equation [A][X]=[C]
A=[12  23  39; 13  17  19; 21  23  29];
% Enter the right hand side vector
C=[29;   37;  59];
%% DISPLAYING INPUTS
disp(‘  ‘)
disp(‘INPUTS’)
disp(‘________________________’)
disp(‘Coefficient Matrix’)
disp(‘________________________’)
dataval=[A];
disp(dataval)
disp(‘________________________’)
disp(‘Right hand side vector’)
disp(‘________________________’)
dataval=[C];
disp(dataval)
disp(‘________________________’)

%% THE CODE
% The solution
X=A\C;

%% DISPLAYING OUTPUTS
disp(‘  ‘)
disp(‘OUTPUTS’)
disp(‘________________________’)
disp(‘Solution Vector’)
disp(‘________________________’)
dataval=[X];
disp(dataval)
disp(‘________________________’)

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

How do I do polynomial regression 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 do polynomial regression.

  • The MATLAB program link is here.
  • The HTML version of the MATLAB program is here.
  • DO NOT COPY AND PASTE THE PROGRAM BELOW BECAUSE THE SINGLE QUOTES MAY NOT TRANSLATE TO THE CORRECT SINGLE QUOTES IN MATLAB EDITOR OR IT MAY NOT PASTE HARD RETURNS.  DOWNLOAD THE MATLAB PROGRAM DIRECTLY INSTEAD
%% HOW DO I DO THAT IN MATLAB SERIES?
% In this series, I am answering questions that students have asked
% me about MATLAB.  Most of the questions relate to a mathematical
% procedure.

%% TOPIC
% How do I do polynomial regression?

%% SUMMARY

% Language : Matlab 2008a;
% Authors : Autar Kaw;
% Mfile available at
% http://nm.mathforcollege.com/blog/regression_polynomial.m;
% Last Revised : August 3, 2009;
% Abstract: This program shows you how to do polynomial regression?
%           .
clc
clear all
clf

%% INTRODUCTION

disp('ABSTRACT')
disp('   This program shows you how to do polynomial regression')
disp(' ')
disp('AUTHOR')
disp('   Autar K Kaw of http://autarkaw.wordpress.com')
disp(' ')
disp('MFILE SOURCE')
disp('   http://nm.mathforcollege.com/blog/regression_polynomial.m')
disp(' ')
disp('LAST REVISED')
disp('   August 3, 2009')
disp(' ')

%% INPUTS
% y vs x data to regress
% x data
x=[-340 -280 -200 -120 -40 40 80];
% ydata
y=[2.45  3.33 4.30 5.09 5.72 6.24 6.47];
% Where do you want to find the values at
xin=[-300 -100 20  125];
%% DISPLAYING INPUTS
disp('  ')
disp('INPUTS')
disp('________________________')
disp('     x         y  ')
disp('________________________')
dataval=[x;y]';
disp(dataval)
disp('________________________')
disp('   ')
disp('The x values where you want to predict the y values')
dataval=[xin]';
disp(dataval)
disp('________________________')
disp('  ')

%% THE CODE
% Using polyfit to conduct polynomial regression to a polynomial of order 1
pp=polyfit(x,y,1);
% Predicting values at given x values
yin=polyval(pp,xin);
% This is only for plotting the regression model
% Find the number of data points
n=length(x);
xplot=x(1):(x(n)-x(1))/10000:x(n);
yplot=polyval(pp,xplot);
%% DISPLAYING OUTPUTS
disp('  ')
disp('OUTPUTS')
disp('________________________')
disp('   xasked   ypredicted  ')
disp('________________________')
dataval=[xin;yin]';
disp(dataval)
disp('________________________')

xlabel('x');
ylabel('y');
title('y vs x ');
plot(x,y,'o','MarkerSize',5,'MarkerEdgeColor','b','MarkerFaceColor','b')
hold on
plot(xin,yin,'o','MarkerSize',5,'MarkerEdgeColor','r','MarkerFaceColor','r')
hold on
plot(xplot,yplot,'LineWidth',2)
legend('Points given','Points found','Regression Curve','Location','East')
hold off
disp('  ')

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.

How do I display the data of an array in MATLAB?

When I give a MATLAB project, I ask my students that the command window can only show output from disp and frprintf statements.  All other statement outputs need to be suppressed.  This is done to get an aesthetically pleasing report.  So what is a student supposed to do when you may have y vs x data and one needs to show it as an output, especially when the number of y vs x data points can change.

For example, we may have

x=[1  4  5   7 ]

y=[12  23  34  100]

How do I display this with just disp and fprintf statements?

  • The MATLAB program link is here.
  • The Hhttp://nm.mathforcollege.com/blog/displaying_arrays.mTML version of the MATLAB program is here.
  • DO NOT COPY AND PASTE THE PROGRAM BELOW BECAUSE THE SINGLE QUOTES DO NOT TRANSLATE TO THE CORRECT SINGLE QUOTES IN MATLAB EDITOR.  DOWNLOAD THE MATLAB PROGRAM INSTEAD

%% HOW DO I DO THAT IN MATLAB SERIES?
% In this series, I am answering questions that students have asked
% me about MATLAB.  Most of the questions relate to a mathematical
% procedure.

%% TOPIC
% How do I display arrays in MATLAB?

%% SUMMARY

% Language : Matlab 2008a;
% Authors : Autar Kaw and Jeremy Baker;
% Mfile available at
% http://nm.mathforcollege.com/blog/displaying_arrays.m;
% Last Revised : July 8, 2009;
% Abstract: This program shows you how to display arrays in MATLAB
clc
clear all

%% INTRODUCTION

disp(‘ABSTRACT’)
disp(‘   This program shows you how to display arrays’)
disp(‘ ‘)
disp(‘AUTHOR’)
disp(‘   Autar K Kaw of http://autarkaw.wordpress.com and Jeremy Baker’)
disp(‘ ‘)
disp(‘MFILE SOURCE’)
disp(‘   http://nm.mathforcollege.com/blog/displaying_arrays.m’)
disp(‘ ‘)
disp(‘LAST REVISED’)
disp(‘   July 8, 2009’)
disp(‘ ‘)

%% INPUTS
% Input x and y arrays, for example as y vs x data
x=[1  4  5   7 ];
y=[12  23  34  100];
%% DISPLAYING INPUTS METHOD 1
disp(‘INPUTS – Method 1’)
n=length(x);
fprintf(‘The number of data points is %g \n’,n)
disp(‘________________________’)
disp(‘  x-values    y values  ‘)
disp(‘________________________’)
for i=1:1:n
fprintf(‘      %g          %g \n’,x(i), y(i)’)
end
disp(‘________________________’)

%% DISPLAYING INPUTS METHOD 2
% Suggested by guest blogger Jeremy Baker
disp(‘  ‘)
disp(‘INPUTS – Method 2’)
n=length(x);
fprintf(‘The number of data points is %g \n’,n)
disp(‘________________________’)
disp(‘     x    y  ‘)
disp(‘________________________’)
dataval=[x;y]’;
disp(dataval)
disp(‘________________________’)

_____________________________________________

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.

Poems on Numerical Methods

In Summer 2009, I gave a HW assignment of writing a poem to my mostly right-brained students.  The results were great; I think they think they are poets and they know it.  The poems were all compiled and can be viewed at http://nm.mathforcollege.com/EML3041/homework/poems2009summer.html.

So happy reading and let me know what you think.  I selected 14 poems out of the 60 or so submitted and am polling the class to select the best three.  The top three poem writers will get prizes including a dollar to get the 89c Chicken Burritto at Taco Bell for “thinking outside the bun” or the biggie fries at Wendy’s for thinking “square rather than round”.

_____________________________________________

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.