Reference Section: Computing for Engineers, Computer Science

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

find(vec)

returns the numerical indices where a logical vector is true

strfind(str, pattern)

returns the numerical indices where each incidence of the pattern of letters occurs in a string

prod(vec)

returns the product of the values in a vector

mod(x,y)

returns the remainder after x is divided by y

min(x) -

returns the smallest element in the collection (Note: if the minimum value occurs

[v,o] = sort(vec)

returns the sorted values of a vector and their positions. Sorts cell arrays in alphabetical order.

sum(vec)

returns the sum of the values in vec

[a b] = max(vec)

returns the value and position of the maximum value in a vector

[a b] = min(vec)

returns the value and position of the minimum value in a vector

(struct, field) -

returns the value of a field in a structure

getfield (struct, field)

returns the value of a field in a structure

double(vec)

returns the values of vec as floating point numbers

between start and stop logical(vec)

returns the values of vec as true or false

all(vec)

returns true if all of the values in a logical vector are true

any(vec)

returns true if any of the values in a logical vector are true

strcmp(a,b)

returns true if the string in a is identical to the string in b

strcmpi(a,b)

returns true if the string in a is identical to the string in b, ignoring case

floor(num) -

rounds a decimal down to the closest integer

ceil(num)

rounds a decimal up to the closest integer

round(num)

rounds a number to the nearest integer

Naming Variables

Must begin with letters and can only consist of letter, numbers, and underscores No spaces Cannot have the same name as a built-in MATLAB function Function names are case sensitive

Useful Functions:

ones(x,y) - creates an array of ones of dimension x,y (Use 1 for x or y to generate vectors) zeros(x,y) - creates an array of zeros of dimension x,y true(x,y) - creates an array of logical trues of dimension x,y false(x,y) - creates an array of logical falses of dimension x,y magic(x)—creates a magic square of dimension x [row,col] = size(arr)—returns the number of rows and columns in the input array The following functions work differently with arrays than with vectors. Built-in functions generally treat arrays as individual column vectors and express their outputs as row vectors. [value,index] = min(arr)—returns a row vector of the minimum values in each column. The second output contains the row number of the minimum value in each column [value,index] = max(arr)—returns a row vector of the maximum values in each column. The second output contains the row number of the maximum value in each column [sorted_arr,index] = sort(arr)—sorts each column of the array in ascending order from top to bottom. The second output consists of the indices used to sort each column concatenated together as an array sum(arr)—returns a row vector of the sum of each column in the array mean(arr)—returns a row vector of the mean of each column in the array To determine the absolute minimum, maximum, sum, or mean of an array, simply call the respective functions twice. [value, index] = max(max(arr))—returns the absolute maximum of the array along with its column number [value, index] = min(min(arr))—returns the absolute minimum of the array along with its column number sum(sum(arr))—returns the overall sum of the elements in the array mean(mean(arr))—returns the overall mean of the elements in the array I know these explanations can be somewhat confusing, so do yourself a favor and play around with the min(), max(), mean(), and sort() functions for a few minutes. All four frequently appear on homeworks and test problems.

Consider the following function, defined in MATLAB's current directory: function [out1, out2] = vecMath(in1) out1 = class(in1); arr = rand(in1); out2 = arr(1,:); end The following code is run in the Command Window: num = 3; arr = ones(2,2); [a,x] = vecMath(num); [b,c] = size(x); % LINE 9 e(1,1:2) = arr; % LINE 10 (a-d) After line 9 is run, what values are stored in variables a, b, c, and d? (e) Does out1 exist in the current workspace? Briefly explain. (f) When line 10 is run in the command window, it produces an error. Explain why.

'double' num is 3, which is passed to vecMath as in1. The output from the class function is always type char. 1 rand(3) creates a 3x3 matrix. out2 is the first row, so it is a 1x3 vector. out2 is passed to the command window as x. 3 size outputs are [rows, columns] Does Not Exist d is never defined in either workspace No out1 is defined in the vecMath workspace, not the command window workspace. Dimension Mismatch arr has 4 elements, but only 2 positions have been indexed on the right side of the assignment operator.

What is the difference between formal and actual parameters?

Formal parameters are variable names used in a function. Actual parameters are variables used when calling a function.

Consider the following function, defined in MATLAB's current directory: function [out1, out2] = vecMath(in1) out1 = class(in1); arr = rand(in1); out2 = arr(1,:); end The following code is run in the Command Window: num = 3; arr = ones(2,2); [a,x] = vecMath(num); [b,c] = size(x); % LINE 9 e(1,1:2) = arr; % LINE 10 (a-d) After line 9 is run, what values are stored in variables a, b, c, and d? (e) Does out1 exist in the current workspace? Briefly explain. (f) When line 10 is run in the command window, it produces an error. Explain why.

'double' num is 3, which is passed to vecMath as in1. The output from the class function is always type char. 1 rand(3) creates a 3x3 matrix. out2 is the first row, so it is a 1x3 vector. out2 is passed to the command window as x. size outputs are [rows, columns] Does Not Exist d is never defined in either workspace No out1 is defined in the vecMath workspace, not the command window workspace. Dimension Mismatch arr has 4 elements, but only 2 positions have been indexed on the right side of the assignment operator. Hide Answers

prod(x)

- computes the product of x

false(x,y)

- creates an array of logical falses of dimension x,y

true(x,y)

- creates an array of logical trues of dimension x,y

ones(x,y)

- creates an array of ones of dimension x,y (Use 1 for x or y to generate vectors)

zeros(x,y)

- creates an array of zeros of dimension x,y

fliplr, flipud(arr)

- flip an array horizontally and vertically, respectively

find(logical expression)

- generates a vector of all indices where the logical expression is true

randn(x,y)

- identical to rand() except all values are truly random

mod(x,num)

- returns the remainder if x is divided by num

[value, index] = min(x)

- returns the smallest element along with its position number multiple times, min() and max() will return only the first instance)

[newX, index] = sort(x)

- returns x in ascending order along with a vector containing the positionnumbers of the original x to which each value corresponds

floor(x)

- rounds x down to the next-lowest integer if x is fractional

round(x)

- rounds x up or down

What is the value of "len" after the lines of code are run

0

The following function is defined in the current folder of MATLAB: function ca = circle_area(A) A = A ./2 ; ca = pi .* (A ^ 2); end The following is run in the MATLAB command window: A = 2; B = circle_area(A) ./ pi; What are the values of the variables A and B?

2 A is only altered in the scope of the function. It is unchanged in the command window's scope. 1 Output of the function with input A=2.

