How do I solve a nonlinear equation that needs to be setup – Updated to MATLAB 2018b

Guest co-blogger: Luis Serrano

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 a nonlinear equation that needs to be set up.

For example to find the depth ‘x’ to which a ball is floating in water is based on the following cubic equation
R= radius of ball
S= specific gravity of ball
So how do we set this up if S and R are input values?

The MATLAB program link is here.

The HTML version of the MATLAB program is here.


% Language : Matlab 2018b;
% Authors : Autar Kaw and Luis Serrano;
% Mfile available at
% Last Revised : January 22, 2020;
% Abstract: This program shows you how to solve a nonlinear equation
% that needs to set up as opposed that is just given to you.
clear all
disp(‘ This program shows you how to solve’)
disp(‘ a nonlinear equation that needs to be setup’)
disp(‘ ‘)
disp(‘ Autar Kaw and Luis Serrano’)
disp(‘ ‘)
disp(‘ ‘)
disp(‘ January 22, 2020’)
disp(‘ ‘)
% Solve the nonlinear equation where you need to set up the equation
% For example to find the depth ‘x’ to which a ball is floating in water is based on the following
% cubic equation 4*R^3*S=3*x^2*(R-x/3) R= radius of ball S= specific gravity of ball So how do we set this up if S and R are input values
func=[‘ The equation to be solved is 4*R^3*S=3*x^2*(R-x/3)’];
disp(‘ ‘)
% Define x as a symbol
syms x
% Setting up the equation
% Finding the solution of the nonlinear equation
for i=1:1:length(solnvalue)
fprintf(‘\nThe solution# %g is %g’,i,solnvalue(i))
disp(‘ ‘)


This post is brought to you by

Solution to ordinary differential equations posed as definite integral

This blog is an example to show the use of second fundamental theorem of calculus in posing a definite integral as an ordinary differential equation.  This plays a prominent role in showing how we can use numerical methods of ordinary differential equations to conduct numerical integration.

This post is brought to you by

Student participant costs in NSF budgets counts as direct cost

A common budget question gets asked about students who participate in the National Science Foundation Education and Human Resources NSF EHR grants and get paid for items such as focus group participation.  Does it count as direct cost?  Yes, it does.  Just read the language on page 53 (Page II-19) of Proposal & Award Policies & Procedures Guide (PAPPG) (NSF 19-1)

Human subject payments should be included on line G6 of the NSF budget under “Other Direct Costs,” and any applicable indirect costs should be calculated on the payments in accordance with the organization’s federally negotiated indirect cost rate.

Third Edition of Programming Textbook

We have just published the third edition of the textbook on programming with MATLAB.   It is available for purchase at

The book is intended for an introductory course in programming in STEM (science, technology, engineering, and mathematics) fields while using MATLAB as the programming language. MATLAB is a popular computational software package used in universities and industries alike.

This textbook differentiates itself from others in two specific ways.

      1. The textbook is suitable for the many engineering departments throughout the nation that no longer teach a 3-credit hour programming course. They weave programming and mathematical software packages such as MATLAB in courses such as Foundations of Engineering, Freshmen Design, Modeling of Systems, Engineering Analysis, Numerical Methods, etc. This book is highly suitable for such audiences. To achieve these goals and make the access far-reaching, we have been deliberate in keeping the lessons short in length so that instructors can easily choose the course content in a modular way.
      2. The textbook is a stand-alone resource for learning programming where the lectures complement the textbook rather than vice versa. This is because of the reason above where in-classroom time is truncated, and therefore students need to be more self-taught. For this reason, we have been meticulous when selecting and organizing the textbook content to include fundamental and application programming problems that prepare students well for other problems they will solve in academia and industry.

The book has nine modules which have been each broken down by lessons. There are 42 lessons in all and depending on the learning outcomes of the course, an instructor can choose to assign only necessary lessons. Modules 1-3 focus on MATLAB and programming basics like the MATLAB program interface, programming variables, different types of data, debugging, plotting, and applications to science and engineering problems. In Module 4, we show the use of MATLAB for basic mathematical procedures learned in the engineering courses including nonlinear equations, integration, differentiation, simultaneous linear equations, interpolation, regression, and ordinary differential equations. In Modules 5-8, the user is introduced to basic programming concepts of conditional statements, repetition (loops), and custom functions. In Module 9, program input/output is shown with writing to and reading from external files as well as navigating directories with MATLAB. Important appendices include a primer on matrix algebra, a collection of mini-projects, and a introduction to animating plots in MATLAB. Appendix A provides a primer on matrix algebra. Appendix B contains a set of mini-projects. Appendix C demonstrates how to make animated plots in MATLAB.

Each lesson contains screenshots of actual MATLAB programs that are used to help illustrate the concepts presented. More than 120 complete programs are shown throughout this book to demonstrate to the reader how to use programming concepts. The book is written in a USA-Today style question-answer format for a quick grasp of the concepts.

The purpose of this book is to provide the reader with a firm basic understanding of MATLAB syntax and fundamental programming concepts. Each lesson contains MATLAB programs that are used to help illustrate the concepts presented. By no means do the authors claim to present every MATLAB command, function, application, or programming concept in existence.

The program to find the determinant of matrix

Here is the MATLAB program to find the determinant of a nxn matrix by the cofactor method.  I had to develop a separate function for each size of the matrix.  I may be wrong about having to do that – is there a single function that can be written to find the determinant of any nxn matrix using the cofactor method?

The mfile can be downloaded here.   Try the program for a 10×10 matrix – it took about 6 seconds of CPU time on my PC.  A 12×12 matrix determinant would take about 13 minutes of CPU time.  I stopped at a 12×12 matrix.  You can either write a function or generate the function via a program for matrices of 13×13 order and higher.


Finding the determinant of a matrix using the cofactor method

and comparing the CPU time with MATLAB det function

clear all
format long

% n=Size of matrix
% Choosing a matrix of nxn size with random numbers

% Calculating cputime by cofactor method

% Calculating cputime by MATLAB det function

% Printing the times
fprintf('Size of matrix is %gx%g \n',n,n)
fprintf('Determinant by cofactor method = %g \n', detval)
fprintf('Determinant by Matlab function = %g \n', MatlabDet)
fprintf('Approximate CPU time taken by cofactor method = %g seconds\n',TimeCrammer)
fprintf('Approximate CPU time taken by MATLAB function = %e seconds\n',TimeMatlab)

Individual functions for determinant of a nxn matrix

function detvalue=det2(A)

function detvalue=det3(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det2(A(2:n,[1:j-1 j+1:n]));

function detvalue=det4(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det3(A(2:n,[1:j-1 j+1:n]));

function detvalue=det5(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det4(A(2:n,[1:j-1 j+1:n]));

function detvalue=det6(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det5(A(2:n,[1:j-1 j+1:n]));

function detvalue=det7(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det6(A(2:n,[1:j-1 j+1:n]));
function detvalue=det8(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det7(A(2:n,[1:j-1 j+1:n]));

function detvalue=det9(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det8(A(2:n,[1:j-1 j+1:n]));

function detvalue=det10(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det9(A(2:n,[1:j-1 j+1:n]));

function detvalue=det11(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det10(A(2:n,[1:j-1 j+1:n]));

function detvalue=det12(A)
for j=1:1:n
    detvalue=detvalue+(-1)^(j+1)*A(1,j)*det11(A(2:n,[1:j-1 j+1:n]));
Size of matrix is 6x6 
Determinant by cofactor method = -0.0431 
Determinant by Matlab function = -0.0431 
Approximate CPU time taken by cofactor method = 0.140625 seconds
Approximate CPU time taken by MATLAB function = 1.562500e-02 seconds

The above mfile can be downloaded here.

This post is brought to you by


Time it takes to find a determinant

To make the point of how inefficient it is to find the determinant of a matrix by the cofactor method, I wrote a program in MATLAB to demonstrate this.  A google search for a program written in any language to find the determinant by using the cofactor method was not available beyond a 4×4 matrix.  So, I wrote one that finds the determinant of matrices of up to 12×12 order.

I ran the program on an Intel(R) Core(TM) i5-8500 CPU @3.00GHz PC.  Here is a table of the CPU time it took in seconds to find the determinant of a matrix as a function of its order.
Order of matrix               CPU Time to Find
Determinant (s)
6×6                                           0.015625
7×7                                           0.046875
8×8                                           0.203125
9×9                                           0.828125
10×10                                        5.14063
11×11                                       52.6406
12×12                                   623.953

If one continues to do this for a 25×25 matrix, it is estimated that it would take 8.1821198 \times 10^{17} seconds which is more than 25 billion years, and we all know that the estimated age of the universe is less at about 13.77 billion years.

The trend of the approximate time it takes to find the determinant of the next order of the matrix, nxn is approximately n times the time it takes to find the determinant of a (n-1)x(n-1) matrix.  For example, it took a time of 52.6406 seconds for finding the determinant of a 11×11 matrix, while it would be estimated to take approximately 12×52.6406=631.7 seconds for finding the determinant of a 12×12 matrix.  This is close to the 623.953 seconds it actually took.

The above approximate time calculations are in concurrence with the note written by Professor A.J. Wise in 1969, where he showed that the number of arithmetic operations required to evaluate a nxn determinant by cofactor method is given by [n!e]-2, and hence n!e for large n and the time it takes to find the determinant of the next order of the matrix, nxn is approximately n times the time it takes to find the determinant of a (n-1)x(n-1) matrix

Since the arithmetic operation required here are just addition, multiplication and subtraction, the computation time could be crudely estimated as 4Tn!e for large n, where T is the clock cycle time and we assume that an addition or a multiplication or a subtraction each use 4 clock cycle times.  Does it match?

For a 3.00 GHz machine, T={1}/({3 \times 10^9}) seconds to give an approximate time for a 12×12 matrix determinant calculation to be 4 \times {1}/{(3 \times 10^9)} \times 12! e = 1.736  seconds.  It is not even of similar order.  Many items go into calculating CPU time for a numerical algorithm, but to do a comparative analysis, these calculations are quite helpful.

This post is brought to you by

Stripping the tags from an HTML file

Recently, I was moving my webpages created through FrontPage 2003 (please stop snickering -it was a great tool for sites with flat web files) to WordPress.

This required clearing of formatting of the HTML file and one could use for doing so – “ gives you a quick, easy and satisfying way to transform your ugly formatted and/or HTMLified text into a clean and pretty text for you to enjoy.”  However, most of us want to preserve the URL links, titles and the paragraph tags.

This VBA program that can be used within Excel takes an input text file, reads it as a single string, removes all tags except the URLs, paragraphs and titles, and writes to a new text file.

The VBA program below has the input file at “C:\Users\Tranq\Documents\abc\inputhtml.txt”, and outputs to “C:\Users\Tranq\Documents\abc\outputhtml.txt” and you can change these locations in the TextFile_PullData and TextFile_Create functions, respectively.  You can modify the program to read several files in a directory and make it even more efficient.

How to Use: Just open an Excel file. Press Alt+F11, and open a new module. Cut and paste what is given below, or download the text file.  Go to a cell in the excel file and enter =CleanTags(A1) in cell B1.  Make sure you have the input file at C:\Users\Tranq\Documents\abc\inputhtml.txt”.   The location can be modified.


Function CleanTags(HTML As String) As String
‘PURPOSE: Clean HTML tags except the paragraph, weblinks and title
‘ You can comment out if you want these to supress these as well
‘ The instructions are given at the spots.
‘ SOURCE: Unknown and
Dim result As String, StripIt As Boolean, c As String, i As Long
HTML = TextFile_PullData()

‘StripIt is used to figure out to include or exclude in output
StripIt = False

‘Looking at each character in the HTML file
For i = 1 To Len(HTML)
‘c is each character
c = Mid(HTML, i, 1)
‘Some conditions to take care for end of input file
If i <= Len(HTML) – 1 Then
‘d is last two characters of file to capture <a and <p
‘Just in case
d = Mid(HTML, i, 2)
d = “”
End If
If i <= Len(HTML) – 3 Then
‘e is last four characters of file to capture </a> and </p>
e = Mid(HTML, i, 4)
e = “”
End If

‘Checking for < character that begins an HTML tag
If c = “<” Then StripIt = True

‘Comment this if you want to strip paragraphs
If d = “<p” Then StripIt = False
If e = “</p>” Then StripIt = False

‘Comment this if you want to strip URL tags and title tags as well.
If d = “<a” Then StripIt = False
If e = “</a>” Then StripIt = False

‘Adds to output or skips it
If StripIt = False Then result = result & c
‘Taking care of closing tag to change the StripIt Boolean
If c = “>” Then StripIt = False
Next i
CleanTags = result

‘Putting the output in a new file
abc = TextFile_Create(result)
‘Run the program by entering =CleanTags(A1) in a blank excel file
‘where you have this module. Puts Done in cell if it runs correctly
CleanTags = “Done”
‘This lets you know the work is done. Comment if you like.
‘MsgBox (“Done”)
End Function

Function TextFile_PullData()
‘PURPOSE: Send All Data From Text File To A String Variable

Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String

‘File Path of Text File
FilePath = “C:\Users\Tranq\Documents\abc\inputhtml.txt”

‘Determine the next file number available for use by the FileOpen function
TextFile = FreeFile

‘Open the text file
Open FilePath For Input As TextFile

‘Store file content inside a variable
FileContent = Input(LOF(TextFile), TextFile)

‘Report Out Text File Contents
‘MsgBox FileContent

‘Close Text File
Close TextFile
TextFile_PullData = FileContent

End Function

Function TextFile_Create(HTML As String)
‘PURPOSE: Create A New Text File

Dim TextFile As Integer
Dim FilePath As String

‘What is the file path and name for the new text file?
FilePath = “C:\Users\Tranq\Documents\abc\outputhtml.txt”

‘Determine the next file number available for use by the FileOpen function
TextFile = FreeFile

‘Open the text file
Open FilePath For Output As TextFile

‘Write some lines of text
Print #TextFile, HTML

‘Save & Close Text File
Close TextFile

End Function

This post is brought to you by