4 Starting with Programming

To err is human. To really foul things up requires a computer.
Bill Vaughan – Journalist
\text{\newthought{If our interest was only computing}} it would not be necessary to ever turn on a computer. We could study every aspect of computing without ever writing a program. But what fun is that?

Code:

The common term for writing computer programs is coding, as in she is coding the new interface. The program itself is often referred to as the code.

The truth is that we learn computing in order to understand the the theory that we need to write effective computer programs. Our goal is the program – or code as it is often called. It is through the program that we are able to get the computer to perform tasks for us.
MatLab is an interpreted programming language.  As with many interpreted programming languages MatLab can be run interactively or through a written script.

Interactive Programming

Interactively
Running a program interactively consists of entering a single statement directly into the command line.

Because an interpreted programming language is executed one line at a time, many interpreted programs can be run interactively; that is by entering a single statement on the command line. MatLab is one of those programming languages.

  1. >>  3 + 5
  2. ans =
  3.      8
  4. >>  9 - 4
  5. ans =
  6.      5
  7. >>  2 .* 5
  8. ans =
  9.      10
  10. >>  36 ./ 9
  11. ans =
  12.      4
  13. >>  3 .^ 4
  14. ans =
  15.      81
  16. >>

Interactive arithmetic

In each case in figure Interactive arithmetic the operations are entered on the commend line as a simple arithmetic operation. When you press enter on the keyboard the single line is executed – in this case performing the arithmetic operation,

Arithmetic Operations

MatLab has operators – the symbol that indicates that the program should do something – to perform the four standard mathematic operations and a fifth for exponentiation – raising a value to a power.
Operator Action Example
+ Addition a+b
Subtraction a-b
.* Multiplication a.*b
./ Division a./b
.\land Exponentiation a.\land b
Table: Arithmetic Operators
Each operator does in a program exactly what it would do on pencil paper.
Dot Operator
While we are all familiar with these operators there is an unusual component in the product, quotient, and power operators – a dot or period in front of the operator. It is often called the dot operator because of this.
Warning
 The difference between using the dot and omitting it is an important consideration when the two values are vectors or matrices. With the dot the operations are performed element-wise while without it they are performed as matrix operations. The differences between element-wise and matrix operations will be presented in chapter Vectors. Until then it is enough that the dot be included in the product, quotient, and power operations.

 

The dot operator indicates that the operation is to be performed element-wise instead of being done using matrix operations. At this point we are only performing operations on scalars and while the dot operator is the correct syntax you would still get the correct result if you had not included it. But since the operations are intended as element-wise it is important to include the dot.
Order of Operations
 An issue can arise when the order in which the arithmetic operations is ambiguous. Is 3 + 5 .* 4 = 32 or is it 23? It becomes clear when parentheses are added; (3 + 5) .* 4 = 32 while 3 + (5 .* 4) = 23.
But what if the parentheses are omitted? With or without the parentheses arithmetic operations are performed in accordance with the standard algebraic order of operations; PEMDAS.
Order Description Operator
1 Parentheses (\cdot\cdot\cdot)
2 Exponentiation .\land
3 Multiplication .*
4 Division ./
5 Addition +
6 Subtraction -
Table: Algebraic Order of Operations
Note
The order of operations is easy to remember with any of a number of mnemonics. As a single word, Pem-das or as a quick phrase such as Please excuse my dear Aunt Sally or a variation provided by a student Please excuse my dumb ass sister.

The order of operations show that all operations that are enclosed with parentheses take precedence. As an example

(1)   \begin{eqnarray*} (3 + 5) \dotProd 7 &=& 8.*7\nonumber\\ &=& 56\nonumber \end{eqnarray*}

while

(2)   \begin{eqnarray*} 3 + (5 \dotProd 7) &=& 3 + 35\nonumber\\ &=& 38\nonumber \end{eqnarray*}

After this it is exponentiation or raising to a power.

(3)   \begin{eqnarray*} 2 \dotPow 3+4 &=& 8 + 4\nonumber\\ &=& 12\nonumber \end{eqnarray*}

but

(4)   \begin{eqnarray*} 2 \dotPow (3+4) &=& 2\dotPow 7\nonumber\\ &=& 128\nonumber \end{eqnarray*}

Variables

Variable
A variable is a block of allocated memory to which data can written and read. It is most commonly used in a program as temporary data storage.

Variables

Notice that in figure Interactive arithmetic each time that you enter a value or operations on the command line the system responds with the result but also an ans =. This would be same for any operation or even a single variable.
  1. >>  7
  2. ans =
  3.      7
  4. >>
Storing results in the variable ans

In fact you could enter a number on the command line, as in figure Storing results in the variable ans, and the system would respond with the same ans =. This is an example of assigning a value to a variable.