The following code is run in the command window: arr1 = [1:3 ; 4:6] arr1(end,:) = [7 8 9] [A row] = size(arr1) B = [1 ; [2:4]']; vec1 = 5:-2:1 vec2 = [1 3 7 1] vec2(7) = 8 C = vec2(vec1) D = vec1 < 2 E = class(D) Give the values of the variables A-E from the MATLAB Command Window workspace after the above code is run.

2 The first output of the size() function is the number of rows. arr1 has 2 rows. [1;2;3;4] B is initially set as [1; [2 3 4]'], which is [1;2;3;4]. B is not reassigned later on in the code. [0, 7, 1] vec1 is initially [5, 3, 1] and vec2 is initially [1 3 7 1]. Then we set the 7th position of vec2 to 8, so vec2 is now [1 3 7 1 0 0 8] (zeroes fill in the missing indicies by default). Then, we index vec2 using vec1, meaning that we get positions 5, 3 and 1 from vec2. [false, false, true] vec1 < 2 gives us true everywhere where vec1 is less than 2, which gives us [false false true]. 'logical' D contains trues and falses, and thus is class logical. The class() function gives a string as the output.

The following function is defined in the current folder: function [C, perim, area] = rightTriangleInfo(A, B) A = A^2; B = B^2; C = sqrt(A + B); perim = sqrt(A) + sqrt(B) + C; area = 0.5 * sqrt(A) * sqrt(B); end The following is run in the MATLAB command window: A = 3; B = 4; [C D E] = rightTriangleInfo(A, B); What are the values of the following values?

3 The function only modifies a copy of A that's "inside the scope of the function," so the value in the command window is not affected. 4 The function only modifies a copy of B that's "inside the scope of the function," so the value in the command window is not affected. 5 Trace through the function to get the output this is assigned to. 12 The value of perim at the end of the function is assigned to D. 6 The value of area at the end of the function is assigned to E.

mileTimes = [7.5 7 6.5 7] A = mean(mileTimes) if A < 6.5 | A > 6 B = true elseif A >= 7 B = false else B = 'so fast' A = 5 end vec1 = mileTimes < 6.5 vec2 = mileTimes > 6 if any(vec1 & vec2) C = 'run' end D = min(mileTimes) switch D case {6} E = 'good job' case {10} E = 'even better' otherwise E = 'try again' end Give the values of the variables A-E from the MATLAB Command Window workspace after the above code is run.

7 The else never runs. true The interval created in the first if statement encompasses all numbers. ERROR vec1 = [false false false false] and vec2 = [true true true true].vec1 & vec2 = [false false false false], and any(vec1 & vec2) = false 6.5 Takes the minimum of the vector. 'try again' The switch statement doesn't run either of the cases, so the otherwise runs.

Why is the function strcmp() and not the == operator often necessary to compare strings?

== will error if the two strings are different sizes. Also, it does an element-by-element comparison, rather than an overall comparison.

Vectors:

A vector is a set of data (elements); also known as a data structure. Vectors could be numerical, strings, or logical. They are homogenous data structures, which mean that they only can consist of one type. Row vectors and column vectors both exist, although the syntax is different for each. Vectors have length- even if the length is simply 1 or 0. For example, you can create an empty vector using just brackets: Empty = [] Creating Vectors of logicals or doubles: 1. Put a series of numbers in brackets separated by either spaces or commas (creates a row vector) vec = [1 1 2 3 5 8]; or vec = [1, 1, 2, 3, 5, 8]; log = [true false true true]; 2.Put a series of numbers in brackets separated by semi colons (creates a column vector) vec = [1; 1; 2; 3; 5; 8]; log = [true; false; true; true]; 3.Use the colon operator to specify a start and stop value and a step size (note: stop value may not be used, depending on step size). -The format is start:step:stop -You do not need to put brackets around this. -Note that your step can be positive or negative. vec = 1:2:6; -> vec = [1 3 5]; vec = 6:-2:1; -> vec = [6 4 2]; 4.Use the linspace function if you absolutely must include both the start and stop values. -The format is linspace(start,stop,amount_of_values_desired) *This work is a combination of ideas from other TAs and materials, as well as our own vec = linspace(0, 2, 5); -> vec = [0,0.5, 1, 1.5, 2]; 5.Use functions such as zeros, ones, or rand to create vectors of a specified length of 0s, 1s or random numbers equally distributed between 0 and 1 -Note that the two inputs for these functions are the number of rows, and the number of columns. vec = zeros(1, 3); -> vec = [0 0 0]; vec = ones(1, 4); -> vec = [1 1 1 1]; vec = rand(1, 5); -> vec = [0.6445 0.6265 0.7946 0.9632 0.1025]; %since it's random it could vary Creating a Vector of chars: 1.Type out the values in single quotes A = 'I get around' 2.Painstakingly type each character out with quotes in a vector A = ['I' ' ' 'g' 'e' 't' ' ' 'a' 'r' 'o' 'u' 'n' 'd'] %note that even spaces get a character value! Numerical Indexing: Indexing is a way for you to select certain elements in a data structure and manipulate them. ​ In Matlab, indexing starts at 1 Hence, the to call the first element in the vector, one would type ​ val = vec(1) ​ For example, given: Vec = [17 38 65 45 5] If I wanted to index all of the even indices, I could say: nVec = vec(2:2:end) *This work is a combination of ideas from other TAs and materials, as well as our own Tobin Abraham RJ Tayal Using the end value in Matlab is a good way to call the last element in a vector, which is useful if you don't know how long the vector is. If you try to index at a value that doesn't exist, Matlab will error, as there isn't any values to retrieve. In contrast, if you add a value at a position that doesn't exist, Matlab will place it there and put zeros where you di not specify any value. Given the above vector: vec(8) = 36 The vector would then look like [17 38 65 45 5 0 0 36] Finally, all of the operations we did here can also be used on logical vectors and strings.

Define abstraction and encapsulation.

Abstraction is that even though you do not know how to write the code someone wrote, if you know how to use it, you can implement and utilize it in your function. For example, even though we might not know how to write mod function, but you can use mod function without really knowing how it works. Encapsulation is where each function has its own "scope" or "workspace."

What value can you add to or subtract from a given uppercase character to convert it to the same lowercase character?

Add ' ', 32 (the ASCII value for space), or add 'a'-'A'.

Introduction How To Test Your CodeA CS 1371 Homework Guide

After you have completed each drill problem, you should make it a habit to test your code. There are good ways of testing your code and there are bad ways of testing your code. This guide is written to teach you good ways and to help you avoid bad ways. What To Avoid The first thing many students try is to copy and paste each test case from the hw##.m file into the Command Window to execute the function and to compare the printout in the Command Window with the solution in the he##.m file by inspection. Not only is this method slow and tedious, it is also prone to many errors, including the following: Your function, as you have coded it, may simply be printing the values of the outputs to the Command Window instead of actually setting output variables. Please make sure your function is producing output variables that appear in the Workspace. Your outputs may look correct when inspected by eye, but you cannot be sure that they are exactly identical to the correct outputs. This is especially true of output strings, where it is easy to miss a space or punctuation mark or even several English words entirely! For example, 'A C' vs. 'A C ' or 'I like turtles.' vs. 'I like turtles' or 'This item is worth $9.' vs. 'The item is worth $9.'. You may also fall victim to misinterpreting the typed-out solution on the hw##.m file. The typed-out solution (which usually looks like out2 => [4, 5; 6, 7; 8, 9] or like str1 => 'Congratulations! You''re the big winner!') is meant to be interpreted as a block of code to be entered into the Command Window. For example, in the first case, a correctly-coded function would produce an output variable called out2 that is a 3x2 array of type double. If you were to compare this variable to the result of entering out2_soln = [4, 5; 6, 7; 8, 9]; into the Command Window, the two variables out2 and out2_soln should be identical. In the second case, a correctly- coded function would output a variable called str1 that is identical to the result of entering str1_soln = 'Congratulations! You''re the big winner!'; into the Command Window. Note that the two single quotation marks are necessary to create a single quotation mark character inside of a string in MATLAB. Your function will ultimately be tested by the Homework Autograder, which compares the outputs of your function with the outputs of the solution file (the file that looks like functionName_soln.p), given inputs from several different test cases. This means that, ideally, you should be testing your code against the solution file instead of the typed-out solutions on the hw##.m file, which are not guaranteed to be correct. What To Do Instead Write a test script! Test Scripts How To Test Your CodeA CS 1371 Homework Guide A test script is a script that you run in order to execute your functions with test cases, each of which is just an input or series of inputs with an associated expected output. A script is just a block of code that you can run without any inputs or outputs. The ABCs pretest file that comes with every homework assignment is a perfect example of a test script. You can't open it, because it's encrypted, but if you could look inside of it, you would see nothing more than a block of code that calls your ABCs function using one or two test cases and compares the outputs of your function to the expected outputs. It then prints out a series of statements to the Command Window which tell you which outputs were correct and which were incorrect. Our goal is to design a similar script to test the code that you write for the drill problems. Writing A Test Script Writing a test script is easy! The first thing you should start with is the built-in clear function. This function will delete all of the variables in your current Workspace so that you can test your code in a clean environment without the risk of mixing up variable names. Remember that you should never use clear in a function, only in a script. The next thing to do is to call your functions with a couple of test cases. For simplicity, we will only call one function in this simple example. Suppose your function is supposed to find the area and perimeter of a rectangle given two side lengths. The function should work as follows: [area, perim] = rectangleMath(width, height) Notice that the function is called rectangleMath and that it takes two inputs and produces two outputs. This means that we will have to execute or call this function in our test script using two inputs from a test case. Which test case should we use? Theoretically, you can use any test case you want. However, for your benefit, there are suggested test cases in the hw##.m file. They might look the following: width1 = 2; height1 = 5; and width2 = 0; height2 = 1; Each pair of inputs is a test case. Notice that the names of the inputs of the first test case end with the number 1 and the names of the inputs of the second test case end with the number 2. This makes sense and is good coding practice. After copying the code above into our test script, we are ready to use them to call our function. Remember that we need to assign two outputs for each function call. We will assign them as follows: How To Test Your CodeA CS 1371 Homework Guide [area1, perim1] = rectangleMath(width1, height1); [area2, perim2] = rectangleMath(width2, height2); Again, notice the use of the numbers 1 and 2 at the end of the names of our outputs. Keep the naming of your variables consistent to avoid unnecessary confusion. At this point, you may think that we are done. We can run the script as it is and inspect the outputs, comparing them to what we know should be the correct outputs. Not so fast! Remember what we said about using the solution files. It may seem trivial in this simple example, but it is very important when testing more complicated code. In your homework folder, you should have been provided with encrypted solution files. In this example, the solution file will be a function called rectangleMath_soln. Let's call the solution function on the same test cases as follows: [area1_soln, perim1_soln] = rectangleMath_soln(width1, height1); [area2_soln, perim2_soln] = rectangleMath_soln(width2, height2); Notice that we are storing our outputs in new variables, with _soln appended at the end of each. This is to distinguish them from the output variables of our own implementation of the function. If we had not done this, we would have overwritten the previous values of area1, perim1, area2, and perim2. Now we can compare the value of area1 with the value of area1_soln and compare the value of perim1 with the value of perim1_soln and so on for the second test case, right? We're done, right? Wrong! Remember that you should refrain from comparing your outputs to the solution outputs by inspection. Instead, we will use a more precise, foolproof method of comparison, the built-in isequal function. The isequal function takes two inputs and tells you if they are equal or not by outputting a logical true or false. Let's call isequal for each pair of output variables to see if our function behaves the same as the solution function. We will write the following lines of code: check_area1 = isequal(area1, area1_soln); check_perim1 = isequal(perim1, perim1_soln); check_area2 = isequal(area2, area2_soln); check_perim2 = isequal(perim2, perim2_soln); Note that the naming of the logical output variables is consistent with what they represent. For example, if after running out test script, check_area1 has the value true, then we know that the area computed by our function is exactly the same as the area computed by the solution file, at least for the first test case. If all of these check variables are true, then we know that our function is probably correct. This does not guarantee, however, that your code will receive full credit when you submit it. That will depend on which test cases the Autograder runs. That is why it is important to test your code with many different test cases and why we provide you with several suggested test cases. If any of the check variables are false, then there is something wrong with your function and you should go back to your code and try to fix the problem. How To Test Your CodeA CS 1371 Homework Guide Congratulations! You just wrote a test script! Of course, on your actual homework, you will have more than one function to implement and test. The process of adding more functions to your test script is the same. Define some input variables from the suggested test cases. Call your function on those inputs. Call the solution function on those same inputs. Generate check variables by using isequal to compare the resulting outputs. Inspect the check variables in the Workspace to ensure that all of them are true. That's it! Just make sure that you do not reuse any variable names. This will cause unexpected and potentially frustrating results. Here is the complete test script: % Test Script clear % Test Case 1 width1 = 2; height1 = 5; % Test Case 2 width2 = 0; height2 = 1; % My Function Outputs [area1, perim1] = rectangleMath(width1, height1); [area2, perim2] = rectangleMath(width2, height2); % The Solution Function Outputs [area1_soln, perim1_soln] = rectangleMath_soln(width1, height1); [area2_soln, perim2_soln] = rectangleMath_soln(width2, height2); % Check Test Case 1 check_area1 = isequal(area1, area1_soln); check_perim1 = isequal(perim1, perim1_soln); % Check Test Case 2 check_area2 = isequal(area2, area2_soln); check_perim2 = isequal(perim2, perim2_soln); Testing Outputs That Are Not Variables The example test script above will work for all types of output variables, including doubles, logicals, chars (strings), cells, and structures. However, some weeks, the homework will require you to write functions that output things other than variables, such as text files, Excel files, plots, or image files. How can you test these? Let's break it down. Testing Text Files How To Test Your CodeA CS 1371 Homework Guide The first thing to check is to see that your text file is named correctly, exactly as specified in the problem statement. You may choose to do this by inspection. Now comes the hard part. How can you compare the contents of your output text file with the contents of the solution text file? It turns out that MATLAB has a built-in tool that will take care of this for you. Suppose your output file is called 'textFile1.txt' and the solution text file provided in the homework is called 'textFile1_soln.txt'. From the Command Window, type and run the following command: visdiff('textFile1.txt','textFile1_soln.txt'); At this point, a new window should pop up. This is the MATLAB File Comparison Tool. It will not only tell you if the selected files match, but it will also tell you exactly what and where all of the differences are. Use this tool to your advantage. Please note that sometimes it will say, 'No differences to display. The files are not identical, but the only differences are in end-of-line characters.' Do not be alarmed if you see this; you will still receive full credit. Testing Excel Files There is no file comparison tool for Excel files. Instead, you can simply read the Excel files you would like to compare into MATLAB using xlsread and compare the raw cell array outputs using isequal. For example, to compare 'excelFile1.xlsx' and 'excelFile1_soln.xlsx', you could type the following in your test script: [~,~,raw1] = xlsread('excelFile1.xlsx'); [~,~,raw1_soln] = xlsread('excelFile1_soln.xlsx'); check_excelFile1 = isequal(raw11,raw1_soln); Testing Plots Unfortunately, there is no easy way to test plots. By inspection, make sure that your plot has the same title and axis labels as the solution plot. Also make sure that you plotted all the correct points with the correct colors and styles. If your plot should contain more than one curve, it does not matter what order you plot the curves in. Therefore, the overlap of the lines or points on your plot will not affect the "correctness" of your plot. Testing Image Files Comparing two image files is very similar to comparing two Excel files. Instead of comparing the images outside of MATLAB, read the images into MATLAB using imread and compare the resulting image arrays as follows: im1 = imread('imageFile1.png'); im1_soln = imread('imageFile1_soln.png'); check_imageFile1 = isequal(im1,im1_soln);

MATLAB's Secret Trick:

Although arrays are displayed in the command window as two-dimensional matrices of values, MATLAB actually stores the information as a very long column vector. It numbers the elements by reading down the columns one at a time, meaning that arrays can actually be indexed as if they were vectors. This can be useful to remember because it allows you to reshape arrays into vectors very easily.

Basic Arithmetic with Vectors:

Any basic arithmetic involving a vector and a constant changes the value of all elements in the vector. Remember to use the dot (.) with multiplication and division. vec = [1 3 5 7 9]; vec = vec + 2 vec = [3 5 7 9 11] vec = vec.*2 vec = [2 6 10 14 18]

The Assignment Operator:

Any line of code that uses a single equals sign (the assignment operator) is called an assignment statement. Assignment is used primarily to set values to variables and works the same way with any data type. All variable names are case-sensitive, so "a" and "A" can be used as separate variables. Be very careful when naming and accessing variables. Variable names are generally short enough to take up little space but long enough to be easily distinguished. The last thing you want to do is have to fix your code when you can't even figure out what it does. There are three important restrictions on naming variables: 1. A variable's name must begin with an uppercase or lowercase letter. The rest of the name may contain any combination of letters and numbers. 2. A variable's name cannot contain spaces. Obviously, MATLAB would then be unable to distinguish between the variable and the surrounding code. 3. A variable's name cannot contain any special characters except underscores. 4. A variable should never be given the same name as a built-in MATLAB function (min, max, sort,etc.) By these rules, the following would be legal variable names: A , a , a1 , a1a , a_a The following are therefore illegal variable names: 1 , 1a , a: , : , a 1, a? Assignment statements take the form A = B, where "A" is a variable or collection and "B" is an expression that can be immediately evaluated. MATLAB first evaluates "B" then sets "A" equal to it. Assignment statements do NOT establish relationships between variables; they can only be used to set a variable equal to a known value. Once again, changing the values of other variables used in an assignment statement has no effect on the previously outputted variable. If no "A" is inputted, the value of "B" will automatically be stored in MATLAB's temporary variable "ans." "ans" can be accessed at any time and is always placed in the workspace, but each new non-specific assignment statement overwrites whatever is stored in it. It is generally a bad idea to rely on "ans" to store any values you may be using later. By default, the result of an assignment statement is immediately displayed on the command window. However, this can become very irritating when you run long scripts or change large collections of values; the command window will quickly become clogged with useless information that slows the execution of your code. To prevent this, you can "suppress" the output of individual lines of code by ending them with a semicolon. The result of a suppressed output is still stored in the workspace but will not be displayed in the command window. With practice, you will learn to subconsciously suppress all outputs as you write. MATLAB will automatically notify you of unsuppressed outputs by discoloring the equal's sign. Whenever MATLAB encounters spaces, it automatically ignores them. You can therefore add spaces in lines of code to make them more legible.

Concatenating Arrays:

Arrays can be concatenated horizontally or vertically just like vectors. Once again, any command that would produce a non-rectangular array results in an error.

Scripts:

As previously stated, using the command window to solve complex problems is inadvisable because it does not allow you to edit commands you have already run. Consequently, most coding is completed using scripts and the MATLAB function editor. A script is a blank space for inputting blocks of code or functions. When you finish writing a script, you can run the entire thing at once; if an error occurs, you can edit and rerun your code to your heart's content. To open a new script, click the icon in the upper-left corner that looks like a blank sheet of paper or press ctrl+n. When you finish typing out your code, you can run the script by using the green triangle icon or by pressing F5. To save, go to filesave as... or press ctrl+s. Scripts are automatically saved as .m files, the default file type for MATLAB. Always leave the file type as .m if want to receive credit. If MATLAB dislikes something you've written on a script, it will inform you by enclosing a variable inside a discolored box or by underlining part of your code in red. This is a very quick way to spot typos, but don't rely on it for everything. If you plan to test your script frequently, you can dock the script editor inside the command window. This will allow you to view the values of different variables from the workspace without having to minimize the script. To dock the editor, click the small arrow on the left just under the minimize button. The editor can be undocked in the same way by clicking the up-arrow above the minimize button. If you wish to run a script one line at a time rather than all at once, you can enter debug mode by clicking the gray space to the right of the line numbers on the left side of the screen. A red circle will appear on the debugged line. Any number of lines can be debugged. When run, the script will immediately proceed all the way to the first debugged line, then stop. You can then continue running each individual line by pressing the icon with the curvy blue arrow on top of a sheet of paper labeled "step." The "step in" icon allows you debug any internal functions that your script runs. "Continue" allows the code to run normally until it reaches the next debugged line. While in debug mode, you can display the values of any variables by hovering the mouse over them or by simply viewing their progress in the workspace. If you cannot locate the source of an error, debugging your script is an excellent way to track the problem. You can add your own personal comments to any of your code to make it easier for you or other people to understand. Simply precede any comments with a "%" percentage sign. MATLAB completely ignores any green text following a percentage sign when it executes code. To see an example, just look at a hw.m file. To comment a line of code, click on it and press ctrl+r. To uncomment something, press ctrl+t. It is not necessary to actually highlight the code you sigh to comment or uncomment. You can earn extra credit points on your homework assignments by commenting your code.

Switch Statements:

As you can see, this code is much easier to understand than its one-line equivalent. Notice that a common strategy is to arbitrarily initialize the output variable as one possibility and change it depending on the result of the if statements; doing so ensure that your output variable will always be defined, thereby reducing the chance of your code producing an error. Switch Statements: Switch statements are if statements that determine the output based on the value stored in a defined variable. The terminology is slightly different for no necessary reason. "case" now replaces "elseif," and "otherwise" replaces "else." Once again, you can have as many cases as you want. The first line always reads "switch" followed by the name of the variable you are "switching" over.

Which isn't a valid function header

C)

Slicing Arrays:

By slicing arrays in creative ways, you can do all sorts of interesting things such as swapping rows or columns, mirroring, deleting elements, and flipping things upside down. Make sure you know and understand the first two, as they are extremely useful.

Function [brown] = primaries(red, blue, yellow)

Invalid function [brown] = primaries(red, blue, yellow)

Section Six: Conditionals

Conditional statements allow you to determine whether or not to run a certain block of code based on some non-predetermined information. Basically, it's what you wish you could have been using for all the previous homework assignments. Conditionals come in two forms—if and switch statements, but knowing switch statements is more useful than absolutely necessary. If Statements: All if statements are coded in the following basic format: if <logical expression> <code block> end MATLAB will automatically turn the words "if" and "end" blue to designate them as markers pertaining to the code block in between them. MATLAB first evaluates the logical expression to the right of "if." If the statement is true, the code block between "if" and "end" is run as if the conditional statement did not exist. Otherwise, MATLAB jumps from "if" to "end" and ignores the code in between. More complicated conditionals can be created by adding the keywords "elseif" and "else." Elseif statements function like extra if expressions (logical1 was false, but maybe logical2 is true). You can have as many elseif statements as you want but each must contain its own corresponding code block. If you find that multiple statements contain the same code block, you should consider combining them into one logical statement using or (|). An else statement, if you use one, must be the final statement in your overall conditional. It functions like an elseif statement that is automatically evaluated as true. However, an else statement will by definition only be run if all preceding conditional statements are evaluated as false. The order of conditional statements is extremely important because MATLAB will run only the code block corresponding to the FIRST true logical expression. Thus, it will not evaluate any expressions following the first true one and will skip to "end" instead. Finally, EVERY conditional statement (if or switch) must have a corresponding "end." Failing to include enough "end"s will cause an error. MATLAB automatically aligns any "end" you type with the nearest designated conditional statement. If <logical expression1> <code block1> elseif <logical expression2> <code block2> elseif <logical expression3> <code block3> else <code block4> end Nested Conditionals: Believe it or not, you can actually place conditionals INSIDE other conditionals . Sometimes, nesting conditionals is the only way to solve a particular problem. More frequently, however, you can use it to make your code more legible, pretty, and/or cool. Consider the following example: Write a function that takes in a vector and checks to see if all its elements are perfect squares between 6 and 23 that are not divisible by four. The function should output a logical true or false function out= Swordfish(vec) out = false; if all(mod(sqrt(vec),1))==0 if all(vec>6) if all(vec<23) if all(mod(vec,4)~=0) out = true; end end end end end

Data Types

Data Types Intro: Data Types are simply a way to categorize different kinds of data. Many operations in Matlab (and functions that you create!) may only work for certain kinds of data. Data Types mean the same thing as classes. The three types we will be working with are double, char, and logical. Double: Doubles are simply any rational or irrational number, decimal, or integer value. Even pi is considered a type double in Matlab! num1 = 3; num2 = pi; Char: A Char is a character, symbol, or number. A series of chars is called a string. You must use single quotes to represent char values. To put an apostrophe in a string, use two single quotes: Var1 = 'you''re the best around' Var2 = 'nothings ever gonna keep you down!' Var3 = 'd' Computers, unfortunately, do not get the concept of character values, so it actually assigns it a number to keep track of it. This is called an ASCII value. There is a table with the ASCII values and corresponding character values, but you do not need to memorize anything for the exams. A common misconception is that you can simply add a char '5' to a double 5 and get a type double 10. What instead happens is that the char '5' gets converted to its ASCII value 53 and then is added to 5, resulting in type double 58 as the final answer. Matlab won't say that it's wrong, but it may not work as expected. Logicals: Logicals are simple true and false statements, and is often represented as 1 or 0 in Matlab. This data type is the result of using operators like > < >= <= ~= and ==. To assign logical values, you must actually type out true and false; typing 1 or 0 tells matlab that you have a type double 1 or 0. Log = true log2 = 17 > 38; %Log2 will be false because 17 < 38 Log3 = 2100 ~= 66; %Log3 will be true Converting to different data types:

If Line 4 is changed to the following, will the code error? If so, very briefly describe the error. If not, explain why an error does not occur. (5 points) price = price(1:end-1) .* quantity;

Error, dimension mismatch

Writing Functions:

Except for a few lines of code, functions are absolutely identical to scripts. The main difference and, coincidentally, the easiest way to spot a function is the first line, the function header. The header contains all of the basic information concerning the function in the following form: function [output1, output2, output3] = name_of_function (input1, input2) or function output1 = name_of_function (input1) When you type the word "function", MATLAB should recognize it and color it blue. Please remember that spaces do not matter, but commas do. In situations with only one input/output, brackets may be excluded but parentheses are always necessary. A function can have any number of inputs or outputs, even zero. You can use the same variable as both an input and an output as long as you don't need to keep track of its original value. Although you will probably never encounter a function with no inputs, it is quite common for one to have no outputs if its purpose is simply to produce a plot or print something out to the command window. If the function has no outputs, eliminate the equals sign and outputs. Thus: function name_of_function (input1, input2, input3) Most functions are ended with the word "end" to let MATLAB know that the function is complete. Doing so is only completely necessary if you plan on using helper functions, which I will now explain. Although functions are normally called directly from the command window, they can actually call other functions as well, as long as all the files needed are saved in the current directory or added to the path. If you wish to perform a small task multiple times in a single function, you can write a small helper function to assist you. Just place the helper function after the "end" of the main function. Doing so can save space as well as make your code more readable. Here is an example of a helper function. function [out1, out2] = helperExample (a,b,c) out1 = confangleNumber(a); out1 = out1 - confangleNumber( a + (b - a).^3); out2 = confangleNumber(b + 6.*a); end function num = confangleNumber(num) num = abs(ceil(num + (num ./ 2).^2 - round( (num +1)/(num - 1).^2))) end As previously stated, it is not necessary to have any earthly idea about what a function actually does. When you attempt to save your function, MATLAB will automatically suggest the same name as the one given in the function header. Never name a function anything else. Because function are so versatile and easy to grade, this course relies primarily on functionwriting for homework assignments and coding problems on tests. If you can't write a function properly, you're probably going to fail the class.

Function Header Practice: Is the function header valid or not? If not, what needs to be fixed? function myfunc function [out1, out2] = classFinder(in1) Function timeNew = myTime(hourIn minIn) function myFunc(myIn) function [grade1 grade2] = rubric(test1, test2) function [word1] = wordmaker(letter1, letter2) function (score) = sportsCalc[goals]

Function Header Practice Solutions Is the function header valid or not? If not, what needs to be fixed? function myfunc Valid function [out1, out2] = classFinder(in1) Valid Function timeNew = myTime(hourIn minIn) function timeNew = myTime(hourIn, minIn) No capital f, need comma separating inputs function myFunc(myIn) Valid function [grade1 grade2] = rubric(test1, test2) Valid Do not need commas separating outputs function [word1] = wordmaker(letter1, letter2) Valid function (score) = sportsCalc[goals] function [score] = sportsCalc (goals) Brackets for outputs, parentheses for inputs

What is the advantage of using a function instead of a script?

Functions have the advantages of both abstraction and encapsulation while scripts do not. Abstraction: functions can accept different inputs, so the user doesn't need to know the complete details of how they work Encapsulation: functions have their own scope, reducing the clutter of the main workspace.

Explain the meaning of the statement "functions have their own scope."

Functions have variables that can't be accessed from command window or other functions; similarly, they cannot access variables defined elsewhere.

Which of the following are true regarding MATLAB functions? I. When writing a function, you can assign the same variable to the input and output II. Variables defined in the function definition can be called from the command window III. Every function must have an output

I only true

Linspace ():

If you absolutely must include both the start and stop values or are interested in generating a vector of a particular length, you can use the linspace() function. Linspace() takes in a start value, a stop value, and the desired length of the output vector (NOT a step size) and produces a vector of linearly spaced numbers between the start and stop values. The start and stop value are guaranteed to be included, and the space between any two adjacent numbers is always equal. However, you will probably end up with some weird fraction as your step size. If you do not input a desired length, MATLAB will use the default value of 100. linspaceVec = linspace(start, stop, length);

Slicing Strings:

If you can slice vectors, you can slice strings. If you slice beyond the bounds of the original string, MATLAB will fill the intermediate spaces with ascii zeros, not 32s.

HELPFUL HINTS

If you don't know how to use a built-in function, run "help function_name>" into the Command Window. Ex. help mod Comment your code! It makes it easier to understand later. You can include helper functions below in the same script as the same function, rather than having multiple .m files. Make sure you're in the right directory when you try to call your function! "clear" will clear all the stored variables in the Workspace. "clc" will clear the clutter in the Command Window. Preview your submission BEFORE you submit to make sure everything is there and once it's submitted you can download those files again and test them just to make sure it all works the way you intended!

When would you use the colon operator ( : ) instead of linspace()?

If you know the starting and ending values and step, but can have any number of elements, you should use the colon operator. If you know the starting and ending values and the number of points, you should use linspace.

When would you use numerical indexing vs. logical indexing?

Indexing is used when you know the positions of the values you want. Logical indexing is useful when you want values that meet a condition.

Masking

Indexing with logicals is very different from indexing with doubles. The position numbers of values being indexed are represented by the values of double indices and the position numbers of logical indices. Thus, a true at position three in a logical collection will index the element in position three of the collection being indexed. The index may be shorter than the vector being indexed, but not longer. For some reason, logicals can even be used to index other logicals. For some reason, this is known as masking. Masking can be used with even more precision using and (&) and or (|). These can be used to combine collections of logicals to form a final index representing all of them. Just remember these seemingly random rules: 1. An "and" statement is only true if all of the elements are true. 2. An "or" statement is only false if all of the elements are false. When multiple logical collections are combined using & or |, each element in the collections is compared individually to the corresponding elements in the other collections. This strategy can be used to make a single index that matches many different parameters.

Determine whether the following function headers are valid. For EACH header circle whether they are valid or invalid. If the function header is invalid, rewrite the CORRECTED function header using the same function and variable names. (2 points each) function [out1, out2] = doggos(dog1 dog2)

Invalid ____function [out1, out2] = doggos(dog1, dog2)___

Determine whether the following function headers are valid. For EACH header circle whether they are valid or invalid. If the function header is invalid, rewrite the CORRECTED function header using the same function and variable names. (2 points each) Function avocado(in1, in2)

Invalid ____function avocado(in1, in2)_

Suppose you have a 4x4 array of 1s (arr = ones(4)). What would MATLAB do when you try to assign 1 to the position in the 5th row and 5th column (arr(5, 5) = 1)?

It expands the original 4x4 array to a 5x5 array, assigns 1 to arr(5,5), and fills the rest of the new values with 0s.

What is the value of "A" after the code is run

It produces an error

What is the value of newVec after the code is run

It produces an error

Transposing and Rotating Arrays:

Just as the apostrophe turns row vectors into column vectors, it also transposes the rows and columns in arrays. The first column becomes the first row, the second column becomes the second row, etc. This is not to be mistaken with rotating an array clockwise or counterclockwise, requires both transposition and indexing.

%% What is logical indexing?

Just like the name says, logical indexing is using logical values (true/false) in order to index things. Review Logicals We can create logicals in 2 ways: Direct Entry: single Logicals logVec = true; vector of logicals logVec2 = [true false true]; Using Logical Operators > < >= <= == ~ ~= & | single Logicals logVec = 2 == 2;%true %vector of logicals logVec2 = [5 8 2] < 6; %[true false true] %compound logicals %create "true" value where the vector is in between 2 and 6 inclusive vec = [2 9 1 3] %[true false false true] %how would you say this in math (but this isn't math so it's wrong) thing = 2<=vec<=6 %also wrong, because of incorrect syntax thing = 2<=vec & <=6 thing = 2 <= vec & vec <= 6 %vec >= 2 & vec <= 6 % [true true false true] & [true false true true] % [true false false true] %OMG BUT WHAT IF I USE AN OR?! vec = [2 9 1 3] thing = vec >= 2 | vec <= 6 %[true true false true] | [true false true true] %[true true true true] %% Using logical vectors to Index VS. Using double vectors to Index %% Regular Indexing % Given a vector of indicies, the index tells you the position you are % accessing, and the location of the index in the vector of indicies tells you the order in which to access a value. vec = [7 10 11 4]; A = vec([3 1 2]); % A will be [11 7 10] % The index 3 is saying you want to access the 3rd element of vec. Since % this is the first index in the vector of indicies, vec(3) (in this case % 11) will be the first value that is accessed. %% Logical Indexing % Given a vector of logicals, true values indicate that indexing will % occur, and false values indicate that indexing will NOT occur. The % location of the logical in the vector of logicals tells you the relative % index that you are checking. vec2 =[7 10 11 4]; B = vec2([true false true false]); % B will be [7 11] % The first true in the vector says that YES the first value of the vector % will be indexed. The next false says that NO the 2nd value of the vector % will NOT be indexed. etc. %% Examples! %% 1) Create a variable 'A' that has all of the values in 'vec' that are % greater than 8 vec = [5 10 14 20 7] mask = vec > 8 %[false true true true false] A = vec(mask) %[10 14 20] %OMG KANTWON SO HOW IS A LOGICAL DIFFERENT FROM A DOUBLE? vec = [5 10 14 20 7] mask = [0 1 1 1 0] A = vec(mask) %this errors, trying to access at the 0th position %omg but what if.... B = vec([1 1 1 1 1]) %[5 5 5 5 5] B2 = vec([true true true true true]) %[5 10 14 20 7] %% delete all even numbers ------------ vec = [5 10 14 20 7] %maskWRONG = mod(vec,2) %[1 0 0 0 1] mask = mod(vec,2) == 0 %[false true true true false] vec(mask) = [] %% delete all values at odd positions -------- %this is wrong because reading is hard mask = mod(vec,2) == 1 vec(mask) = [] %correct way vec(1:2:end) = [] %---------------------------------------- %% add 1 to all of the a's (lowercase) in str to make . them all b's 'matlab' --> 'mbtlbb' str = 'matlab' mask = str == 'a' str(mask) = char(str(mask) + 1) if we wanted to test to see if you knew what was going on mask = str == 'a' A = str(mask) + 1 B = class(A) %this is class double Count the number of consonants in a string (that doesn't contain punctuation but does contain spaces) str = lower(str) %make everything the same case so we dont have to care later vowelMask = str == 'a' | str == 'e' | str == 'i' | str == 'o' | str == 'u' | str == ' ' consMask = ~vowelMask %could also say: %consMask = str ~= 'a' & str ~= 'e' & str ~= 'i' & str ~= 'o' & str ~= 'u' & str ~= ' ' cons = str(consMask) quantCons = length(cons) %OMG YOU SHOULD NEVER DO THIS BECAUSE IT HURTS KANTWON DEARLY.....but it %works... quantCons = sum(consMask) %this is treating logicals as if they were doubles :( %---------------------------------------- subtract the maximum number in the vector from all values between 5 and 10 (inclusive) vec = [2 8 39 6 9 2] %[2 8 39 6 9 2] --> [2, 8-39, 39, 6-39, 9-39, 2] capitalize a string without using the upper/lower functions str = 'Matlab is bae!!!!' %--> 'MATLAB IS BAE!!!!' mask = str >= 'a' & str <= 'z' str(mask) = char(str(mask) - ('a' - 'A')) %% Delete all special characters, numbers and spaces %% from a string str = 'This Is @ t3st_ sTR!ng!!' %find all letters mask = (str >='a' & str <= 'z') | (str >= 'A' & str <= 'Z') %one way is deleting what we don't want %% Functions find Takes in a logical vector and outputs the indicies of the trues. inds = find([true true false]) inds --> [1 2] vec = [45 3 2 10]; ind = find(vec > 7); %find([true false false true]) --> [1,4] yikes a lot of people will try to use find and random ways! %REMEMBER: find takes in a logical vector, and outputs the POSITIONS of the sevens = find(7) %this is just wrong, find expects a vector of logicals as an input sevens = find(vec == 7) %indicies of the 7's delete all even numbers with find vec = [45 3 2 10]; true values mod(vec,2) --> [1 1 0 0] mod(vec,2) == 0 --> [false false true true] inds = find(mod(vec,2) == 0) vec(inds) = [] without find mask = mod(vec,2) == 0 vec(mask) = [] More Examples! %---------------------------------------------------------- count the number of odd values vec = [1 3 5 21 10 6 8]; mask = mod(vec,2) == 1 quantOdd = length(vec(mask)) can I also do this? NO quantOdd = length(mask) %length([true true true true false false false]) NO quantOdd = length(mask == true) with find quantOdd = length(find(mask)) and if you are a terrible person quantOdd = sum(mask) %---------------------------------------------------------- Find out how many lowercase letters there are in 'str' str = 'Matlab is BAE!'; %---------------------------------------------------------- Remove the spaces from 'str' str = 'Matlab is BAE!';

In MATLAB, you right click a function you wrote that has one input and two outputs and press run. MATLAB throws an error that says "Not enough input arguments." What is the cause of this error?

Running the function through this method calls the function without any inputs.

Char() and Double():

MATLAB contains two built-in functions for converting between different data types. double() changes a character string into a vector of each character's representative ascii code; char() converts a vector of doubles into the characters they represent. You can therefore create a vector of ascii codes and use char() to change it into a string.

Guide for CS 1371 Introduction: The MATLAB Command Interface

MATLAB is basically just a really complicated program that functions as an extremely powerful calculator. As such, it can perform tasks than most calculators cannot, usually in fractions of a second. However, like all computer programs, MATLAB is incredibly stupid and is only ever as useful as your coding capability allows it to be. Never underestimate how irritatingly picky MATLAB can be about small sections of code. The programmers designed some functions to be flexible with input values, but for the most part they didn't bother making it user-friendly. It is not necessary to actually purchase the MATLAB software to complete this course, although it is probably pretty useful; I do not personally own the software. Many, not all, computers in the library do have it. Additionally, some computer geeks have set up a virtual desktop call Citrix that allows you to access your library desktop from your laptop. Unfortunately, the remote desktop generally runs very slowly and is prone to freezing at frequent intervals. It also likes to give you nonsensical login error messages such as "We are sorry. This desktop has been locked, and only you can use it." Whenever you run MATLAB in the library or from your remote desktop, it will tell you it's "initializing" and then proceed to take an unreasonable amount of time to generate a pointless message about customizing shortcuts. I have yet to find a method for preventing this. The MATLAB screen is divided into a number of sections with specific names and titles. These are important to learn because they make up a large part of the terminology used in the course The Command Window: This is the large and obvious block in the middle of your screen labeled "Command Window." It can be used to run individual lines of code or display the progress of a script. Although you'd imagine it must play a very important role in writing codes, it is actually pretty much useless. If you use the command window to run multiple lines of code sequentially and realize you made a mistake somewhere, you have to redo the WHOLE process. The command window will not allow you to edit anything previously entered, and once a variable is overwritten the original value cannot be restored. To enter a command in the command window, simply type it in the little box underneath and pres enter. It is possible to enter multiple lines of code such as loops and conditional statements using shift+enter, but I wouldn't suggest it. You can use the up-arrow to scroll through your most recent commands so you don't have to retype them. If you attempt to do something that MATLAB doesn't like or if there is a typo in your command, MATLAB will make an annoying beeping sound and display a red error message that tells you what the problem is. Learn to fear the error message. At the very bottom-left part of the screen MATLAB will display statuses such as "initializing", "busy", or "ready." If you accidentally run an infinite loop or an extremely long recursive function, you can cancel your last command by pressing ctrl+c. You can enter clc to clear whatever is in the command window at the time The Workspace: This is the little box off to the right labeled "Workspace." Its purpose is to keep track of all the variables and data types you are using. Anytime you save a value to a particular variable or enter any assignment statement, the workspace is automatically updated with the new information. It displays both the name of the variable and its data type (a brief description of data types will be given in section one). If the workspace is becoming too cluttered with useless variables, you can reset it by entering clear in the command window. Command History: This little box keeps track of all the commands you have entered since the beginning of the MATLAB session. If you accidentally clear the command window and workspace but still need the information from them, you can access it from command history. Otherwise, you should just pretend it doesn't exist. The Current Directory: This box is labeled "Current Folder" and is slightly confusing to become accustomed to. MATLAB can only access files and programs that reside in your current directory; if you attempt to run a function or script from a different folder, MATLAB will give you an error message saying that it doesn't exist. It would therefore behoove you to create an organized set of folders and sub-folders for CS 1371, with each homework assignment having its own folder. If you need to access a function from another homework, which will inevitably happen for some of the more difficult problems, simply copy/paste it into the current directory's folder and submit it with your homework problems. To change the current directory, locate the button on the primary toolbar at the top of the screen and to the right of the current folder display. It should look like an ellipsis. Then just navigate to the folder you wish to select and click "OK." I suggest saving your entire CS 1371 folder on your GT Prism drive so you can access it from any computer on campus.

Concatenating Vectors:

MATLAB uses square brackets for just about everything. You can also use them to concatenate vectors, or combine multiple small vectors into one large one. Simply create a vector in the standard manner using vectors as the elements rather than scalar values. To concatenate vectors column-wise, separate the different elements with semicolons.

Scripts vs Functions

Scripts Doesn't need any interaction from the user Never takes in inputs, must specify all values of each variable To use scripts, press the "run" button in the Editor tab, and the results should show up in the Workspace Functions Can take in inputs from the user and gives an output When writing the function, be sure not to use literal values for inputs ex. function out1 = myFunc(12, in2) To "call" a function, in the Command Window , type in variable outputs (if there are any), the function, and the literal input values for the function. The outputs should show up in the Workspace ex. function out1 = myFunc(17, 38)

Calling Functions:

Many people become very confused when they actually attempt to use a function they've written. The easiest and most obvious way to remember the format is that you call your own functions in EXACTLY THE SAME WAY as you would call built-in MATLAB functions. Here is a comparison to the built-in min() function. [minimum, index] = min(vector); [distance, speed] = helperExample(length, width, height); Notice that the input and output variable names of the function call above do not match the names given in the function itself. This is because all variables used in a given function are temporary. When you enter the function call above, MATLAB first opens a new command window for the function helperExample. It then sets the values of "length", "width", and "height" equal to "a", "b", and "c" respectively (always in the same order given in the function header). When MATLAB reaches the end of the helperExample function, it closes the new command window and sets whatever values are stored in "out1" and "out2" equal to "distance" and "speed." However, only those final values will be stored in your original workspace. All other variables are deleted as soon as the function call is complete. Let me reiterate: MATLAB will return only the output variables specified in the function header; all other variables are considered temporary. Additionally, each function call opens its own workspace, which does not have access to the variables in any other workspace. Therefore, any values used within a function must be given as inputs. If you do not specify output variables in your function call, the first results will automatically be stored in "ans." Function calls utilize a simple system known as the stack. Basically, the most recent command is executed first in any given situation. In the helperExample function, each function call to confangleNumber is completed (another command window is opened and closed) before the next line of code is executed. Really, the stack concept is straightforward and easy to remember. That's pretty much it for functions. There's really not that much to know. Examples: Let's just take the scripts from section one and turn them into functions. Remember to make your functions easy to understand by naming variables properly. function [radius, surface_area] = circleStuff (volume) radius = (volume.*3./4./pi).^(1./3); surface_area = 4.*pi.*radius.^2; end function y3 = extrapolate (x1, x2, y1, y2) slope = (y2 - y1) ./ (x2 - x1); y_int = y1 - slope .* x1; y3 = 20 .* slope + y_int; end

The Colon Operator:

Many vectors are too large to create manually. To generate sets of evenly incremented numbers, MATLAB uses a colon operator, not to be confused the semicolon used to suppress outputs. The colon operator takes in a start value, a step value, and a final value; it generates a vector of numbers ranging from the start value to the stop value and incremented by the step size. Expressions using the colon operator do not have to be enclosed in brackets. All vectors are of type double. colonVec = start:step:stop If a step size is not specified, MATLAB will use the default step of one. Step sizes can be positive or negative. Any of the three inputs can be substituted for a variable stored in the current workspace. Putting stupid expressions into the colon operator almost never produces an error. Here is a list of references for absurd situations. 1. If the step size is equal to zero, regardless of the other two inputs, produces an empty vector. 2. If the start and stop values are equal, returns a vector containing only that number unless the step value is zero. 3. If the start value is less than the stop value but the step size is negative, produces an empty vector. 4. If the start value is greater than the stop value but the step size is positive, produces an empty vector. Although the start value is always included in the resulting vector, the stop value will only be included if it falls within the exact step size of the value before it. Thus, 0:4:7 produces the vector [0 4], which does not include 7. You must always be careful to set the step value properly if you want the stop value to be included

Strings

NEW DATA TYPE ALERT!!!!! char (great debate over how to pronounce it....) We denote chars with single quotes ex: letter = 'a'; How does MATLAB see chars? Computers are run off of binary numbers (ones and zeros). So therefore, in memory you can't really store an actual symbol or letter. Instead, everything has to be converted into a number which then can ultimately be converted into binary. So, to Matlab, all chars are actually just numbers. The conversion is through what we call ASCII Values. ASCII --> American Standard Code for Information Interchange By looking up the ASCII table, we can see that when we type something like a lowercase 'a', to the computer this is actually the value 97. What is a String? A string is A VECTOR OF CHARs. Everything we talked about with vectors is applicable here. Creating Strings Direct Entry word1 = ['h','e','l','l','o'] word1b = 'hello'; strNum = '1'; word2 = 'bye'; Concatenation Concatenate strings together and append new stuff to the end Concatenation with strings is the same as it was with concatenation of doubles; just use square brackets %Jaskaran %https://www.instagram.com/jk_brar/ problematic1 = 'plot twist; shes the only girl I pulled this weekend'; problematic2 = 'idc who yall are i could probably pull'; bigProblem = [problematic1 ' ' problematic2 ' #fullerLifeWithChrist']; bigProblem2 = 'problematic1 problematic2 #fullerLifeWithChrist' Casting % "Casting" is just a term that means changing a value from one data type another. char (changes ASCII value into character symbol) let = char(65); %produces A double (changes character symbol into ASCII value) ascii = double('H');% produces 72 ('H' ascii value); num2str (changes a number (double) into a char version of that number) num = 123; %length is 1 str = num2str(123) ; %'123' length is 3 str2num (changes a char version of a number into a double version) str2 = '1234'; %length 4 num2 = str2num('1234'); %num2 is 1234 length 1 Question: Note: the ASCII value for 'A' is 65 thing1 = char(65); %'A' length 1 thing2 = num2str(65); %'65' length 2 log = thing1 == thing2 %'A' == '65' [false false] Math and Strings Anytime you do math to a string, you get back an double (ASCII) value. Often times you'll need to cast it back to a char Produce the next letter from the given variable let = 'b'; nextLet = char(let+1) %'c' Capitalization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% You can either use the upper/lower functions, or do math to the strings. However, be mindful of upperStr = upper(str) lowerStr = lower(str) three ways to capitalize with math capLet = str - 32 capLet2 = char(str - ('a' - 'A')) capLet3 = char(str - ' ') %the ASCII value of space just so happens to be 32 three ways to lowercase with math lowLet = str + 32 lowLet2 = char(str + ('a' - 'A')) lowLet3 = char(str + ' ') Capitalize an entire string problematic2 = 'idc who yall are i could probably pull' using function upperProb = upper(problematic2) using math upperProb2 = char(problematic2 - 32) this is actually not correct because it is subtracting 32 from the spaces too! Also, what if a letter is already capitalized, subtracting 32 from that will cause problems! We will talk about how to deal with this later. It is super important to check your outputs with the 'isequal' function! Indexing Strings All of the indexing we did with vectors of numbers still applies with strings. Minjae https://www.instagram.com/minjae_lee_/ Reverse minjaeCap = 'If you look back you''ll soon be going that way'; revCap = minjaeCap(end:-1:1); strfind function ind = strfind(str,substring) strfind takes in a string and a pattern of characters we often call a "substring". All a substring is is just a part of the overall string. strfind then produces a vector of the starting indicies of where that substring is in the entire string. Examples: ind = strfind('Kantwon','won') % ind --> 5 ('won' starts at the 5th index of 'Kantwon') this is looking for 'won' inside of 'Kantwon'. Seeing it does appear, it produces back the index in the first string where the substring starts. ind = strfind('Yellow Jackets','e') % ind --> [2,12] The character e shows up multiple times in the string. So strfind produces back a vector of all of the indicies. Keep in mind that the *space* does occupy an index! ind = strfind('Georgian Tech','t') % ind --> [] Case matters. And if the substring does not appear in the string, the function outputs an empty vector Indexing multiple spots %%%%%%%%%%%%%%%%%%%%%%%%%%%%% In the "mocking spongebob" type memes, you capitalize different parts of a sentence to make it look strange which then would signify a difference in tone when saying the words. Example: "wow you are so cool" --> "wOw YoU ARe sO cOoL" Although you could easily do this in Matlab by randomly selecting different indicies and capitalizing them, let's make a watered-down/fake version of this. So, let's always just capitalize the first and last letter of each word. Emily https://www.instagram.com/_emilythom/ fakeCap = 'oops i didnt really get the whole red and black memo' spaceInds = strfind(fakeCap,' ') firstLetInds = spaceInds + 1 lastLetInds = spaceInds - 1 fakeCap(firstLetInds) = upper(fakeCap(firstLetInds)) take first lets, capitalie them, put them back fakeCap(lastLetInds) = upper(fakeCap(lastLetInds)) same as above but with last lets need to account for first and last letter of the string fakeCap([1 end]) = upper(fakeCap([1 end])) same as fakeCap(1) = upper(fakeCap(1)) fakeCap(end) = upper(fakeCap(end)) another way of doing all of this by concatenating 1st and last letter inds earlier on fakeCap = 'oops i didnt really get the whole red and black memo' spaceInds = strfind(fakeCap,' ') firstLetInds = [1 spaceInds + 1] lastLetInds = [spaceInds - 1 length(fakeCap)] fakeCap(firstLetInds) = upper(fakeCap(firstLetInds)) take first lets, capitalie them, put them back fakeCap(lastLetInds) = upper(fakeCap(lastLetInds)) same as above but with last lets Capitalize/Lowercase a specific word in a string wrongCap = 'Call me Prince Ali of Ababwa cause I can show you AND four other friends the world' ind = strfind(wrongCap,'AND') wrongCap(ind:ind+2) = lower(wrongCap(ind:ind+2)) %this is hardcoding for "AND" %What if I was given a variable that contained a word that I wanted to lowercase? How could I do this generically? wrongCap = 'Call me Prince Ali of Ababwa cause I can show you AND four other friends the world' word = 'AND' ind = strfind(wrongCap,word) wrongCap(ind:ind+length(word)-1) = lower(wrongCap(ind:ind+length(word)-1)) %what if I wanted to search for a word no matter the case? wrongCap = 'Call me Prince Ali of Ababwa cause I can show you AND four other friends the world' word = 'anD' ind = strfind(upper(wrongCap),upper(word)) %force the sentence and word searching for to be the same case temporarily wrongCap(ind:ind+length(word)-1) = lower(wrongCap(ind:ind+length(word)-1)) More functions %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %sprintf with sprintf i can use %s (strings),%d (doubles),%f(doubles and you can control decimal points) to create spots to fill in later str = sprintf(formattedStr,var1,var2,.....) %strtok Strtok stands for string tokenization. Tokenizing something just means separating it into pieces. Strtok has 2 inputs, the first is the string you want to split, and the second is the character(s) that you want to split it by (we call these characters delimeters). If you don't include a second input, it assumes "space" is your delimeter. At a basic level, strtok starts from the left side of the string and continues searching for a character that matches one of the inputted delimeters. When it finds one, everything before the delimeter is placed in the output, and the delimeter and everything after it are placed in the second output. Example: str = 'hey there pal' [word,rest] = strtok(str,' ') %Want to separate based on a space. It finds the first one at the 4th position %word --> 'hey' %rest --> ' there pal' (the beginning of rest is a space!) Often times you might want to split a string multiple times. You can do this by calling strtok multiple times, but by changing the input to be the 2nd output of what the previous strtok produced. This works because strtok has the property of ignoring all leading delimeters. This means that if you string starts with any delimeters, it essentially deletes and ignores them until it finds something that isn't a delimeter. Example str = 'hey there pal' [word,rest] = strtok(str) %without the second input it assumes space as the delimeter [word2,rest2] = strtok(rest) when the input is now ' there pal', this starts with a space. Since it is a leading delimeter, it ignores it and continues searching for something that isn't one of the delimeters. Once it finds, one, it then uses that to separate the string. word2 --> 'there' (no space at the start) rest2 --> ' pal' (space at the start) In each of the examples above, there has only been 1 delimeter (a space). However, you can put in a string as the second input that representes a list of delimeters. Example: str = 'hey there pal' [word,rest] = strtok(str,'hey') This is NOT separating by the entire word 'hey' instead it is separating by an 'h' or 'e' or 'y'. The notion of ignoring leading delimeters still remains. %word --> ' t' ('h', 'e', 'y' were all leading delimeters so there were ignored) rest --> 'here pal' (it found the 'h' so therefore it split based on that) %Dylan %https://www.instagram.com/_dylan__robinson_/ sort function suppose the string 'names' and 'ages' contain data about people. Each index corresponds to a certain person, meaning the first spot in both vectors corresponds to person 1. Sort the names in descending order, then rearrange the ages to have them align with the newly sorted name. names = 'HCD'; ages = [19 18 17]; [sortedNames inds] = sort(names) sortedNames --> 'CDH' inds = [2 3 1] sortedAges = ages(inds); %sortedAges --> [18 17 19] %% Tips for Homework 3 %calcGravity This is a problem of mathematical manipulation of vectors. Refer to examples done in the vector notes formatBookTitle Elements of this problem are similar to the word replacement we did in the strfind examples above. Think about how to apply what we did with Emily's caption to this problem. Also, sometimes "hardcoding" is fine if certain aspects are guaranteed in the problem %%repWord Elements of this problem are similar to the word replacement we did in the strfind examples above. Think of how to apply what we did to Andy's caption to this problem. %%wordLen strtok helps with this problem. Refer to the notes above and also what was gone over in recitation. Just using strfind alone will be problematic, because what if the words are separated by more than one space? %%dataMixer The second output of sort is helpful. There are notes on this concept in the vector notes and also in the notes above. Perhaps you might want to create a larger vector then fill it in to create the desired output? Example tracing and coding can be found in the class notebook. The link is in the class dropbox folder.

Consider the following function that takes in a 1XN vector of doubles and answer the questions below. 1 function average = findAverage(vec) 2 sumOfVec = sum(vec); 3 average = sumOfVec./5 4 end Will the function above find the average of the vector for every vector input? Explain your answer (3 points).

No, because not all vectors are of length 5 and this only accounts for vectors of length 5. This is an example of hardcoding

Suppose we have: vec = [2 3 4 5]; and we wish to extract the values 2 and 5 into vector vec1 using logical indexing. We ran: vec1 = vec([1 0 0 1]); What do I get and why?

The code will produce an error because numerical indexing is interpreted to be positions. Using a 0 to index is invalid because there is no zero-th index in MATLAB.

Section Three: Vectors

So far, we have only considered situations that involve working with single values. However, we may wish to operate on large sets of numbers at the same time. In these situations, we utilize vectors, large collections of scalar quantities. As a matter of fact, even single numbers in MATLAB are interpreted as vectors of length one. Vectors are easy to work with and easy to understand. Creating Vectors: To create a vector, simply enclose a list of numbers or variables separated by spaces or commas in straight brackets. Vectors can be of any length, even one or zero. Vectors of length zero, or empty vectors, are usually used to initialize variables that will be filled later. If you want to create a new variable of a non-predetermined length, first initialize it as an empty vector. You can also create column vectors in much the same way. Simply separate all elements with semicolons to indicate that they should be placed on top of each other. MATLAB indexes and slices column vectors in the same way. To convert row vectors from row to column or column to row, transpose them by following them with an apostrophe. The transpose function is not limited to transposing vectors; it actually swaps the rows and columns of any one or two-dimensional collection. vec = [1 2 3 4 5]; vec2 = [6, 7, 8, 9]; emptyVec = []; columnVec = [1; 2; 3; 4; 5]

Logical Indexing:

So far, we have only dealt with data of type double, representing real, measurable numerical values. However, another data type frequently used in MATLAB is type logical. Logical data can only take two forms: true or false. In most cases, the number one represents true, while the number zero indicates false; however, MATLAB actually interprets anything not equal to zero as true, including negative numbers and strings. When using any of the expressions below, keep in mind that the two objects you wish to compare must be dimensionally IDENTICAL. Attempting to compare two vectors of unequal length will produce an error. A logical expression will generate a collection of logical indicating where the statement is true and where it is false (one for true and zero for false). Logical expressions generally involve comparisons and can take numerous forms: ==, equal to >, greater than <, less than >=, greater than or equal to <=, less than or equal to ~=, not equal to The tilde (~) is always used to refer to the word "not." When preceding a logical collection, it changes every true to false and every false to true. Nifty!

Function Header Practice Questions Identify which of the following function headers are valid and which are invalid. If they are valid, explain why. 1. function out = myFunc(in) 2. Function [out1, out2] = myFunc(in1, in2) 3. function = myFunc(in) 4. function [] = myFunc() 5. function myFunc 6. function [out1 out2] = myFunc(in1,in2) 7. function [out] = myFunc(12, in) 8. function out = in 9. function out1, out2 = myFunc(in) 10. function[out1 out2] = myFunc(in1 in2 in3 in4)

Solutions 1. function out = myFunc(in) 2. Function [out1, out2] = myFunc(in1, in2) The word 'function' must be all lowercase 3. function = myFunc(in) There are no outputs so you don't need an assignment operator 4. function [] = myFunc() 5. function myFunc 6. function [out1 out2] = myFunc(in1,in2) 7. function [out] = myFunc(12, in) 12 is a literal value and those cannot be in a function header 8. function out = in 9. function out1, out2 = myFunc(in) Since there are multiple outputs, there needs to be brackets around the outputs 10. function[out1 out2] = myFunc(in1 in2 in3 in4) Commas must separate input variables

Sprintf():

Sprintf(): The sprintf() function allows you to create strings containing variables. Consider the following situation: You need to create a string stating how old someone is, but the person's name and age are stored in variables in your workspace. You can either concatenate the string manually or use the sprintf() function. sprintf() takes in a string containing variable markers followed by the parameters you wish to use. The number of inputs will always be equal to one plus the number of variables in the output string. Variable markers are placed using a percent (%) sign followed by a letter designating the type of variable (double or string, usually). Type %d for a double variable and %s for a string. Remember to list the variable names in the same order you used them; you can use the same variable multiple times in the formatted string, but you still have to list it once for each time it is used.

Logical Indexing with Strings:

Strings can be used in logical expressions much like vectors. The only difference is that you can now make comparisons between characters and doubles. Remember that comparing vectors of different lengths produces an error. It is impossible with strings of unlike lengths as well; there's a special function for that. Logical expressions are very useful for determining capital and lowercase letters and for differentiating between letters and symbols. Once again, you can locate elements that fulfill multiple logical conditions using and (&) or or(|).

Using the Dot with Basic Arithmetic:

The MATLAB notation to add, subtract, multiply, divide, or raise to a power is exactly what you would expect (+, -, *, /, ^). However, MATLAB must have a way of distinguishing between regular arithmetic and special matrix operations. For instance, you can either multiply each element in one matrix by the corresponding element in another or actually perform matrix multiplication using linear algebra. Note: MATLAB uses decimals instead of fractions whenever it encounters a non-integer. To differentiate between the two, MATLAB utilizes a dot (.) system with the symbols *, /, and ^. To perform element by element multiplication, division, or exponentiation, simply add a single period before the arithmetic symbol (.*, ./, or .^). Linear algebra functions are performed whenever the dot is absent and will cause errors if the dimensions of the matrices do not match properly. Note that the dot has no effect on scalar values (5*5 is the same as 5.*5).

Built-In MATLAB Functions:

The designers of MATLAB included hundreds of built-in functions to assist users in writing code. These functions allow you to perform otherwise complex tasks in a single line of code. To call a function, type its name followed by any inputs in parentheses, separated by commas. I will list any useful functions as well as brief descriptions of them in each section of this guide. If you wish to perform a relatively common task and are wondering whether MATLAB has a built-in function, it probably does. Go to Help function browser (shift+F1) and search for the name of the function you are looking for. Function names are generally incredibly obvious, exactly what you would expect them to be. Function names are also case-sensitive. sin() Calculates the sine cos() Calculates the cosine sqrt() Calculate the square root abs() Calculates the absolute value exp() Calculate e^x The primary drawback of scripts is their lack of variability; to run a script with different starting values, you must manually change each of the predetermined variables. Additionally, many problems require running the same block of code many times. Using functions allows you to complete such tasks in a more concise, easily understandable, format. A function is simply a script with variable inputs and outputs. You call the function with whatever inputs you wish to use, it does something, and it returns the final result to whatever called it. Once you have written a function, you don't even have to know exactly what it does—just what it takes in and what it regurgitates.

Indexing Arrays:

The items in arrays are organized based on their location as determined by rows and columns. Both rows and columns begin at one and increase as you move down and to the right, respectively. Elements are indexed by their row numbers followed by their column numbers, with a comma in between. To index all rows or all columns, replace the row or column numbers in the index with a colon symbol. You can also use the keyword "end" to access the final element in a particular row or column, or both if it makes you happy.

Lower() and Upper():

The lower() and upper() functions take in a string and convert all letters to lowercase or uppercase letters, respectively. Because they ignore special characters in strings, they are generally very useful.

Strcmp() and Strcmpi():

The strcmp() function allows you to compare strings of unequal length. This is important because attempting to use logical expressions to do so produces an error. Strcmp() outputs a logical 1 or 0 representing whether the two input strings are exactly equivalent. Strcmp() is case-sensitive. There is another built-in function, strcmpi(), that performs the same function while ignoring case Strcmp() and strcmpi() can also be used to compare a string with a cell array of strings, in which case they output a vector of logicals.

Strtok():

The strtok() function is used to split (tokenize) an input string into two parts based on the location of a specific character called the delimiter. Basically, you choose what character to search for (the delimiter) and MATLAB will divide the input string into two output strings according to the following rules: 1. MATLAB locates the first non-delimiter character and deletes all delimiters preceding it. 2. MATLAB locates the next delimiter after the character in (1). The first output is every character from the remaining string up to the character before the delimiter. The first output can NEVER contain the delimiter. 3. The second output is everything else, including the delimiter found in (2). 4. If the input is an empty string, both outputs will be empty strings. 5. If the string does not contain any delimiters, the first output is the entire string, and the second output is an empty string. 6. If the string contains only the delimiter, both outputs will be empty strings. Strtok() is one of the most important functions to know for MATLAB. It is used heavily in both string manipulation and file input/output.

Slicing Vectors:

The word "slicing" seems to be standard terminology for this course even though it makes no sense to me. Slicing involves replacing some of the elements in one vector with some of the elements in another vector. The most important thing to remember when slicing is to be careful about what you choose to overwrite. To delete elements from a vector, set them equal to empty brackets. Here are the basic forms of slicing: 1. A(index) = B(index) This is the most common form. MATLAB first evaluates B(index), then replaces A(index) with it. The rest of "A" remains unchanged. Produces an error if B(index) and A(index) are not the same length. 2. A(index) = B Replaces the elements in A(index) with whatever is stored in B. Once again, A(index) and B must have identical lengths. 3. A = B(index) This is the mistake many students make when slicing. This overwrites the variable A and sets it equal to B(index). All elements in A are replaced, including the ones outside the range of B, so the lengths can be unequal without producing an error. 4. A(index) = [] Setting anything equal to empty brackets deletes it. This can be used to shorten the length of A or delete all of the elements entirely, leaving A as an empty vector. Contrary to indexing, you can slice elements that are out of bounds of the original vector. If you assign a value to an element that did not originally exist, MATLAB will extend the vector by filling all intermediate positions with zeros. To slice outside the bounds of a vector of unknown length, use addition or multiplication with "end."

Reshape()

This function allows you to change the number of rows and columns in an array without altering its overall size. MATLAB fills the spaces in the new array in the same order as the original, namely reading down the columns one at a time. Thus arr(4) will be equal to new_arr(4). You probably won't be using reshape() more than once or twice.

Indexing Vectors:

To return a particular range of values from a given vector, you can index into it using parentheses. The item in parentheses, or the range you wish to return from the vector, can be either a double or collection of doubles (another vector) representing the positions in the original vector that you wish to return. By using another vector as the index range, you can return the elements in any order or even the same element multiple times. The length of the vector returned will always be equal to the length of the index. Because any index that returns multiple values is by definition a vector, indices easily be generated using the colon operator. Doing so allows you to perform many nifty indexing tricks such as reversing a vector or returning only even-numbered positions. If you wish to index up to the last element in a vector, use the keyword "end." Because MATLAB interprets "end" as a number equal to the length of the vector, you can use subtraction or division to index positions based on the end value. Any attempt to index with a number less than one, a fraction, or a number greater than the length of the vector you're indexing into will produce an error. You will probably lose a majority of the points on homework assignments from the message "Error: Index exceeds matrix dimensions."

What is encapsulation?

Variables defined in the function are known only to the function.

Section Five: Strings

Vectors and arrays are only useful for organizing sets of doubles and logicals. Now, we will be dealing with a new data type called char (short for character). Using characters allows you to set variables and outputs equal to meaningful words and phrases rather than just numbers. A string is a vector of numbers that represent the characters and symbols on your keyboard. MATLAB identifies these number-character combinations based on a predetermined set of conversions called an Ascii Table. The columns labeled "Dec" contain the ascii codes for the corresponding red characters in the columns labeled "Char." For example, the ascii code for a capital Z is 90. Note that the code for a lowercase letter is exactly 32 plus its uppercase equivalent. The ascii code for a space is 32. The most important thing to remember about strings is that they function exactly like vectors in most scenarios. To better understand the functionality of strings, we'll be looking at a lot of examples. Creating Strings: Strings are created by enclosing letters, numbers, and symbols in single quotations marks (''). Unlike with creating vectors, you needn't separate the elements with spaces or commas (remember that spaces and commas now count as elements). You can also create empty strings that function just like empty vectors. If you have a string saved as a variable in your workspace, it will have a cute little 'ab' symbol next to it. The class() of a string is 'char.' In fact, the class() function always returns an answer of type char

Functions

What is a computer program? A computer program is a series of instructions in order to accomplish a desired task. The process in which a task is completed in called an algorithm. This is nothing new to you. Humans develop and execute algorithms all of the time. If I asked you to make a bowl of cereal the order of your steps might be 1) get a bowl 2) get cereal 3) get milk 4) get spoon 5) pour cereal into bowl 6) pour milk into bowl However, these instructions are at a very high level. Each of the steps actually has many substeps that you need to complete, but often it is useful to use abstract (which is just another name for high level) steps to plan out an algorithm. When you are writing a computer program, you can't just leave instructions at an abstract level. You have to tell the computer exactly what you want to do at all steps. This is when you must start thinking about how to break down your thought process into more detailed and specific steps. Building Blocks of Computer Program Instructions Variables 11:25 A variable is an entity that saves values during the execution of program. A variable's value can change throughout the program. Variable names can NOT have special characters (except underscore) and MUST start with a letter. Valid variable names: kantwon, matlab_is_bae, wowz3rz93 Invalid variable names: k@ntwon, matlab-is-bae, 93wowz3rz Data types There are multiple data types you will learn. For now, all you have to know is: double: numbers logical: true or false Assignment Operator the assignment operator is the = symbol. Is is NOT the same thing as "equals". The assignment operator executes the right hand side first and then assigns the value to the left hand side. example: luc = 18; JacK = true; sawyer = 20; luc = luc + 1; value of luc is now 19 not 18, it has been overwritten JacK = luc; JacK is now 19 Mathematical Operators These are similar to what you've probably used in math addition: + subtraction: - multiplication: .* division: ./ exponentiation: .^ NOT USING THE . BEFORE *,/,AND ^ IN THE FUTURE WILL CAUSE WEIRD THINGS TO HAPPEN. THEREFORE, GET IN THE HABIT OF ALWAYS USING IT NOW. WE WILL EXPLAIN LATER WHAT IT DOES WITHOUT IT. after these lines of code are run, what are the values of the variables: uno = 1 dos = 4 tres = 6 num = 3 num2 = 7 uno = 1; 1 dos = 2; 2 tres = uno + dos; %3 dos = 4; 4 num = tres; 3 num2 = tres + dos; 7 tres = tres + tres; 6 Logical Operators Logical operators produce logical values. The ones you need to know are: logical and: & logical or: | (this is the symbol you get when you shift click the backslash button) logical equal: == greater than or equal to: >= less than or equal to: <= greater than: > less than: < logical not equal: ~= logical not: ~ REFER TO logicalTable.png FOR A TABLE THAT SHOWS HOW THE AND AND OR OPERATORS WORK log1 = 1 == 2 %false What is a script A script is just a collection of instructions that perform the same exact operations every single time it is run. The term "running a script" means telling matlab to execute all of the lines of code in the script. This can be done by typing the name of the name of the script into your command window. Let's create an example script called my_quad that performs the quadractic equation fo r given values. look at script1.m look at script2.m for an improvement What is a function? A function is a collection of instructions where given a certain set of inputs produces a certain set of outputs. This is nothing new. You've seen functions in math. For instance let's say I had a math function that was defined as: z(x,y) = x + y - 2*y. The function z takes in 2 inputs (x and y) and does some computations in order to produce a certain output. If my inputs were x = 2 and y = 4 asking for z(2,4) would produce the answer 2 + 4 - 2*4 which is -2 Why do we LOVE functions? Functions allow you to have lines of code that can always be executed but for inputs that can change. You don't have to go into the function and change any lines of code to get another output. All you have to do is change the inputs. There are two fundamental principles of functions: 1) Abstraction functions allow you to name a series of steps by name. You are taking detailed steps and "abstracting" them to a higher level representation which makes understanding them a lot easier. For instance, instead of telling you to do all of the 6 individual steps to make a bowl of certain, I can just say "make a bowl of cereal" and all of the steps are "abstracted" into that statement. 2) Encapsulation The power of computer programming is being able to have many seperate functions that don't necessarily interfere with one another. Functions are black boxes that take inputs and produce outputs. Another function can't change the commands or lines of code in another function. All it can do is affect the inputs. We call this idea of every function having all of its bits and pieces contained within itself as "encapsulation". The commands are "encapsulated" within the function. Function headers 11:17 In order to define a function, we have to tell matlab a couple of things: 1) It is a function (not a script) 2) What do you want the function to output (if anything) 3) Whats the name of the function 4) What do you want the function to have as inputs (if anything) These are the four parts of funciton headers. 2) and 4) are optional. Lets go into the rules of each part. 1) Dictating it is a funciton first you have to use the word "function" to dictate that a it is a function. It must be all lowercase and should turn blue. 2) Outputs: no outputs: don't put anything here. OR you could explicitly say you have no outputs by writing [] = 1 output: place the variable name of the output and then the assignment operator. ex: myOutput = You can also put square brackets around the output variable but it not mandatory ex: [myOutput] = multiple outputs: place the variable names inside of square brackets then the assignment operator. ex: [myOutput1 output2] = THE BRACKETS ARE MANDATORY including commas between outputs is OPTIONAL ex: [myOutput1, output2] = 3) Name of the function: write the name of the function. function names follow the same rules as varible names. 4) Inputs: no inputs: you can either put nothing, or explicitly say you have no input by writing () 1 input: place the variable name of your input inside of parentheses. The parentheses are MANDATORY ex: (in1) multiple inputs: place the variable names of your inputs inside of parentheses and separate them by commas. the parentheses and the commas are MANDATORY. ex: (in1, blah) The inputs and outputs dictated in the function header are known as FORMAL PARAMETERS So lets put it all together! Function header examples 11:25 1) A function called "boo" with 2 inputs, 2 outputs function [out1,out2] = boo(in1,in2) %valid function [out1 out2] = boo(in1,in2) %valid, comma in outputs arent mandatory function [out1 out2] = boo(in1 in2) %invalid, comma in inputs needed 2) A function called hola no inputs 1 output function [out1] = hola() valid function out1 = hola() valid, dont need brackets on output function out1 = hola valid, don't need to specify no inputs Is this a valid function header? 11:30 1) function in = blah(out) Valid, just bad practice with naming variables 2) Function out = hello(howdy) invalid, capital F 3) function [out1, out2] = randomThing(in1 in2) not valid, no comma in inputs 4) function out = myFunc(30) no valid, invalid variable name for inputs 5) function out valid, this is a function with no inputs and no outputs Running functions 11:35 You can run a function by typing into the command window the name of the function, parentheses, and then the inputs. If you want the function to a certain variable, you would assign this to said variable. example:root = sqrt(2341); newNum = round(73.7); when you have a function that has multiple outputs, you have to place outputs in square brackets. If you only put one, then you will only get back the first output. [maxxNum,position] = max(3) maxxNum --> 3 (the maximum number is the value 3) position --> 1 (it is a list of 1 number so it is in the 1st spot) When running a function, the inputs are known as ACTUAL PEREMETERS running a function is very similar to writing a function header except you dont include the word "function". However, when running a function, you DON'T need to use the same variable names that were used in the function header. We will talk about this later if you want to learn more about a built-in function you can access the documentation of the function by typing either: help nameOfFunction (this will print all of the documentation into your command window) or doc nameOfFunction (this will open up a completely new window with the documentation Steps for completing a drill problem on the homework 11:40 %-------------------------------------------------------------------------% >>Step 1: Solve the problem as a human %Make sure you know how to solve the problem yourself...as a human. It would be impossible for you to explain to someone (or in our case something) else how to do a problem if you yourself don't know how to do it! Therefore, pretend you are asked to do the problem yourself as a human with the given instructions and input data. On paper, go through the steps of actually solving the problem! %-------------------------------------------------------------------------% >>Step 2: Break down your human thoughts into steps After you are sure you know how to solve the problem yourself, start breaking down your process into smaller steps. This is going to be tricky at first because humans naturally combine a lot of things together and you may not actually know all of the steps you're doing or WHY you are actually doing them! But with practice, you will be able take your complex thought process and break it down into small manageable steps. In order to do this step, physically write out a SHORT description or blurb about what you are trying to accomplish. %-------------------------------------------------------------------------% >>Step 3: Translate your steps from human thoughts to Matlab Given that you now have a roadmap of how you want to complete the problem, step by step, translate each of the steps from "human-language" to Matlab. In order to do this step, you will have to start to learn the connections between your own thinking and how to model that in Matlab. This requires that you not only fully understand syntax and how to physically write code, but you must UNDERSTAND the underlying principles of Matlab operations. You only learn this through practice! Also, when hitting this step, multiple things may happen. A) You have no clue how to translate your step from human-language to Matlab if this is the case, this can be because of either lack of knowledge, or it's impossible to too complex to translate. If it is a lack of knowledge, this is when you need to either review lecture code, or get help. But many times, you won't know if it is a lack of knowledge or just too complex, and this is why it is important to ask for help when you're confused and to specifically ask WHY something works or WHY something doesn't work. If you are thinking of the problem in an unneccessarily complex way, then you may have to return to Step 1 or 2 and rethink how you can do the problem. This forces you to have to be able to thinking through a problem in MANY different ways. Over time, you will begin to learn more efficient ways of translating your human thinking to Matlab.B) You can easily translate the step %-------------------------------------------------------------------------% >>Step 4: Check for syntax errors Ideally, all of these steps have been done on paper and not in Matlab. So therefore, you should type what your wrote down on paper directly into Matlab and see if you have any syntax errors. This will allow you to star to see early on what type of things you get wrong when you don't have Matlab underlining syntax errors! %-------------------------------------------------------------------------% %>> Step 5: Test your code Without Matlab, you should be able to go through your code BY HAND and trace it with a given input. You can also use Matlab to check to see if your outputs. If your code works, awesome. If not, return back to Step 1 or 2 and figure out what isn't working and WHY it isn't working. %-------------------------------------------------------------------------% %VERY IMPORTANT! Throughout every step of the process, you should ALWAYS be asking yourself questions about generalizability and assumptions you're making. For instance, if you determine you should do a certain step, ask yourself: "Does this step (or series of steps) ALWAYS work?" "In which cases DOESN'T it work?" "What am I assuming about the data that I have at this point?" "Are these assumptions valid for the types of inputs my function can have?" Throughout the process, you should also be testing your code in small chunks. It might not seem like a big deal now, but when you start writing functions that are 50+ lines of code, it makes no sense to wait to test your code when youre done writing the whole thing. That will just make your life harder in trying to figure out what is right and what is wrong! Functions that may be helpful in HW01 round %how do you round to a different decimal? ceil floor abs cos sin cosd sind mod(in1,in2) Writing your own function 11:45 Write a function called myQuad that takes in an A, B, and C value and outputs the positive and negative roots. Function Scope Every function has its own memory and realm that is lives in that is different and unique. Tracing functions. Tracing is just a term that means reading a function line-by-line and determining what each line does and the overall function output. The steps for tracing a function are: 1) translate the actual parameters into the formal parameters of the function. 2) Execute all of the lines of code in the function 3) translate the formal outputs to the actual outputs of whatever called the function Example 1: 11:55 Given the following lines of code to be run into the command window, what will be the values of out1, out2, and output1 in the command window workspace. A = 2; B = 3; [out1, out2] = mysteryFunction(A,B); Let's briefly introduct a new one: char We denote chars with single quotes ex: letter = 'a'; How does MATLAB see chars? Computers are run off of binary numbers (ones and zeros). So therefore, in memory you can't really store an actual symbol or letter. Instead, everything has to be converted into a number which then can ultimately be converted into binary. So, to Matlab, all chars are actually just numbers. The conversion is through what we call ASCII Values. ASCII --> American Standard Code for Information Interchange By looking up the ASCII table, we can see that when we type something like a lowercase 'a', to the computer this is actually the value 97. Casting Now that we have 3 different data types, sometimes we might want to convert one type to another. This is called casting. Converting to logical logical function logical(1) --> true logical(0) --> false logical(5) --> true %anything other than 0 is true logical('a') --> true Converting to char char function (only works for double --> char. NOT logical --> char) looks up the value on the ASCII table char(65) --> 'A' char(49) -->'1' Converting to double double function double('K') --> 75 %this is the ASCII value of the char 'K' doing math to a logical or a char by default changes it into a double 'a' + 1 --> 98 true + true + true --> 3 %ouch Changing case of chars Often time you might have a char and want to change it to lowercase or uppercase. Looking at the ASCII table, we can see that lowercase 'a' has a value of 97, while capital 'A' has a value of 65. We can learn two things %from this: % 1) lowercase letters have higher ascii values than capital letter % 2) the difference between a lowercase letter and its corresponding % capital letter is 32. %Using both of these notions, suppose we have a varible 'var' that %contained a lowercase letter and we wanted to capitalize it. %One way of doing that to do math to the actual char: bigLet = char('a' - 32) bigLet = char('a' - ('a' - 'A')) %Another way is to just use the upper/lower function bigLet = upper('a')

