Tag Archives: matlab

Checking if a number is non-negative or not?

Many students ask me how do I do this or that in MATLAB.  This is a new addition to the “How do I do that in MATLAB“  series.
 
In this blog, I show you how to use the if-else-end statement to write a simple program of finding if a number is non-negative or not.
 
Here are the links for the program.
The mfile is here
The published version of the mfile is here
 

%% HOW DO I DO THAT IN MATLAB SERIES?
% In this series, I am answering questions that students have asked
% me about MATLAB.
%% TOPIC
% How do I check if a number is non-negative or negative
%% SUMMARY
% Language : Matlab 2010a;
% Authors : Autar Kaw and Sri Harsha Garapati;
% Mfile available at
% http://numericalmethods.eng.usf.edu/blog/if_else_end_statements_blog.m
% Last Revised : January 23, 2012;
% Abstract: This program shows you how to check if a number is negative or
% non-negative using if-else-end statement in MATLAB
clc
clear all
%% INTRODUCTION

disp(‘ABSTRACT’)
disp(‘   This program shows you how to check if a number is negative or’)
disp(‘   non-negative using if-else-end statement in MATLAB’)
disp(‘ ‘)
disp(‘AUTHOR’)
disp(‘   Autar Kaw and Sri Harsha Garapati of http://autarkaw.wordpress.com’)
disp(‘ ‘)
disp(‘MFILE SOURCE’)
disp(‘   http://numericalmethods.eng.usf.edu/blog/if_else_end_statements_blog.m’)
disp(‘ ‘)
disp(‘LAST REVISED’)
disp(‘   February 13, 2012′)
disp(‘ ‘)

%% INPUTS
 
% Enter the number to be tested
a=4;
%% DISPLAYING INPUTS
disp(‘  ‘)
disp(‘INPUTS’)

% Printing the input number
fprintf(‘The input number to be tested is %g\n’,a)
%% CODE AND DISPLAYING OUTPUT
disp(‘  ‘)
disp(‘OUTPUTS’)

% using the if-else-end statement to check
if (a>=0)
    disp(‘The number is nonnegative’)
else
    disp(‘The number is negative’)
end

_________________________________________________

This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://numericalmethods.eng.usf.edu, the textbook on Numerical Methods with Applications available from the lulu storefront, the textbook on Introduction to Programming Concepts Using MATLAB, and the YouTube video lectures available at http://numericalmethods.eng.usf.edu/videos.  Subscribe to the blog via a reader or email to stay updated with this blog. Let the information follow you.

Printer cuts off MATLAB code and text

When you print MATLAB code or the published form of the code, you may find the code or the comments getting cut off.  The solution to these problems is given at several places in MATLAB blogs and documentation.  In this blog, I have summarized what to do as the issues of code getting cut off falls into three categories
 

___________________________________________

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, the textbook on Introduction to Programming Concepts Using MATLAB, and the YouTube video lectures available at http://nm.mathforcollege.com/videos.  Subscribe to the blog via a reader or email to stay updated with this blog. Let the information follow you.

Differentiating a Discrete Function with Equidistant Points

Many students ask me how do I do this or that in MATLAB.  This is a new addition to the “How do I do that in MATLAB”  series.
 
In this blog, I show you how to find the first derivative of a discrete function y(x).  We are assuming that the x values are eqidistant and the data is sorted in ascending or descending order by the x values.  The latter requirement can be relaxed easily in programs such as MATLAB where one can use the sortrows command to put the data in the required order.
 
To keep the accuracy of all calculated first derivatives to be the same, we use the following formulas:
 
For the first data point, we use the forward divided difference formula
        f ‘(x) =(-f(x+2h) + 4 f(x+h) -3 f(x))/(2h)+order(h^2)
 
For the interior points, we use the central divided difference formula
       f ‘(x) =(f(x+h) -f(x-h))/(2h)+order(h^2)
 
For the last data point, we use the backward divided difference formula
       f ‘(x) =(f(x-2h) - 4 f(x-h) +3 f(x))/(2h)+order(h^2)
 
Here are the links for the program.
The mfile is here
The published version of the mfile is here

%% 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 find the first derivative of a discrete function y(x) if the
% x values are equidistant.
%% SUMMARY
% Language : Matlab 2010a;
% Authors : Autar Kaw and Sri Garapati;
% Mfile available at
% http://numericalmethods.eng.usf.edu/blog/discrete_diff_equidistant_blog.m
% Last Revised : January 17, 2012;
% Abstract: This program shows you how to differentiate discrete data if
% the x values are equally spaced
clc
clear all

%% INTRODUCTION

disp(‘ABSTRACT’)
disp(‘   This program shows you how to differentiate discrete data if’)
disp(‘   the x values are equally spaced ‘)

disp(‘ ‘)
disp(‘AUTHOR’)
disp(‘   Autar Kaw and Sri Garapati of http://autarkaw.wordpress.com’)
disp(‘ ‘)
disp(‘MFILE SOURCE’)
disp(‘   http://numericalmethods.eng.usf.edu/blog/discrete_diff_equidistant_blog.m’)
disp(‘ ‘)
disp(‘LAST REVISED’)
disp(‘   January 17, 2012′)
disp(‘ ‘)

%% INPUTS

% Inputs assuming
%    that three or more points are given
%    all x values are equidistant
%    x values are in ascending or descending order.
x=[2.3   3.4   4.5    5.6   6.7   7.8];
y=[4.6   7.9   13.0   12.3  3.2   1.9];
%% DISPLAYING INPUTS
disp(‘  ‘)
disp(‘INPUTS’)
% Creating a matrix to print input data as a table
data=[x;y]‘;
disp(‘   X Data     Y Data’)
% Printing the input data as a table
disp(data)

%% THE CODE

% n returns the number of data points
n=length(x);
% delta is the distance between consecutive x values
delta=x(2)-x(1);

% “dy” is an array which stores the value of the derivative at each x-value

% finding the derivative from the 2nd order accurate forward divided
% difference formula at the first data point
dy(1)=(-y(3)+4*y(2)-3*y(1))/(2*delta);

% finding the derivative from the 2nd order accurate central divided
% difference formula at the second to (n-1)th data point
for i=2:1:n-1
    dy(i)=(y(i+1)-y(i-1))/(2*delta);
end

% finding the derivative from the 2nd order accurate backward divided
% difference formula at the first data point
dy(n)=(y(n-2)-4*y(n-1)+3*y(n))/(2*delta);

% creating a matrix with input data and calculated derivative value at
% each data point for printing as a table
xdy=[x' y' dy'];

%% DISPLAYING OUTPUTS
disp(‘  ‘)
disp(‘OUTPUTS’)
disp(‘     XData   YData  Derivative’)
% printing the input data points and calculated derivative values(Outputs)
disp(xdy)
_________________________________________________

This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://numericalmethods.eng.usf.edu, the textbook on Numerical Methods with Applications available from the lulu storefront, the textbook on Introduction to Programming Concepts Using MATLAB, and the YouTube video lectures available at http://numericalmethods.eng.usf.edu/videos.  Subscribe to the blog via a reader or email to stay updated with this blog. Let the information follow you.

Reading an excel file in MATLAB

Recently I taught a volunteer class to professional engineers on MATLAB.  Two of the most requested items of interest were
1. How do I read an excel file?
2. How do I do curve fitting?

We address the first question here.  It is easy to read an excel file with the xlsread command but what do you with it once the file has been assigned.  So we took a simple example of an excel spreadsheet where the first column consists of a student number and the second column has the examination scores of the students.  You are asked to find the highest score.

The MATLAB program link is here.
The HTML version of the MATLAB program is here.
The Excel file used in the MATLAB program is here

It is better to download (right click and save target) the program as single quotes in the pasted version do not translate properly when pasted into a mfile editor of MATLAB or you can read the html version for clarity and sample output.

%% READING AN EXCEL SPREADSHEET IN MATLAB
% Language : Matlab 2008a
% Authors : Autar Kaw
% Last Revised : December 12, 2010
% Abstract: This program shows you how to read an excel file in MATLAB
% The example has student numbers in first column and their score in the
% second column
clc
clear all
disp(‘This program shows how to read an excel file in MATLAB’)
disp(‘Matlab 2008a’)
disp(‘Authors : Autar Kaw’)
disp(‘Last Revised : December 12, 2010′)
disp(‘http://numericalmethods.eng.usf.edu’)
disp(‘  ‘)

%% INPUTS
% We have two column data and it has headers in the first row.
% That is why we read the data from A2 to B32.
A=xlsread(‘c:\users\grades.xls’,’A2:B32′);
disp (‘The data read from the excel spreadsheet is’)
disp(A)
disp(‘  ‘)
%% SOLUTION
% Finding the number of rows and columns
sizem=size(A);
rows_A=sizem(1);
cols_A=sizem(2);
% Assigning the scores to a vector called score
for i=1:1:rows_A
    score(i)=A(i,2);
end
% Using the max command to find the maximum score
% HW: Write your own function “max”
maxscore=max(score);
% Finding which student got the highest score
for i=1:1:rows_A
   if score(i)==maxscore
       student_no=i;
       break;
   end
 % HW: What if more than one student scored the highest grade??
end
%% OUTPUT
disp(‘  ‘)
disp (‘OUTPUT’)
fprintf(‘Student Number# %g scored the maximum score of %g’,…
    student_no,maxscore)
disp(‘ ‘)

This post is brought to you by

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

Inverse error function using interpolation

In the previous post, http://autarkaw.wordpress.com/2010/09/01/using-int-and-solve-to-find-inverse-error-function-in-matlab/, we found the inverse error function by using the integral and solve MATLAB functions.  In this blog, we find the inverse error function by using interpolation.

The value of erf(x) is given at discrete data points of x, and we use spline interpolation to find the value of x at a given value of erf(x).  The given data points of (x,erf(x)) are (0,0), (0.1,0.1125), (0.25,0.2763), (0.75,0.7112), (1.0,0.8427), (1.5,0.9661), (2.0,0.9953), (5.0,1.000). 

It is better to download (right click and save target) the program as single quotes in the pasted version do not translate properly when pasted into a mfile editor of MATLAB or you can read the html version for clarity and sample output.

%% FINDING INVERSE ERROR FUNCTION
% In a previous blog at autarkaw.wordpress.com (Sep 1, 2010), we set up a
% nonlinear equation to find the inverse error function.
% In this blog, we will solve this equation
% by using interpolation.
% The problem is given at
% http://numericalmethods.eng.usf.edu/blog/inverseerror.pdf
% and we are solving Exercise 2 of the pdf file.

%% TOPIC
% Finding inverse error function

%% SUMMARY

% Language : Matlab 2008a;
% Authors : Autar Kaw;
% Mfile available at
% http://numericalmethods.eng.usf.edu/blog/inverse_erf_interp_matlab.m;
% Last Revised : October 4 2010
% Abstract: This program shows you how to find the inverse error function
% using interpolation
clc
clear all

%% INTRODUCTION

disp(‘ABSTRACT’)
disp(‘   This program shows you how to’)
disp(‘   find the inverse error function’)
disp(‘ ‘)
disp(‘AUTHOR’)
disp(‘   Autar K Kaw of http://autarkaw.wordpress.com’)
disp(‘ ‘)
disp(‘MFILE SOURCE’)
disp(‘ http://numericalmethods.eng.usf.edu/blog/inverse_erf_interp_matlab.m’)
disp(‘  ‘)
disp(‘PROBLEM STATEMENT’)
disp(‘ http://numericalmethods.eng.usf.edu/blog/inverseerror.pdf  Exercise 2′)
disp(‘ ‘)
disp(‘LAST REVISED’)
disp(‘   October 4, 2010′)
disp(‘ ‘)

%% INPUTS
% Value of error function
erfx=0.1125;
% Table of erf(x) vs x
xx=[0  0.1  0.25  0.75  1.0  1.5  2.0  5.0];
erfxx=[0  0.1125  0.2763  0.7112  0.8427  0.9661  0.9953  1.0000];

%% DISPLAYING INPUTS

disp(‘INPUTS’)
fprintf(‘ Inverse error function is to be found for= %g’,erfx)
disp(‘  ‘)
disp(‘ Given erf(x) vs x values’)
disp(‘_______________________’)
disp(‘    x          erfx  ‘)
disp(‘________________________’)
dataval=[xx;erfxx]‘;
disp(dataval)

%% CODE
if erfx>1.0 | erfx<0
    disp(‘Invalid value. erf(x) only takes values in [0,1] range’)
else
inverse_erf=interp1(erfxx,xx,erfx,’cubic’);
%% DISPLAYING OUTPUTS

disp(‘OUTPUTS’)
fprintf(‘ Value of inverse error func from this mfile is= %g’,inverse_erf)
fprintf(‘ \n Value of inverse error func from MATLAB is    = %g’,erfinv(erfx))
disp(‘  ‘)
end

__________________________________________________

This post is brought to you by

Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://numericalmethods.eng.usf.edu,
the textbook on Numerical Methods with Applications available from the lulu storefront,
the textbook on Introduction to Programming Concepts Using MATLAB, and
the YouTube video lectures available at http://numericalmethods.eng.usf.edu/videos

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

Using int and solve to find inverse error function in MATLAB

In the previous post, http://autarkaw.wordpress.com/2010/08/24/finding-the-inverse-error-function/, we set up the nonlinear equation to find the inverse of error function.  Using the int and solve MATLAB commands, we write our own program to find the inverse error function.

It is better to download (right click and save target) the program as single quotes in the pasted version do not translate properly when pasted into a mfile editor of MATLAB or you can read the html version for clarity and sample output.

%% FINDING INVERSE ERROR FUNCTION
% In a previous blog at autarkaw.wordpress.com (August 24, 2010),
% we set up a nonlinear equation to find the inverse error function.
% In this blog, we will solve this equation.
% The problem is given at
% http://numericalmethods.eng.usf.edu/blog/inverseerror.pdf
% and we are solving Exercise 1 of the pdf file.

%% TOPIC
% Finding inverse error function

%% SUMMARY

% Language : Matlab 2010a;
% Authors : Autar Kaw;
% Mfile available at
% http://numericalmethods.eng.usf.edu/blog/inverse_erf_matlab.m;
% Last Revised : August 27, 2010
% Abstract: This program shows you how to find the inverse error function
clc
clear all

%% INTRODUCTION

disp(‘ABSTRACT’)
disp(‘   This program shows you how to’)
disp(‘   find the inverse error function’)
disp(‘ ‘)
disp(‘AUTHOR’)
disp(‘   Autar K Kaw of http://autarkaw.wordpress.com’)
disp(‘ ‘)
disp(‘MFILE SOURCE’)
disp(‘   http://numericalmethods.eng.usf.edu/blog/inverse_erf_matlab.m’)
disp(‘  ‘)
disp(‘PROBLEM STATEMENT’)
disp(‘   http://numericalmethods.eng.usf.edu/blog/inverseerror.pdf’)
disp(‘        Exercise 1′)
disp(‘ ‘)
disp(‘LAST REVISED’)
disp(‘   August 27, 2010′)
disp(‘ ‘)

%% INPUTS
% Value of error function
erfx=0.5;

%% DISPLAYING INPUTS

disp(‘INPUTS’)
fprintf(‘ The value of error function= %g’,erfx)
disp(‘  ‘)
disp(‘  ‘)

%% CODE
syms t x
inverse_erf=solve(int(2/sqrt(pi)*exp(-t^2),t,0,x)-erfx);
inverse_erf=double(inverse_erf);
%% DISPLAYING OUTPUTS

disp(‘OUTPUTS’)
fprintf(‘ Value of inverse error function from mfile is= %g’,inverse_erf)
fprintf(‘\n Value of inverse error function using erfinv is= %g’,erfinv(erfx))
disp(‘  ‘)

___________________________________________________

This post is brought to you by

Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://numericalmethods.eng.usf.edu,
the textbook on Numerical Methods with Applications available from the lulu storefront,
the textbook on Introduction to Programming Concepts Using MATLAB, and
the YouTube video lectures available at http://numericalmethods.eng.usf.edu/videos

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

A short online quiz for the MATLAB conditional statements

Frequent testing has been proven to be effective in learning.  Here we have an online quiz on MATLAB conditional statements (only if-then-else), where some of the questions are calculated (meaning that the numbers in these questions change when you retake the quiz).  So give it a try.
http://numericalmethods.eng.usf.edu/EML3041/studymate/MATLABifelseend.htm

_____________________________________________________

This post is brought to you by Holistic Numerical Methods:  Transforming Numerical Methods for the STEM undergraduate at http://numericalmethods.eng.usf.edu, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://numericalmethods.eng.usf.edu/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.

A short online quiz on the for-end loops in MATLAB

Frequent testing has been proven to be effective in learning.  Here we have an online quiz on MATLAB loops (just the for-end loops in this quiz), where some of the questions are calculated (meaning that the numbers in these questions change when you retake the quiz).  So give it a try and soon we will be adding questions on other programming basics.
http://numericalmethods.eng.usf.edu/EML3041/studymate/MATLABforendloops.htm

____________________________________________________

This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://numericalmethods.eng.usf.edu, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://numericalmethods.eng.usf.edu/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.

A short online quiz on MATLAB basics

Frequent testing has been proven to be effective in learning.  Here we have an online quiz on MATLAB basics, where some of the questions are calculated (meaning that the numbers in these questions change when you retake the quiz).  So give it a try and soon we will be adding questions on programming basics.
http://numericalmethods.eng.usf.edu/EML3041/studymate/matlabbasics.htm

This post is brought to you by Holistic Numerical Methods: Numerical Methods for the STEM undergraduate at http://numericalmethods.eng.usf.edu, the textbook on Numerical Methods with Applications available from the lulu storefront, and the YouTube video lectures available at http://numericalmethods.eng.usf.edu/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 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.