A variable is a block of memory that has been allocated to store data. Each memory block has an address that can be used to identify the location of the memory.
Identifier
In programming an identifier is a name that is given to some item so that item can be accessed in the program. A common identifier is the variable identifier – a name given to a variable in the program.
While each block of memory has an address assigned to it, keeping track of the constantly changing memory addresses would be a herculean task. Instead, the variables have variable identifiers – common names that can be used instead of the variable address.
In the sample code in figure Storing results in the variable ans, ans is a variable identifier – although from here on the variable identifier will be called simply the variable. Because ans directs the program to a location in memory, data can be written to that location or read from it by using the variable ans.
Comment
The terms variable and variable identifier indicate the memory location and the name that the programmer gave the variable. This formality is never enforced. Any time that the term variable is used it is implied that you mean the variable identifier. Further, if it is the memory address that is needed the term variable reference or variable address would be used.

Changes to the variable are made using the = called the assignment operator. The action is called an assignment or assigning data to the variable.

When using the assignment operator any operations must be performed on the right hand side of the operator. The program will perform those operations first and the assign the results to the single variable – if any – on the left hand side of the operator. If there is no assignment operator then the results are stored in the variable ans by default. If ans already exists the data will be overwritten.
  1. >>  ans = 5 + 4
  2. ans =
  3.      9
  4. >>
Storing results in the variable ans
The assignment operator should not be confused with a mathematical equals sign. It does not indicate equality. In fact in a program the assignment operations would rarely make sense in a mathematical form. An example is having the variable on both sides of the assignment operator.
Assignment Operator
The = is called the assignment operator. It directs data to – or from – a variable.
A common action is to have the variable on both sides of the assignment operator. This is known as an update. Because the program will always perform all of the actions on the right hand side before any assignments, the current value of the variable will be used in the operations. Once completed the results are then copied into, and thus replacing the old values in, the memory location.
Warning
 Although the assignment operator appears like a mathematical equals sign it is important to understand that it is not an indication of equality.
  1. >> ans = 9
  2.  ans =
  3.       9
  4.  >> ans = ans ./ 2
  5.  ans =
  6.       4.5
  7.  >>

Updating the variable ans

Creating Variables

If you do not create a variable in your command, MatLab will create one for you. In Matlab this default variable is always ans (a diminutive of answer). It is limiting to have only a single variable so you can create others as needed.
  1. >>  x = 16
  2. x =
  3. 16
  4. >> y = 3.* x - 5
  5. y =
  6. 43
  7. >>
Creating additional variables

There are no limits on the number of variables that you may create in a program, and only a few limitations on what you can name them. The rules are quite simple.

  • A variable identifier must begin with a letter of the Latin alphabet
  • After the first letter the variable may contain any alpha-numeric character or the underscore symbol, but no other symbols or spaces
  • Variables are case sensitive thus a variable with an upper case letter and the same identifier but with lower case letters are two different variables. There are no restrictions on where an upper case or lower case letter may be used
  • A variable may not be a keyword. You cannot use names such as function, or end, or while, or any of the additional reserved words
Variable Nomenclature
  • A variable identifier must begin with a letter of alphabet
  • All other characters may be any alpha-numeric character or the underscore symbol
  • Variables are case sensitive
  • No keywords
Keywords are words that are reserved for specific programming purposes. Some common examples are the words functionendifwhile, and for but there are far too many to list here.
  1. >>  iskeyword end
  2. ans =
  3.    logical
  4. 1
  5. >>  iskeyword time2go
  6. ans =
  7.    logical
  8. 0
  9. >>
Checking variable identifiers with iskeyword
No worries, MatLab provides a means of determining if a possible variable name is a keyword. It is the command iskeyword.
Logical
A logical is a variable that is used to denote that a test is either true – the value 1, or false – the value 0
In the sample code in figure Checking variable identifiers with iskeyword the word logical that appears indicates that the result will be one of the values 1 or 0.  This is known as a logical – an output that indicates if the test was true or false. The logical value 1 indicates true, while the logical value 0 indicates false.
There is another function, isvarname, figure Checking variable identifiers with isvarname,  that can be used to check if your variable name is legal. Much like iskeyword this function returns the logical true – or 1 – the name that you used is legal, and a logical false – or 0 – if it is not.
  1. >>  isvarname 3xy
  2. ans =
  3.    logical
  4. 0
  5. >>  isvarname xy3
  6. ans =
  7.    logical
  8. 1
  9. >>

Checking variable identifiers with isvarname

Data Types

Data Type
Each value in a program has a data type. It is an attribute of the value that is used to determine how the program is to use the data. The three primary data types are integers, floating point values, and characters.
 MatLab is what is known as a weakly typed language. This has nothing to do with keyboards but instead is a description of how variables deal with data of different data types.
The data type is an attribute of the data that is to be stored. There are three primary data types; integers, floating point values, and characters. Since MatLab is a weakly typed language it allows a variable to store data of each of these, and in addition, strings.

If the data is value then MatLab will determine if it is an integer based upon its context. That is if the value contains a fractional part then it will assume that it is a floating point value. If it does not then it will assume that the value is an integer.

A issue might occur with characters or strings. If you want to store a character or string in a variable by simply writing the character or string the program will assume that it is another variable. If the character is a symbol then the program would assume that it is an operation. As a result of this all characters, strings, and symbols are placed within a pair of single quotes.
  1. >>  name = 'Joe Bfstk'
  2. name =
  3. 'Joe Bfstk'
  4. >>