Explain what is stored in the variable x after the following line of code is run: x = '3' + 3;

When adding together char data and double data, MATLAB converts everything to type double. The ASCII value for character '3' is 51, so x = 51 + 3 = 54.

Explain what is stored in the variable x after the following line of code is run: x = '3' + 3; You do not need to give an exact answer, just a description.

When adding together char data and double data, MATLAB converts everything to type double. The ASCII value for character '3' is 51, so x = 51 + 3 = 54.

Section Four: Arrays

While vectors are merely one-dimensional collections of data stored as rows or columns, arrays are two-dimensional collections stored as grids containing both rows and columns. They operate in exactly the same way as vectors except for a few minor differences. Although arrays are supposed to be different from matrices, they're actually not. Arrays can contain doubles, logicals, and various other data types. While MATLAB is capable of storing data in more dimensions than are readily understandable, this course never involves data collections of more than two dimensions, excluding images. Creating Arrays: Arrays are created using square brackets in much the same way as vectors. Simply enter the individual rows of the collection separated by semicolons. Yes, the semicolon also has many diverse uses. Arrays must always be rectangular; if at any point MATLAB attempts to create an array that is not rectangular, it will produce an error.

What is the difference between X * Y and X .* Y? What size arrays are valid for each operation?

X.*Y denotes element-by-element multiplication, while X*Y denotes matrix multiplication. For X.*Y, the arrays must be the same size or one must be a scalar. For X*Y, the arrays must meet the rules for matrix multiplication.

