Structured Programming and Applications A. Haghighat M. Department of Building, Civil & Environmental Engineering (BCEE 231) Lecture 1 (January 13, 2025) Today’s lecture: - An overview of Structured Programming - Advantages of Matlab Programming - Vectors and Matrices in Matlab Textbook: Chapters 1 & 2 Structured Programming and Applications 1 Motivation for Structured Programming • The computer programs used in engineering applications are written using high-level languages because of their clarity. • These languages have to follow strict logical statements which will be our focus in this course. • Structured programming aims at improving clarity, (logical) quality, and development time of a computer program. • Common features of structured programs are their modularity and use of block procedures such as subroutines and functions, as well as control statements for the logical flow control; these features make the use of structured programming suitable for scientific and engineering applications. Structured Programming and Applications 2 Elements of Structured Programming – Control Structures Sequence: Simply doing one instruction (task) then the next and the next. Just do them in a given sequence or in the order listed. Example: Baking bread requires the execution of a list of statement in a sequence. Add flour to bowl → Add salt → Add yeast → Mix → Add water → Knead → Let rise → Bake Iteration: The code or algorithm is executed for a certain number of times Or might not be executed at all (repeats zero time) Or executed indefinitely until some conditions are met. Example: Washing dishes requires iterations. Stack dishes by sink Fill sink with hot soapy water Get dish from counter Selection: This is where you select or choose between two or more flows. The choice is decided by asking some sort of question/condition. The answer then determines the path (or which lines of the code) will be executed. Wash the dish Put dish in drain rack Wipe off counter Rinse out sink Example: Sorting mail requires selection. Read it If personal If magazine Get mail from mailbox If bill If ads Structured Programming and Applications Magazines basket Pay it Put in recyclables bin 3 Elements of Structured Programming – Operators Arithmetic operators: Give us results for certain mathematical operations. Relational operators: Check whether an expression is True or False Example: Structured Programming and Applications 2 == 3 False 2 \= 3 True 2>3 False 2<3 True 2 >= 3 False 2 <= 3 True 4 Elements of Structured Programming – Operators Logical operators: Are both statements True? Is either statement True? Example: AND True only if both statements are True OR True if either item is True 3 + 5 > 6 AND 18 < 21 True AND True True 3 + 5 > 10 AND 18 < 21 False AND True False 3 + 5 > 10 AND 18 < 18 False AND False False 3 + 5 > 6 OR 18 == 18 True OR True True 3 + 5 > 6 OR 18 == 21 True OR False True 3 + 5 > 16 OR 18 == 21 False OR False False Structured Programming and Applications 5 Elements of Structured Programming – Variables and Arrays Variable: Variable is an area of memory that stores one item of data. Variables basically serve two purposes: 1. The programmer can choose the names of the variables, making coding easier. 2. Programs or functions can be developed using variables in a way that they work with any values. Types of variables Integer Integers are whole numbers; integer variables are used when we are certain there not going to be any need for numbers after the decimal point. e.g., if you are counting people, cars, etc. Real or float Numbers that contain fractional parts or in other words numbers with a decimal place (e.g., 2.2). Character A character variable stores either a single letter (e.g., ‘s’) or multiple letters (e.g., ‘storm’). Boolean A Boolean variable can store on of the two values – either TRUE or FALSE Array: An array is the most fundamental representation of information and data. Arrays are a collection of several values of the same type. Structured Programming and Applications 6 Elements of Structured Programming – Functions Functions • Within a computer program, a function is a sequence of program instructions that performs a specific task, packaged together. • Function is a block of organized, reusable code that can be used within a program wherever that particular task should be performed. • Functions provide better modularity for your application and a high degree of code reusing. Variables are passed to a function by value. • Functions can be used within command lines like variables. • Functions help reducing code size, and improve readability and debugging procedure Structured Programming and Applications 7 Choosing a programming language, Why MATLAB? • Be easy for beginners to learn, understand, and implement • Be a general-purpose programming language • Be interactive • Shield the user from detail understanding of the computer hardware and operating system • It is high-level programming language which allows quick coding • Use of arrays is very flexible. • Many built-in functions and toolboxes are available. • Easy to use visualization tools (e.g., graphs, charts, etc.) are offered in MATLAB. Structured Programming and Applications 8 MATLAB Environment • The simplest method for using MATLAB is interactively; an expression is entered by the user and MATLAB responds immediately with a result. prompt Command window Structured Programming and Applications 9 MATLAB Environment • In command window, user and MATLAB can communicate in real time; e.g., MATLAB can be your calculator. You can enter any expression or command at the prompt. Structured Programming and Applications 10 MATLAB Environment • Some commands that allow you to get help from MATLAB: demo, help, lookfor, doc ➢ To exit from MATLAB, either type quit or exit at the prompt, or click on “x”. Structured Programming and Applications 11 Variables in MATLAB To store a value in a MATLAB session, or in a program, a variable is used. The Workspace Window shows variables that have been created and their values. An easy way to create a variable is to use an assignment statement: variablename = expression meaning: “variable b gets the value of 3, not “variable “b” equals 3” Structured Programming and Applications 12 Variables in MATLAB • Note that the variable name must always be on the left, and the expression on the right. An error will occur if these are reversed. • You can use a semicolon at the end of a statement to suppress the output from being printed out. • A shortcut for retyping commands is to hit the up arrow ↑, which will go back to the previously typed command(s). This is very useful, especially if a long expression is entered and it contains an error, and it is desired to go back to correct it. • To change a variable, another assignment statement can be used, which assigns the value of a different expression to it. Structured Programming and Applications 13 Variables in MATLAB Variable Names ❑ The name must begin with a letter of the alphabet. After that, the name can contain letters, digits, and the underscore character (e.g., value_1), but it cannot have a space. ❑ There is a limit to the length of the name (it is 63); the built-in function namelengthmax tells what this maximum length is. ❑ MATLAB is case-sensitive, which means that there is a difference between upper- and lowercase letters. So, variables called mynum, MYNUM, and Mynum are all different. ❑ There are certain words called reserved words, or keywords, that cannot be used as variable names (e.g., for, if, float, return, while, continue, etc.) ❑ Names of built-in functions (eye, rectangle, sin(), etc.) can but should not be used as variable names. ❑ Some useful functions for working with variables: who, whos, clearvars, clear Structured Programming and Applications 14 Variables in MATLAB • In the Workspace Window, the variable name, value, and class (which is essentially its type) can be seen. • The function class can be used to see the type of any variable: Structured Programming and Applications 15 Numerical expressions in MATLAB ❖ The default in MATLAB is to display numbers that have decimal points with four decimal places. The format (short or long) command can be used to specify the output format of expressions. ❖ Continuation operator (ellipsis): Especially long expressions can be continued on the next line by typing three periods. Structured Programming and Applications 16 Numerical expressions in MATLAB Operators + addition Negation or subtraction * multiplication / division (divided by e.g., 10/5 is 2) \ division (divided into e.g., 5\10 is 2) ^ exponentiation (e.g., 5^2 is 25) Operator Precedence Rules (PEMDAS) () parentheses ^ exponentiation negation *, /, \ all multiplication and division +, addition and subtraction * Within a given precedence level, the expressions are evaluated from left to right Constants Structured Programming and Applications 17 Numerical expressions in MATLAB Built-in functions To call a function, the name of the function is given followed by the argument(s) that are passed to the function in parentheses. ❑ Some of the other built-in functions: fix, floor, ceil, mod, exp, log, and log10 * To see a list of elementary math functions, >> help elfun generates one random real number in the open interval (0,1) generates random real numbers returns a random integer in the range (inclusively) Structured Programming and Applications 18 Characters and strings in MATLAB ➢ A character in MATLAB is represented using single quotes (e.g., ‘a’ or ‘x’). ➢ Characters are put in an order using what is called a character encoding. ➢ In the character encoding, all characters in the computer’s character set are placed in a sequence and given equivalent integer values. ➢ Standard ASCII has 128 characters, which have equivalent integer values from 0 to 127. ➢ The character set includes all letters of the alphabet, digits, and punctuation marks. ➢ Strings are sequences of characters in double quotes (e.g., "ciao"). ➢ To know the integer associated with a character you can use built-in function double ➢ To know the character associated with an integer you can use built-in function char Structured Programming and Applications 19 Relational expressions in MATLAB Relational (Boolean) expressions Structured Programming and Applications 20 Vectors and Matrices in MATLAB ❖ Everything in MATLAB is written to work with vectors and matrices. The following slides will introduce vectors and matrices. Operations on vectors and matrices and builtin functions that can be used to simplify code will be reviewed. ❑ Vectors and matrices are used to store sets of values, all of which are the same type. ❑ A matrix can be visualized as a table of values. The dimensions of a matrix are r x c (pronounced r by c), where r is the number of rows and c is the number of columns. ❑ A vector can be either a row vector or a column vector. If a vector has n elements, a row vector have the dimensions 1 x n and a column vector have the dimensions n x 1. ❑ A scalar (one value) has the dimensions 1 x 1. Structured Programming and Applications 21 Vectors and Matrices in MATLAB Creating row vectors • Put the values that you want in the vector in square brackets, separated by either spaces or commas. • If the values in the vector are regularly spaced, the colon operator can be used to iterate through these values. • With the colon operator, a step value can also be specified by using another colon, in the form (first:step:last). • linspace function creates a linearly spaced vector; linspace(x,y,n) creates a vector with n values in the inclusive range from x to y. • Putting two vectors together by concatenating the vectors. Structured Programming and Applications 22 Vectors and Matrices in MATLAB Referring to and modifying elements of row vectors • The elements in a vector are numbered sequentially; each element number is called the index, or subscript. In MATLAB, the indices start at 1. indices elements ➢ Accessing a particular element: (pronounced “newvec sub 5”) ➢ Accessing a subset (several elements) of a vector: index vector ➢ Accessing a subset of a vector (any vector can be used for the indices into another vector): Structured Programming and Applications 23 Vectors and Matrices in MATLAB ➢ The value stored in a vector element can be changed by specifying the index or subscript. ➢ By referring to an index that does not yet exist, a vector can also be extended. Creating column vectors • One way to create a column vector is to explicitly put the values in square brackets, separated by semicolons (rather than commas or spaces): • Any row vector created using any method can be transposed to result in a column vector. In MATLAB, the apostrophe (or single quote) is built-in as the transpose operator. Structured Programming and Applications 24 Vectors and Matrices in MATLAB Creating Matrices • For matrix, the values within a row are separated by either spaces or commas, and the different rows are separated by semicolons. • Iterators can be used for the values in the rows using the colon operator. * There must always be the same number of values in each row and each column of a matrix. Structured Programming and Applications 25 Vectors and Matrices in MATLAB ❖ Matrices of random numbers can be created by rand and randi: ▪ If a single value n is passed to rand, an n x n matrix will be created ▪ If two arguments are passed, they specify the number of rows and columns in that order. ▪ Matrices of random integers can be generated using randi; after the range is passed, the dimensions of the matrix are passed. Structured Programming and Applications 26 Vectors and Matrices in MATLAB ❖ Several functions that create special matrices: zeros, ones, and eye: Referring to and modifying matrix elements • To refer to matrix elements, the row and then the column subscripts are given in parentheses: This is called subscripted indexing Structured Programming and Applications 27 Vectors and Matrices in MATLAB ❖ An individual element or an entire row/column in a matrix can be modified by assigning new values to them. The exception to this rule is that a scalar can be assigned to any size subset of a vector or matrix Structured Programming and Applications 28 Vectors and Matrices in MATLAB ❑ To extend a matrix, an individual element could not be added as that would mean there would no longer be the same number of values in every row. However, an entire row or column could be added: Structured Programming and Applications 29 Vectors and Matrices in MATLAB Vector and matrix dimensions ➢ The length and size functions are used to find dimensions of vectors and matrices. For vectors: For matrix: ➢ MATLAB also has a function numel, which returns the total number of elements in any array (vector or matrix): Structured Programming and Applications 30 Vectors and Matrices in MATLAB Changing matrix dimensions MATLAB has several built-in functions that change the dimensions or configuration of matrices, including reshape, fliplr, flipud, flip, and rot90. Structured Programming and Applications 31 Vectors and Matrices in MATLAB Empty vectors • An empty vector (a vector that stores no values) can be created using empty square brackets: ➢ Values can then be added to an empty vector by concatenating: ➢ Empty vectors can also be used to delete elements (one or even a subset) from vectors: ➢ Individual elements cannot be removed from matrices, but entire/column can: Structured Programming and Applications 32 Vectors and Matrices in MATLAB Vectors and matrices as function arguments • An entire vector/matrix can be passed as an argument to a function; function will be evaluated on every element, meaning that the result will be the same size as the input argument. • There are some functions (min, max, sum, prod) that are written specifically to operate on vectors or on columns of matrices: Structured Programming and Applications 33 Vectors and Matrices in MATLAB Vectors and matrices as function arguments • A matrix with dimensions r x c, the result for the min, max, sum, and prod functions will be a 1 x c row vector, as they return the minimum, maximum, sum, or product for every column. • To work with rows, one method would be to transpose the matrix: • Another useful function that can be used with vectors and matrices is diff: Structured Programming and Applications 34 Vectors and Matrices in MATLAB • There are also functions that return cumulative results; the functions cumsum and cumprod return the cumulative sum or cumulative product, respectively Structured Programming and Applications 35 Vectors and Matrices in MATLAB • The cummin and cummax functions find the cumulative minima and maxima for every column. Structured Programming and Applications 36