Storing a string in a variable

The interactive approach is nice if all you need are some simple results; calculating a few values, plotting the graph of a function to print, or finding a single solution to a small system of linear equations.
But for almost anything else running your program from the command line is horribly inefficient. You need to enter each line of a program individually, and if you want to make changes and then run it again you have to start over. Imagine the frustration of entering fifty or a hundred lines only to make a numerical mistake on line one hundred and one.
To counter this you need a means of running a program that is consistent and repeatable. You want to create a script.

Scripted Programming

The interactive approach to programming works, but lacks efficiency and repeatability. The chances are good that once you write a program you would want to run it multiple times – changing a parameter or two and calculating new results. The would require a program in which all of the executable statements can be run multiple times with little or no changes to the program.

Script:

A script is the program that is written in an interpreted programming language. It consists of a set of commands that will be executed in the sequence in which they are presented.

Since MatLab is an interpreted language this requires writing a script.
Recall that a script is the set of executable commands that will be followed in a specific order. An interpreted language requires an interpreter that for each line of code in the script
  • parses the line of code
  • checks the line for syntax errors
  • if an error is found – exits the program
  • else
    • translates the line to machine code
    • executes the statement
    • goes to the next line
This process is similar to an actor reading a play. The actor reads a line or performs an action. Until that action is completed – and completed successfully – the rest of the play waits. The directions to the actors is called a script thus the program that is written for an interpreted programming language is also called a script.

Writing a script

In its simplest form, a script is simply a text file in which the lines of code are written in the order in which you want them to be run. We are going to take a more formal approach to programming that will be better explained in chapter Functions but for now just do it.

Story:

Why do we always start with Hello World!? You could start by doing any programming task but printing an output is always first.
There is a puzzler that goes “If you want to teach a dog to swim, what do you do first?” Ask this to a hundred people and you will get a hundred answers – but rarely are any of them the correct one. The answer is “you teach them to get out of the water.”
The first skill is not to get into the water, it is to get out. If the poor dog cannot get out of the water then all of the swimming lessons will be for naught.
In the same way the first programming skill that you need to learn is how to get the information out of the program. Without that you would never know if the program was performing the correct actions or even any actions – thus Hello World!
The file consists a line with the name of the program – which will call driver, the statements that we want the program to run, and the keyword end to indicate that end – obviously – of the program.
In MatLab this file is often called a dot m file because of the .m suffix that you will give the file. It must have the same name as the program name – in this case driver – so the file will be named driver.m
Tradition has it that the first program that you write will print the statement Hello World! on the screen. So let’s do it
Once you have written the script, you run it by typing the name of the file onto the command line. It is a standard convention to include a set of parentheses, but for now that is optional. The program would run the same with or without them.
  1. function driver()
  2.      s = Hello World!
  3. end
  1. >> driver()
  2. s = Hello World!
  3. >>

The Hello World Program

This first program was simple but it demonstrates the ideas of a script. The single line of code is parsed – read into memory one character at a time while checking for syntax errors, and then executed.
In this program, a string of text was assigned to a variable and because the line does not end with a semi-colon the value stored in the variable is printed to the screen. Echoing is not the method we want to use for printing but for now it accomplishes the task.

The form of a program

As we begin to write programs – what we will call scripts – it is helpful to develop an efficient approach. Too often programmers will start with a blank screen and starting
writing inputs, then calculations, then outputs. After all, this is the form the program will take when it is done.

Rendered by QuickLaTeX.com

Standard form of a computer program

But it is not how it should be written. While it is the final form of the program, it is inefficient. Instead, a more productive approach is to work in reverse. Create the outputs with all of the formatting to have the results in a form that can be either printed or can be used directly. To do this you will need variables with values. This is what we do first. Do not be concerned with the calculations – they will come later.

%Flow chart showing data being turned into information

Rendered by QuickLaTeX.com

Process of efficiently writing a program

Variables in a program can be classified as input variables or output variables. The values in the input variable will later be entered by the user of the program, while the output variables will be the result of calculations. Regardless of the type, at this point they should just be assigned values. This is often called hard coding.

Once the variables in the program have been created and assigned values – both those that will be the inputs and those that will be the outputs to the program – start writing the outputs.

 

Creating Outputs

 

A paradox of programming is that we need to be able to print before we learn to enter data, or perform calculations. But why?

While the program we wrote could have performed any task, how would we know it was correct – or even if it ran at all – if we do not have an output? The output is where the user gets to see the result of the program. So while printing the results seems like it should be the last task, it is actually the first.In the Hello World! program you had the script print by calling a function fprintf.  There are actually several different ways to print results in your program.  Each of them have their own purpose and should be used as such.

Echoing

Echoing:
Echoing is when the results of an operation is printed to the screen as soon as the action is complete. It is activated by not ending a line with a semi-colon (;).

The first means of printing is called echoing. Echoing is when the results of an operation, be it an input, assignment, or a calculation are printed to the screen immediately after it is done.