If Line 2 is changed to the following: mask1 = animals >= 'a' | animals <= 'z' | animals == ' '; Will mask1 change? If so, describe how it changes. (6 points)

Yes, the mask will change. Changing the & to an | means that every value in the mask will be true, as every single possible character is greater than/equal to 'a' OR less than/equal to z.

Indexing Strings:

You can index the elements in a string the same way you would with a vector. Just keep in mind that MATLAB now interprets EVERYTHING in the string as a separate element, including spaces and commas. Indexing strings returns the actual characters, not doubles.

Basic Arithmetic with Strings:

You can use basic arithmetic to change characters in strings to other characters. From our previous example, we know that adding 32 to a string of uppercase letters will convert them to lowercase. Just remember the golden rule of strings: whenever you add or subtract elements in strings, MATLAB always changes them back to doubles. You will therefore have to use char() to keep your original string format.

You have two vectors: vec1 and vec2 ​ . ● Sort the first one, and then sort the second one by the same positions you did as when you sorted the first one. ● Replace every 3rd index in the vec1 with the corresponding index of vec2 Given a sentence, stored in sent, and two words separated by a space, stored in words, output the number of times that that the more common word appears, regardless of case. (The word can appear inside of another word.) ex. sent = 'I love matlab, MATlab is the bEST!' words = 'Matlab best' → 2 Given a sentence, stored in sent , and a number, stored in num , shift the letters in the sentence by the value stored in num. ex. sent = 'gh' , num = 1 → 'hi' sent = 'lzskza' , num = 1 → 'matlab'

You have two vectors: vec1 and vec2 ​ ● Sort the first one, and then sort the second one by the same positions you did as when you sorted the first one. ● Replace every 3rd index in the new vec1 with the corresponding index of the new vec2 [vec1, idx] = sort(vec1) vec2 = vec2(idx) vec1(1:3:end) = vec2(1:3:end) Given a sentence, stored in sent , and two words separated by a space, stored in words, output the number of times that that the more common word appears, regardless of case. The word can appear inside of another word. ex. sent = 'I love matlab, MATlab is the bEST!' words = 'Matlab best' → 2 words = lower(words) [word1, rest] = strtok(words) [word2, ~] = strtok(rest) sent = lower(sent) idx1 = strfind(sent, word1) idx2 = strfind(sent, word2) vec = [length(idx1) length(idx2)] out = max(vec) Given a sentence, stored in ​ sent , and a number, stored in num , shift the letters in the sentence by the value stored in num. ex. sent = 'gh' , num = 1 → 'hi' sent = 'lzskza' , num = 1 → 'matlab' sent = double(sent) + num - 'a' sent = mod(sent, 26) sent = char(sent + 'a')

Concatenating Strings:

You only need to worry about concatenating strings horizontally. Technically, they can be concatenated vertically to make freaky string arrays, but doing so is virtually useless. Keep in mind that strings are concatenated just like vectors, so MATLAB will not add spaces to separate words. You can also concatenate strings with doubles since they're virtually the same thing. MATLAB always retains the string format after concatenation.