Echoing is a type of flag. In programming a flag is a state in the program that indicates  that some condition has been met or that some operation should be done. It is called a flag because it only has two possible choices; On or Off – similar to a flag being raised or lowered.

Flag:
A flag is a variable or indicator of a state in the program. It can only have two values – On or Off, 1 or 0, true or false, and so on.

To use echoing you omit the semi-colon from the end of a line. Examples of this are shown in the sample code in the figures earlier.

When the semi-colon is at the end of the line the statement is run exactly like it was before, but nothing is shown on the screen.

Echoing should not be used as the standard print method. Instead it is a debugging tool. When you run your program you can turn echoing on (by removing the ; ) to check if intermediate results are correct.

Warning:

Echoing is a useful technique for checking intermediate results or when using the command line for quick calculations. But it should not be used as the main method for printing results in your programs.

But if you use it throughout you program it becomes a nuisance. Values – in which you are not normally interested – continue to clutter the output. They become a distraction. Instead, once you are assured that the intermediate calculations are correct it is important to turn echoing back off (by ending the line with the ;).

Since echoing should only be used for debugging, standard practice is to end every line of code with the semi-colon; even those that would have printed without the semi-colon.

Display

disp
The disp function will print strings of text or the values stored in a variable.

 

There is another print function that while it has a use for vectors and matrices is not recommended for normal printing. This is the disp function

  1. disp(variable);

Syntax of the disp function

Unlike echoing in which the variable identifier and the value are printed the disp function will print the variable’s data and nothing else. This function can be used print both text – or strings – as well as numerical data. 

  1. function driver()
  2.      x = 7 ./ 6;
  3.      disp('Printing using disp');
  4.      disp(x);
  5. end
  1. >> driver()
  2. Printing using disp
  3.      1.667
  4. >>

Printing using disp

The default for disp is to print the string or value exactly as presented with no other formatting or alignments. It does not print the variable identifier.

The default is to print values using with four digits after the radix point. If the number is small enough it prints it directly while for larger – or smaller values disp prints using scientific notation.

It may occur that you need to know more than four digits in the fractional part. If so you will need to adjust the precision of the output (the number of decimal places).

There are several system commands, in the table, that can set the precision that are printed using disp. Since these are system commands once they called they fix the formatting for echoing and for any other system printing until they are changed or the MatLab session is closed.

Format Command Print
Format bank Two digits after the radix point
format compact Four digits after the radix point
format long Fifteen digits after the radix point
format shortEng Engineering format – scientific notation limited to multiples of three – with four digits after the radix point
format longEng Engineering format – scientific notation limited to multiples of three – with fifteen digits after the radix point
format shortG Either fixed decimal format or scientific notation whichever is shorter each value with four digits after the radix point
format longG Either fixed decimal format or scientific notation whichever is shorter each value with fifteen digits after the radix point
format hex Gexadecimal (base 16)
format rat Ratio of small integers
format + + for positive values, – for negative values, and blank for zero
format Reset to the system default

Table: Setting precision for the disp function

Warning:

The format command is a system command. This means that it does not apply only to disp or to that run of the program. It applies to both echoing and disp and will remain until it is either changed or the MatLab session ends.

  1. function driver()
  2.      disp('Using default format');
  3.      x = 53287 ./ 3;
  4.      disp(x);
  5.      format shortEng
  6.      disp('and now with engineering notation');
  7.      disp(x);
  8. end
  1. >> driver()
  2. Using default format
  3.     1.7762e+04
  4. and now with engineering notation
  5.      17.7623e+003
  6. >>

Changing the precision using the format command

Printing is a primary task in most programs. And while you can print using echoing, it is intended as a debugging tool and should not be used in the final program.

Further disp, while providing a basic means of printing text and data does not include many of the formatting tools that are necessary for controlling how the output is printed.

So while we will continue to use echoing – as a temporary means for printing – disp has been superseded by a printing function that offers more ability to control almost every aspect of printing. This is the function fprintf.

Why is the function fprintf and not just print?

The first f stands for file while the second is for formatted. You use this same function for writing results to files thus the first f. The second part is also important. Formatting means the we control the width of the printed value (the number of spaces that is uses) and also the precision (the number of decimal places).

fprintf

A function in the old C programming language provided a method of printing both strings and data simultaneously. In addition the function enabled a wide range of formatting. This function has been adapted for MatLab as fprintf.

  1. fprintf('formatting string', ouput parameter list);

Syntax of the fprintf function

The formatting string can be as simple as a string of text to be printed. It can – and usually does – include indications as to where to print data. In the sample code, in the figure The Hello World Program, since all that you were going to print is Hello World! the formatting string contained just that. The single quotes at the beginning and end are used to indicate the start and end of the formatting string.

We want more than being able to print strings of text. We want to print our results. This will require formatting.

Formatting the Output

How would you print variables? If you could type them in as text then you just put them inside of the quotes but that is a bit paradoxical. To print them you need to know the values when you write the code. But if you already know the values then there is probably no reason to write a program.

Newline:

There are a pair of characters right before the closing quote. The \n is called an escape sequence. It tells the program to go to a new line at the end of the printing.

You want to be able to print the values after they have been calculated. This is going to require formatting.

We can add several different types of variables to printed. The most common are strings of text, and numerical values.

The location in which you will print text is indicated with a %s while numerical values are positioned using one of several formatting characters. The most common are %f%d, %e, and  %g.

  1. function driver()
  2.    name = 'Joe Bfstk';
  3.    month = 'August';
  4.    day = 23;
  5.    year = 2025;
  6.    fprintf('Hello %s!\n', name);
  7.    fprintf('It is %d %s %d\n', day, month, year);
  8. end
  1. >> driver()
  2. Hello Joe Bfstk!
  3. It is 23 August 2025
  4. >>

Printing your name and date in which name is a string of text and the date consists of two integer values and a string

In the sample code in the figure Printing your name and date in which name is a string of text and the date consists of two integer values and a string the location of the formatting characters indicate where the data will be printed. Which variable is printed is determined by the order that they are presented – first in the list gets printed first, second is second, and so on.

Format Character Action
%f Print a floating point value
%d Print an integer value
%e Print a floating point value in scientific notation
%g Print a floating point value in either regular notation or scientific notation whichever is shorter
%o Print an integer in octal (base 8)
%x Print an integer in hexadecimal (base 16)
%c Print a single character
%s Print a string of text

Table: Formatting Characters

Controlling the width and precision

Precision:

Precision is distance of an observation from the actual value. In the case of coding, precision is determined by the number of decimal places that are retained or printed.

In the standard form the formatting characters provide the location for printing the data value. When they print, whatever is printed abuts the text that comes both immediately before an after it. Additionally, if what is being printed is a a floating point value – a number with a fractional part (or decimal places) – then the default is to print the value with four decimal places.

You may want additional control over the printing. Perhaps you want to align several rows of values o the radix point (the decimal point in base ten). fprintf also provides the ability to control the amount of space – the width – that is reserved for the printed data, and in the case of printing floating point values, the precision.

Each of the formatting characters allow you to set the width that this reserved for printing. This is done by adding a non-negative value between the % and the letter. For example, to print an integer right justified with a minimum of seven spaces reserved you would use %7d. This applies for any of the non-floating point formatting characters.

The syntax for doing this with an integer variable is shown in the figure Syntax for reserving ‘w’ spaces for an integer. Of course the w would be replaced with an integer value.

Radix Point:

The radix point the period that is used to separate the integer part of a floating point number from its fractional part. In base ten it is commonly called the decimal point

  1. fprintf('%wd', integer variable);

Syntax for reserving w spaces for an integer

This same addition will work with all of the non-floating point data types. For example, %32s will reserve 32 spaces for a string of text.

  1. function driver()
  2.    name = 'Joe Bfstk';
  3.    month = 'August';
  4.    day = 23;
  5.    year = 2025;
  6.    fprintf('Hello %s!\n', name);
  7.    fprintf('It is %d %s %d\n', day, month, year);
  8. end
  1. >> driver()
  2. Hello Joe Bfstk!
  3. It is 23 August 2025
  4. >>

Printing your name and date in which name is a string of text and the date consists of two integer values and a string

A common method to attempt to align text is to add spaces within the string in the formatting of the fprintf function. It may work but is awkward. It also tends to fail when the size of the values being printed change from run to run.
Alternatively, the width parameter when printing strings of text can be a useful technique for aligning columns in a table. An example of this is in the figure Printing your name and date in which name is a string of text and the date consists of two integer values and a string
  1. function driver()
  2.    fprintf('\n');
  3.    fprintf('%15s%20s%20s\n', 'Trial', 'Voltage', 'Power');
  4.    fprintf('\n');
  5. end
  1. >> driver()
  2.         Trial              Voltage              Power
  3. >>

Printing a table header using string variables

  1. function driver()
  2.    fprintf('\n');
  3.    fprintf('%15s%20s%20s\n', 'Trial', 'Voltage', 'Power');
  4.    fprintf('\n');
  5. end

 

  1. >> driver()
  2.      Trial          Voltage          Power
  3. >>
Printing a table header using string literals
In this example, the three strings on the right of the comma are actually variables, but are hard coded into the fprintf function parameters as literals. When the program is run, the literal is printed in the space that is reserved for it with the %s. You could have also assigned the text to a variable and used the variable in the fprintf statement as was done in the figure Printing a table header using string literals .
Note
When printing a floating point value, the printed value is rounded using the standard rounding rules.

 

Most of the variables printed are not integers or text, but are floating point values. Recall this means the value has a fractional part; what we usually think of as a decimals or values to the right of the radix (the decimal point).
To format a floating point value you enter the width and the precision separated by a period.
  1. fprintf('%w.pf', floating_variable);