The following code is written in MATLAB: vec = 1:3:7 A = [vec vec(end:-1:1)] B = [2 3 5] C = sum(B) B = B(end:-1:1) D = vec == 7 vec(1,3) = 0 E = vec

[1, 4, 7, 7, 4, 1] A is vec which is [1 4 7], and then vec backwards, and thus [1 4 7 7 4 1] [5, 3, 2] B is originally [2 3 5], but then is reversed, so [5 3 2] 10 C is the sum of B, which is 2 + 3 + 5 = 10 [false, false, true] D is a logical vector of where vec is equal to 7, which is [false, false, true] [1, 4, 0] Setting the 3rd value in vec to 0, gives [1, 4, 0]

What is the value of "vec" after the lines of code are run?

[5,2,3,2,1]

What is the value of log after the function is run?

[false, false]

1 function [cost,time] = phonePlan(calls, texts) 2 temp = calls + texts; 3 cost = temp .* 2; 4 time = calculate(calls); 5 cost = cost + time; 6 end 7 8 function [out] = calculate(calls) 9 time = calls .* 3; 10 out = time + 1; 11 end The following code is run in the Command Window: >> textsSent = 2; >> [wasted, cost] = phonePlan(3,textsSent);

a. totalVec = zeros(1, length(vec1).*3); totalVec(1:3:end) = vec1; totalVec(2:3:end) = vec2; totalVec(3:3:end) = vec3; [ ~ , smallest] = min(totalVec); b. mask = mod(vec, 2) == 0; evenCount = sum(mask); vec(1:end/2) = vec(1:end/2) - evenCount; vec(end/2+1:end) = vec(end:-1:end/2+1); newVec = vec; c. The code will NOT error. num => 4 Q4: function [newArr, check] = partyMonster(arr, str) mask = arr < 0; arr(mask) = arr(mask) .* -1; [~,ind] = sort(arr(:,end),'descend'); newArr = arr(ind, :); newArr = [newArr ; max(newArr)]; [~, rest] = strtok(str); [~, rest] = strtok(rest); num = strtok(rest); mask = newArr(:,1) > str2num(num); check = all(mask) end Other ways to find number: -Mask to find spaces, index between 1 after second space and 1 before third space -Mask between ASCII values 48 and 57, apply to string to get out number