Syntax for reserving a total of w spaces and p decimal places for for a floating point value
In this method, the value in w is the total number of spaces reserved for the value. This includes the decimals.  p is the precision – or the number of decimal places.
  1. function driver()
  2. % DRIVER driver() is the main or driver function
  3. %Assign data to all variables
  4.      trial1 = 42;
  5.      volt1 = 109.74652;
  6.      power1 = 203.93287;
  7.      trial2 = 43;
  8.      volt2 = 73.29876;
  9.      power2 = 12.30842;
  10.      %Print the values as a formatted table
  11.      fprintf('\n');
  12.      fprintf('%15s%20s%20s\n', 'Trial', 'Voltage', 'Power');
  13.      fprintf('%15d%20.2f%20.2f\n', trials, volt, power);
  14.      fprintf('\n');
  15. end
  1. >> driver()
  2.      Trial          Voltage          Power
  3.       42             109.75          203.93
  4.       43              73.30           12.31
  5. >>

Printing strings, decimals, and floating point values

By adjusting the width, it is possible to get the values in each printed line to align on the decimal points.

Escape Sequences

There is an additional item of text in the fprintf formatting string. It is the \n, what we earlier described as the command to force a new line when printing. This is known as an escape sequence.

 

Format
Character Action
\n Force a new line
\r Carriage return
\t Tab over the print to the next stop
\b Move back a space
Print a single quote – ‘
“” Print a double quote – “
%% Print the percentage symbol – %
EscapeSequences
Escape sequences address the issue of printing a character that if you had entered the actual keystroke would have been interpreted differently. For example, the enter or return key on the keyboard moves the cursor to the next line. When you press it while writing a program, the program would move to the next line. This would not put the new line in the print statement, but would actually result in a syntax error since the formatting string would have stopped before the closing quote.
To resolve this, programs use escape sequences for the different non-enterable characters. The list of the common escape sequences are in the table EscapeSequences.
Most escape sequences are self-explanatory. The \n is the newline code and causes the printing to move the next line. Since the fprintf function does only what is within the formatting string, if the newline was omitted the printing would stop at the last character. The next print statement would then start on the same line. Ending the formatting string with \n forces the cursor to move to the start of the next line – in effect preparing it for the next print statement.
There is a second, similar, escape sequence. The carriage return \r. The carriage return is from the old manual typewriter days. The mechanism upon which the paper rested and where the keys struck the paper was called the carriage. When a typist neared the end of a line,
they would push the carriage back to the beginning to start the next line – thus carriage return. Originally the carriage return did not move to a new line but reset to the beginning of the same line. To move to a new line required two commands. Since it is rare in printing to not move to a new line the carriage return escape sequence included the newline. Having two,  \n and \r, are redundant but usually still included. The new line escape sequence, \n, is more commonly used.
Another useful escape sequence is the tab \t. Again, a hold over from the old manual typewriters. A typist would set a series of tab stops across the length of the page. By pressing the tab key on the typewriter the platen would move so the next key strike would be at the next tab stop. On the computer the tab stops are set a fixed amount across the screen or the paper. Each time the fprintf encounters a \t moves to the next tab stop.
Warning
The tab escape sequence does not always move the cursor over the same number of spaces. It moves the cursor to the next tab stop. This means it could space over anywhere from one to whatever the tab stop spacing. Because of this when used alone, it may not be a reliable means of aligning data. But can be effective when combined with the width and precision modifiers.

 

The \t works the same way. When the computer encounters a \t in the formatting string it moves the cursor to the next tab stop. While the tap escape sequence is often used to format data so values align on the decimal point, if the width of the numbers vary widely the tab stop issue often disrupts the alignments. Setting the width is usually a better approach.
While there are many other escape sequences but there are three that are especially useful. Although they may not be specifically escape sequences – because they do not start with the backslash – the single and double quotes, and the percent sign are still needed when printing but are used for other purposes in the fprintf function.
The issue with quotes is that they are already used to start and end a formatting string or a literal. If you use only one quote, MatLab will interpret that as the end of the formatting string. Instead you repeat the quote twice.  Since the percent symbol is used to indicate the start of value, the same approach is used to enter the percent sign.
  1. function driver()
  2. % DRIVER driver() is the main or driver function
  3. %Demonstrate escape sequences for quotes and percentage symbol
  4.      fprintf('\n');
  5.      fprintf('Don''t use a single quote or a single %% sign\n');
  6.      fprintf('\n');
  7. end
  1. >> driver()
  2.      Don't use a single quote or a single % sign
  3. >>
Printing quotes and the percent symbol
Now that we know how to get the information out of a program, the efficient programming approach is to implement the calculations. But that was covered earlier in the interactive approach. That means we need to address getting the data into the program.

Entering the Data into program

 

Turning data into information requires data, that is any inputs. This can be done in two ways; by hardcoding the values directly into the program, and by having the user enter the data at runtime

Hard coding data

When developing the program it is a time saver to hard code the data directly into the variables that will be used.
  1. function driver()
  2. % DRIVER driver() is the main or driver function
  3. %Hard Coded Data
  4.      dist = 420;
  5.      fuel = 10.0;
  6.      eff = dist ./ fuel;
  7.      fprintf('\n');
  8.      fprintf('%15s%20.1f miles\n', 'Distance: ', dist);
  9.      fprintf('%15s%20.4f gallons\n', 'Fuel: ', fuel);
  10.      fprintf('%15s%20.1f mpg\n', 'Efficiency: ', eff);
  11.      fprintf('\n');
  12. end
  1. >> driver()
  2.       Distance:         420.0 miles
  3.           Fuel:          10.0000 gallons
  4.     Efficiency:          42.0 mpg
  5. >>
Hard Coding Inputs
Not only will this eliminate the need to constantly enter the data into the program for each variable in the calculations, It will also create a consistent set of inputs. Since you can hard code the inputs from the hand calculation, the results that should print are already known. If what prints is different, then there must be a logic error. Catching these errors at this stage is far easier than searching for them at the end.

Input Function

Hard coding data is useful, especially for constants that are used throughout the program. But they would require the user to edit the script each time the data changes. Instead a method for having the user enter data at runtime is necessary. This is done using the input function.
There are two forms for the input function depending upon whether the user will be entering a numerical values – either a floating point value or an integer – or entering a string of text.
When entering a numerical value the input function is called as shown in figure  Syntax of the input function for entering a floating point value.  The variable prompt is usually a string of text, but it does not have to be hard coded into the input function. It could be text stored in a variable.
Hardcoding the input data in a model is useful when developing the model. This saves the time of reentering the same values each time the program is run. Further, since the hand solution would have used these same inputs, it is easier to determine if the developing program has any logic errors. This was shown in the figure Hard Coding Input.
  1. variable = input(prompt);

Syntax of the input function for entering a floating point value

But once the program is working and the solution – at least for the single set of inputs – is known to be correct, these hard coded variables should be replaced with calls to the input function as in the figure Entering Numerical Data Using the Input Function
  1. function driver()
  2. % DRIVER driver() is the main or driver function
  3. %   Enter the data for the model
  4.    dist = input('Enter distance driven (miles): ');
  5.    fuel = input('Enter fuel purchased (gallons): ');
  6. %   Calculate fuel efficiency
  7.    eff = dist ./ fuel;
  8. %   Print the results
  9.    fprintf('\n');
  10.    fprintf('%15s%20.1f miles\n', 'Distance: ', dist);
  11.    fprintf('%15s%20.4f gallons\n', 'Fuel: ', fuel);
  12.    fprintf('%15s%20.1f mpg\n', 'Efficiency: ', eff);
  13.    fprintf('\n');
  14. end
  1. >> driver()
  2. Enter distance driven (miles): 380
  3. Enter fuel purchased (gallons): 12.3084
  4.       Distance:         380.0 miles
  5.           Fuel:          12.3084 gallons
  6.     Efficiency:          30.9 mpg
  7. >>

Entering Numerical Data Using the Input Function

Using the input function as show in figure Syntax of the input function for entering a floating point value  assumes the user is entering a numerical value – a float or an integer. In fact, whatever character is entered is converted from the characters to a numerical value. But if the user mistakenly enters a character or a string of text the interpreter throw an exception and print an error message. To correct this the input function call must indicate that the data to be entered is not numerical but is instead text. This is done by adding the modifier ‘s’ to the input function.
  1. variable = input(prompt, 's');
Syntax of the input function for entering a string of text
Numerical inputs are limited by white space. This means that if the user attempts to enter several numbers separated with commas or spaces between them the interpreter will give an error. But strings of text allow non-numerical characters such as symbols or spaces.
  1. function driver()
  2. % DRIVER driver() is the main or driver function
  3. %   Enter data as a string of text
  4.    name = input('Enter your name: ', 's');
  5. %   Print the results
  6.    fprintf('\n');
  7.    fprintf('Welcome, %s!\n', name);
  8.    fprintf('\n');
  9. end
  1. >> driver()
  2. Enter your name: Joe Bfstk!
  3. Welcome, Joe Bfstk
  4. >>
Entering A String of Text Using the Input Function

Summary

 

 

At its lowest level, a program in an interpreted programming language can be run interactively. The means entering the executable commands one at a time at the command line. While effective this approach is time consuming but also lacks repeatability. Writing a script will alleviate this. A script in an interpreted language is a text file with each command written in the order in which it is to be executed.
In its most simple form, each program consists of three sequential parts; creating the input data, computing using the data, and printing or returning the results or the information. An effective approach to writing the script is to create variables with fixed input and output values. From there you create the outputs.
Printing the results uses fprintf with the appropriate formatting string. Once the output is working, the next step is create the computational part of the program with the fixed values in the input variables. Finally, the inputs are created. These are often done using the input function.
Self Test
  1. What is the order of operations in arithmetic?
  2. What is the result of the following line of code?
    •     \[y = 4\dotProd 4\dotQuot 2 + 1\]

  3.  What is the result of the following line of code?
    •     \[y = 4\dotProd 4\dotQuot (2 + 1)\]

  4.  What is the result of the following line of code?
    •     \[y = 2\dotPow 3\dotProd 2 + 16\dotQuot 4\dotProd 2\]

  5. What is the result of the following line of code?
    •     \[y = 2\dotPow 3\dotProd (2 + 16)\dotQuot 4\dotProd 2\]

  6. What does the command isvarname do?
  7. What does the command iskeyword do?
  8. What is echoing?
  9. How is echoing implemented?
  10. What does the disp function do?
  11. How are integers and floating point values different?
  12. What is precision?
  13. What is a formatting string?
  14. What is the formatting string for printing an integer? A floating point value? A string of text?

 