Logical Stuff:

all(x) - true if everything in x is true any(x) - true if anything in x is true not(x) - same as ~x or(x,y) - same as x | y and(x,y) - same as x & y

Given a character vector called letters and a char array arr, replace the underscores ('_') in arr with the characters stored in letters. Assign the resulting sentence in a variable sent as a vector, as shown below in the example case. Note that once the array becomes a vector, the first row comes first, then the second, and so on. It is guaranteed that the number of underscores in arr is equivalent to the length of letters. (9 points) Note that in the example case, there is a space after the 'w' in the first row. HINT: You may want to turn the array into a vector before replacing the underscores. Example: >> letters = 'hr?' >> arr = ['Hi, _ow '; 'a_e you_'] >> sent = ['Hi, how are you?']

arr = arr' arr = arr( : ) sent = arr' mask = sent == '_' sent(mask) = letters

Make a checkerboard array of 1's and 0's with 1 being at position (1,1). This is a n x n square array. Example of a 4x4 output: [1, 0, 1, 0; ... 0, 1, 0, 1; ... 1, 0, 1, 0; ... 0, 1, 0, 1]

arr = ones(n); arr([2:2:end],[1:2:end]) = 0; arr([1:2:end],[2:2:end]) = 0;

Generate a 3x4 array of random numbers between -5 and 5. Store it in a variable called arr.

arr = rand(3,4)*10 - 5;

(i) Given an array arr, change all values in the even rows of the array with the maximum value of the array. (ii) Add one to all values in the odd columns.

arr(2:2:end, :) = max(max(arr)); arr(:, 1:2:end) = arr(:, 1:2:end) + 1;

(i) Given an array arr, change all values in the even rows of the array with the maximum value of the array.(ii) Add one to all values in the odd columns.

arr(2:2:end, :) = max(max(arr)); arr(:, 1:2:end) = arr(:, 1:2:end) + 1;

fclose(fh)

closes a text file

sum(x) -

computes the sum of x

cat(dimension, arr1, arr2, ...)

concatenates arrays in a particular dimension

cell2mat(arr)

converts a cell array of doubles to an array of doubles

num2str(x)

converts a number to the string representing that number

str2num(x)

converts a string representing a number to the number itself

num2cell(arr)

converts an array of doubles to a cell array

cell(r,c)

creates a cell array of empty cells with dimensions r*c

struct(field,value,field,value,...)

creates a structure/structure array

subplot(m,n,num)

creates an MxN subplot and specifies which subplot to work on

function: newtonsLaw

function [acc, force] = newtonsLaw(vInitial, vFinal, deltaTime, mass) vChange = vFinal - vInitial; acc = vChange ./ deltaTime; force = mass .* acc; acc = round(acc, 2); force = round(force, 2); end

[tk,rest] = strtok(str,dlm)

discards leading delimiters and returns the next token and the remains of the string

imshow(arr)

displays an image given a uint8 image array

cumsum(x,y)

estimates the area under a curve using rectangles

trapz(x,y)

estimates the area under a curve using trapezoidal method

cumtrapz(x,y)

estimates the cumulative area under a curve using trapezoidal method

polyval(cofs,x)

evaluates a polynomial regression

Given a 1xN double vector stored in nums, find the number of even integers in the vector and store it in evens. Then delete all values of nums that are not divisible by the value stored in evens. (8 points) Example: >> nums = [4 12 10 15 8 20] >> evens = 5 >> nums = [10 15 20]

evens = sum(mod(nums, 2) == 0) mask = mod(nums, evens) == 0 nums(~mask) = []

fliplr(x) -

flips x left-to-right

Which of the following illustrates a correct MATLAB function header?

function (a,b) = myFunc[b] Smooth parentheses are used for inputs while square ones are for outputs. function a = myFunc(b c) Commas are necessary when listing mulitple inputs. a = myFunc(b, c) The word function must always be the first thing in a function header. function = myFunc(b, c) When there are no outputs, you may either have []= or neither (ie, function myFunc function myFunc() Correct! A function may have no inputs or outputs and this syntax is correct.

function: youngsModulus

function E = youngsModulus(F, A, deltaL, L0) %calculate stress stress = F ./ A; %calculate strain strain = deltaL ./ L0; %calculate Young's modulus and round to 2 places E = round(stress./strain, 2); end

function: calcGravity

function Fg = calcGravity(mass1, mass2, distance) G = 6.67e-11; top = mass1 .* mass2 .* G; bottom = distance .^ 2; Fg = round(top ./ bottom, 4); end

function: arrhenius

function T = arrhenius(k, k0, Ea) R = 8.314; % ln(k / k0) = -Ea / (R * T) % R * T = -Ea / ln(k/k0) T = (-Ea ./ R) ./ log(k ./ k0); % ln is log() in matlab T = round(T,2); end

Which function header correctly defines a function called myFunc which has two inputs and three outputs?

function [a, b] = myFunc(one, two, three) This has three inputs and two outputs. function [a, b, c] = myFunc(one, two) Correct! function [a, b, c] = myFunc(one two) Commas are necessary when listing mulitple inputs. function [a b c] = myFunc(one two) Commas are necessary when listing mulitple inputs. function (a, b, c) = myFunc[one, two] Smooth parentheses are used for inputs while square ones are for outputs.

Which of the following illustrates the minimal requirements for a MATLAB function header?

function [a] = myFunc(a, b) function myFunc (correct) function myFunc(a) function function c = myFunc

polyint(p)

returns the integral for the coefficients stored in p

function: formatbooktitle

function [formatted] = formatBookTitle(unformatted) %% Lowercase all letters first. unformatted = lower(unformatted); %% Capitalize the first letter of each word. % Find the indices of spaces. spaces = strfind(unformatted, ' '); % Shift the indices over by 1 to the right. firstLetters = spaces + 1; % Replace the lowercase first letters with the uppercase ones. unformatted(firstLetters) = upper(unformatted(firstLetters)); %% Lowercase 'and', 'of', 'the'. unformatted = strrep(unformatted, 'And', 'and'); unformatted = strrep(unformatted, 'Of', 'of'); unformatted = strrep(unformatted, 'The', 'the'); %% Capitalize the first letter of the title. unformatted(1) = upper(unformatted(1)); %% Output the result. formatted = unformatted; end

function: citizenwatch

function [hrHand, minHand] = citizenWatch(hrHand, minHand, deltaMins) deltaHrs = floor((deltaMins + minHand)/60); minHand = mod(minHand + deltaMins, 60); hrHand = mod(hrHand + deltaHrs, 12); end

function: EOS

function [maxP, log] = EOS(V, n, T) %constants Vm = n/V; R = 0.0821; a = 0.242; b = 0.02651; %equations of state idealP = n*R*T/V; vdwP = R*T/(Vm-b)-a/Vm^2; %find max and output logical log = idealP > vdwP; maxP = max(idealP, vdwP); maxP = round(maxP); end

function: repword

function [modified] = repWord(original, wordFind, wordReplace) %find the starting and ending indices of the word to replace startInd = strfind(original, wordFind); endInd = startInd + length(wordFind) - 1; %create the final output through concatentation modified = [original(1:startInd-1) wordReplace original(endInd+1:end)]; end

Function: pizzaParty

function [num, left] = pizzaParty(people, pizzas) slices = pizzas*8; num = floor(slices/people); left = mod(slices, people); end

Problem 4. Write the following function. Do NOT hardcode! (30 points)

function [out1 out2] = matrixManipulator(arr, vec) [~, ind] = sort(arr(1,:)); arr = arr(:, ind); arr(arr < 0) = arr(arr < 0) .* -1; [m] = max(arr, [], 2); delete = m < 4; arr(delete, : ) = []; arr(end, :) = vec; right = arr(: , end./2 +1 : end); out2 = sum(sum(right)); out1 = arr; end

Rules for Function Headers

function [out] = sampleFunc(in1, in2) In lowercase, type out function. It should turn blue function Now put the output variables. If there is only one output, you don't need any brackets ( Although it's still ok to use brackets on a single output!). If you have multiple output variables, you must use brackets around them and separate them with either a space or with commas function [out] Now put the assignment operator "=". function [out] = Now put the output variables. If there is only one output, you don't need any brackets ( Although it's still ok to use brackets on a single output! ). If you have multiple output variables, you must use brackets around them and separate them with either a space or with commas function [out] Now put the assignment operator "=". function [out] = Now put in the function name. function [out] = sampleFunc Immediately after the function name put in a parenthesis and enter in you input variables, separated with commas ( Note: input variables require commas, but output variables can use either spaces or commas ) function [out] = sampleFunc(in1, in2) %Hooray We're done! (items %put after the percent sign, colored green, is a comment) A function can have no inputs nor outputs. The only component absolutely required in a function header is the function name. Literal values can't be used in a function header.Now put in the function name. function [out] = sampleFunc Immediately after the function name put in a parenthesis and enter in you input variables, separated with commas ( Note: input variables require commas, but output variables can use either spaces or commas ) function [out] = sampleFunc(in1, in2) %Hooray We're done! (items %put after the percent sign, colored green, is a comment) A function can have no inputs nor outputs. The only component absolutely required in a function header is the function name. Literal values can't be used in a function header.

function: quadForm

function [x1, x2] = quadForm_soln(a, b, c) determinant = sqrt(b.^2 - 4.*a.*c); %computing the determinant of the quadratic formula x1 = (-b + determinant) ./ (2.*a); %giving the larger output x2 = (-b - determinant) ./ (2.*a); %giving the smaller output x1 = round(x1, 2); x2 = round(x2, 2); %rounding outputs to two decimal places end

function: NerstPotential

function eqPot = nernstPotential_soln(Z, cOut, cIn) eqPot = 61./ Z .* log10(cOut ./ cIn); eqPot = floor(eqPot); end

function: alphaIndex

function ndx = alphaIndex(character) ndx = upper(character) - ('A' - 1); end

● You can use the ~ operator to negate a logical. Function Name: forecast Inputs: 1. (char) A character vector of the current forecast 2. (char) The word to be replaced 3. (char) The new word to put into the forecast Outputs: 1. (char) The updated forecast description Banned Functions: strrep() Background: You have recently started your internship as a weather engineer at the local news station. Unhappy with how the current forecasts are described as 'gloomy' and 'cold', you decide to use MATLAB to replace these words with some happier words! Function Description: Write a function that takes an input string, a word to be replaced, and the word to replace it with. Your function should output the original string, but with the one word corrected to the new word. Example: [out] = forecast('This snowy weather is so cold.','cold','awesome') out => 'This snowy weather is so awesome.' Notes: ● The word to be replaced is guaranteed to appear in the forecast string, but only once. Hints: ● strfind() will be useful in solving this problem.

function newStr = forecast_soln(str, wordRep, newWord) startPos = strfind(str,wordRep); len = length(wordRep); endPos = startPos + len - 1; newStr = [str(1:startPos-1), newWord, str(endPos+1:end)]; end

Write a function named priceCalculator that takes in the price of a meal and a tip percentage as an integer between 0 and 100 (pretend there's no tax). Output the final price rounded to the nearest cent.

function out = priceCalculator(price, tipPercentage) tipPercentage = tipPercentage/100; newPrice = price .* (1 + tipPercentage); out = round(newPrice.*100)/100; end

Which of the following function headers correctly defines a function with no inputs and no outputs?

function out1 = myFunc(in1) Has 1 input and 1 output function myFunc Correct! function out1 = myFunc() Has one output function myFunc(in1) Has one input

function: wordLen

function vec = wordLen(str) [w1, rest] = strtok(str); [w2, rest] = strtok(rest); w3 = strtok(rest); vec = [length(w1), length(w2), length(w3)]; end

Function Name: cupcakeContestInputs: 1. (double) a vector of critics' scores for a cupcake flavor 2. (double) cutoff scoreOutputs:1. (double) vector of revised cupcake scores 2. (double) overall cupcake scoreFunction Description:Write a function called cupcakeContest that takes in a vector of scores for a cupcake flavor and returns the overall score of the flavor, as well as a vector of revised cupcake scores. To adjust for disgusting cupcakes, remove any cupcake score less than or equal to the second input. Return a vector of revised cupcake scores ordered from greatest to least. Take the average of the revised scores to return the overall cupcake score.

function[newScores, overall] = cupcakeContest(scores,cutoff) newScores = scores(scores>cutoff); overall = mean(newScores); newScores = sort(newScores,'descend'); end

rand(x,y) -

generates an array of dimension x,y of linearly spaced random numbers between 0 and 1

title(str)

give the current plot a title

[value, index] = max(x) -

returns the largest element along with its position number

xlabel(str)

labels the x-axis of the current plot

ylabel(str)

labels the y-axis of the current plot

Given an array called math, replace all the instances of the number 3 in the array with the number 10. Store the answer back in math.

math(math == 3) = 10;

You are given a MxN data matrix called data. Take the average along each row and append it as the last column in data. Take the sum across columns and append it to the bottom of the matrix.

mn = mean(data'); data = [data mn']; sm = sum(data); data = [data; sm];

open(filename, permission) -

opens a .txt file with specified permissions ('w', 'r', or 'a') and returns the file handle of the new file

max(x) -

returns the largest element in the collection

fgetl(fh), fgets(fh)

returns the next line down of the file specified by fh

length(vec)

returns the number of elements in a vector, or the longest dimension of an array

[r,c,l] = size(arr)

returns the number of rows, columns, and layers of an array

function [out1, out2] = zoo(animals, price, quantity) 2 mask1 = (animals >= 'a' & animals <= 'z') | animals == ' '; 3 animals(~mask1) = []; 4 price = price .* quantity; 5 [num, idx] = max(price); 6 out1 = animals(1:idx+2); 7 mask2 = price <= num./2; 8 mask3 = quantity < num./2; 9 vec = mask2 & mask3; 10 out2 = price(vec); 11 end Assuming the above function is defined in the current directory and the following code is written and run in the Command Window, answer the questions that follow: >> animals = 'ap2e. do2g _c4at..' >> price = [2 1 3] >> quantity = [4 3 1] >> [out1, out2] = zoo(animals, price, quantity) a. What is the value stored in out1 and out2 in the Command Window? (4 points each)

out1: 'ape' out2: [3 3]

If Line 10 is changed to the following line, the function will not error. Will the value of out2 change? Explain why it does or does not change, and if it does, provide the new value of out2. (5 points) out2 = price(find(vec));

out2 will not change. The find() function returns all non-zero values, so when used on a logical vector, returns the numerical indices of all true values. The resulting vector of class double will index price at the exact same locations as the logical vector, so the output does not change.

rmfield(struct,field)

outputs a structure with the field removed

setfield(struct,field,value)

outputs a structure with the given value assigned to a field

ischar, isnumeric, iscell, islogical, isnan, isempty (var)

outputs true or false, depending on whether or not the variable has a particular data type or value

spline(x,y,xguess)

performs a piecewise cubic interpolation

interp1(x,y,xguess,method1,method2)

performs linear interpolation or extrapolation

plot(x,y,style,...)

plots x and y data with a given style

fprintf(fh,line) -

prints a line to the text file specified by fh getfield

[num txt raw] = xlsread(filename)

reads in an Excel file (.xls or .xlsx) and stores numerical data in num, character data in txt, and all data in raw

strrep(str,pattern,replacement)

replaces every instance of a pattern in a string with another string

ones(r,c)

returns a r*c array all with value 1

rand(r,c)

returns a r*c array containing random numbers between 0 and 1

zeros(r,c)

returns a r*c array of zeros

imresize(arr,scale)

returns a resized image array based on scale given

imresize(arr, dimensions)

returns a resized image array with the given input dimensions

sprintf(fmt,var1,...)

returns a string containing the format string after replacing the %<> entries with each input parameter.

char(vec)

returns a string whose ASCII values are given by vec

imread(filename)

returns a uint8 image array

imread(filename)-

returns a uint8 image array

linspace(start, stop, num)

returns a vector of length num containing evenly spaced values

fieldnames(sa)

returns all of the fields in a structure array as a column cell array

imrotate(img, deg)

returns an image array rotated by deg counterclockwise

reshape(arr,r,c)

returns an r*c array formed by reshaping an array which has r*c total elements

mean(vec)

returns the average of the values in a vector

polyfit(x,y,order)

returns the coefficients of a polynomial regression in descending order

class(vec)

returns the data type of a variable

polyder(p)

returns the derivative for the coefficients stored in p

diff(vec)

returns the differences between adjacent entries in a vector

Given the 1xN double vector vec, find the sum of the first half of vec and the product of the second half. Find the greater of the two values and store it in great. If the sum is greater than or equal to the product, output true. If the product is greater than the sum, output false. Store the logical in out. Note: vec is guaranteed to be an even length. (8 points) Example: >> vec = [5 8 6 4 1 3] >> great = 19 >> out = true

s = sum(vec(1:end ./2)) p = prod(vec(end./2 +1 : end)) great = max([s p]) out = s >= p

sort(x) -

sorts the elements in ascending order

x' -

transposes x (row vector column vector)

Determine whether the following function headers are valid. For EACH header circle whether they are valid or invalid. If the function header is invalid, rewrite the CORRECTED function header using the same function and variable names. (2 points each) function [ ] = fluffers()

valid

function SchoolSpirit(oldGold, white)

valid

function pink = mixColors(white, red)

valid

If there was a vector vec = [1 2 3 4 5] and I entered vec(3:1) into the workspace, what would be the result? Why?

vec(3:1) --> [] 3:1 is equivalent to 3:1:1, which creates a vector beginning at 3 and going to 1 in steps of 1. It is impossible to do this in steps of 1, so this vector is an empty vector []. If you index a vector with an empty vector, then you get an empty vector.

In the variable soupGoup, you are given a sentence with words separated by spaces. Replace all the instances of 'soup' with 'goup', even if it is part of another word. Store this new string in the variable soupGouped. Banned functions: strrep() Test case: soupGoup = 'Howdy I really love soup, in the winter, summer and soupspring. Soup is the best.' soupGouped --> 'Howdy I really love goup, in the winter, summer and goupspring. Soup is the best.'

where = strfind(soupGoup, 'soup') soupGoup(where) = 'g' This works because strfind() searches the first input string for occurrences of the second input string, and outputs a vector of doubles. Each number in that vector is the index of the starting index of 'soup' in soupGoup. This means it's the index of the 's'. We can use the wherevector to numerically index and replace the proper 's's with 'g'.

xlswrite(filename,data)

writes a new Excel file (.xls or .xlsx) with an input cell array

imwrite(img,filename)

writes a uint8 image array to the filename

What is the difference between the operations done by the lines of code x = 3 and x == 3?

x = 3 assigns the value of 3 to x. x == 3 compares x to the number 3.


Set pelajaran terkait

Unit Eight - The Department and Insurance Defined

View Set

Розділ 3. УТВЕРДЖЕННЯ КОМУНІСТИЧНОГО ТОТАЛІТАРНОГО РЕЖИМУ В УКРАЇНІ

View Set

Chief Officer 3rd Ed. Ch.2- Professional Development Pg 32-40

View Set

Exam Review BGSU MGMT 3600 CH 1-6

View Set