Projects

  1. Write a script that uses fprintf with the appropriate formatting to print Hello World! on the screen.
  2. Write a script in which the user enters two values that are stored in the variables x and y. It then calculates the mean
      •     \[m = \frac{x + y}{2}\]

    • It prints two lines of output. For example, if the user enters 10 and 20, the program prints
      X Y Mean
      10.00 20.00 15.00
  3. Write a script in which the user enters two values that are stored in the variables x and y. It then calculates the root-mean-square
      •     \[\mbox{rms} = \sqrt{\frac{x^2 + y^2}{2}}\]

    • It prints two lines of output. For example, if the user enters 10 and 20, the program prints the result formatted to two decimal places as
      X Y Mean
      10.00 20.00 15.81
  4. Write a script in which the user enters the temperature in degrees Fahrenheit and it converts it to degrees Celsius. The transformation formula is
      •     \[^{\circ}C = \frac{5}{9}\left(^{\circ}F - 32\right)\]

    • The temperatures should be formatted to show two places of precision. A sample output might be
      • 47.00 \mbox{ degrees F } = 8.33 \mbox{ degrees C}
  5. Write a script in which the user enters the temperature in degrees Celsius and it converts it to degrees Fahrenheit. The transformation formula is
      •     \[^{\circ}F = \frac{9}{5}^{\circ}C + 32\]

    • The temperatures should be formatted to show two places of precision. A sample output might be
      • 27.00 \mbox{ degrees C } = 80.60 \mbox{ degrees F}
  6. A force F acting on a body can be decomposed into its x and y components. This requires the use of the sine and cosine functions;
      •     \[F_x = F\cos(\theta)\]

      •     \[F_y = F\sin(\theta)\]

    • In MatLab, the functions sind(angle) and cosd(angle) will return the value of the sine and cosine where angle is a variable storing the the angle in degrees the force makes at the point. Write a script in which the user enters two variables; the force F and an angle angle in degrees. It then calculates the decomposition of the force in the x and y directions. The output should be a table formatted to two decimal places such as
      F Angle Fx Fy
      100.00 30.00 86.60 50.00
  7. A projectile is launched from the ground at an angle \theta with an initial velocity of v_0 \mbox{ m/s}. The time until it hits the ground is
      •     \[t_f = \frac{2(v_0)_y}{g}\]

    • where (v_0)_y = v_0\sin(\theta) and g = 9.81 \mbox{ m}/\mbox{sec}^2 is the acceleration due to gravity.
    • Write a script in which the user enters the initial velocity and the initial angle, and the program calculates the time until impact.  The output should be a table formatted to two decimal places such as
      Velocity (m/sec) Angle (Degrees) Impact (sec)
      50.00 60.00 8.83
    • Do not use 9.81 directly in the calculation, but create a variable g and set it to the constant 9.81.
  8. Three forces are acting at a point at a point. The first is a force of F_1 acting at an angle of A^{\circ}. The second is a force of F_2 acting at an angle B^{\circ}. The third is F\_3 acting at an angle C^{\circ}. Write a MatLab program that that analyzes the individual forces and calculates the resultant force. In particular decompose each force into its x and y direction components. Then calculate the resulting x and y components of the resultant force by summing the component forces. Finally, calculate the overall resultant force and the angle that it would make as a single resultant force. Have the user enter the three forces, F\_1, F\_2, and F\_3, and the angles that each of these make on the beam, A^{\circ}, B^{\circ}, and C^{\circ}. These are all scalar values. The formulae for decomposing the angles are
      •     \[F_{1x} = F_1\cos\left(A\right) \qquad F_{1y} = F_1\sin\left(A\right)\]

      •     \[F_{2x} = F_2\cos\left(B\right) \qquad F_{2y} = F_2\sin\left(B\right)\]

      •     \[F_{3x} = F_3\cos\left(C\right) \qquad F_{3y} = F_3\sin\left(C\right)\]

      •     \[F_{Rx} = F_{1x} + F_{2x}  + F_{3x} \qquad F_{Ry} = F_{1y} + F_{2y} + F_{3y}\]

      •     \[F_R = \sqrt{F_{Rx}^2 + F_{Ry}^2} \qquad D = \tan^{-1}\left(\frac{F_{Ry}}{F_{Rx}}\right)\]

    • In Matlab, the command to calculate the trig functions for an angle A is sind(A) and cosd(A). The inverse tangent is D = atand(y./x); Your program should print the three forces and their angles with the two component forces for each. You will also print the the two components of the resultant force, the overall resultant force and its angle, D.

License

Discover Computing Copyright © by Brian Adams. All Rights Reserved.