Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Getting Started with Matlab: Understanding Variables, Vectors, and Matrices, Study notes of Algebra

An introduction to using Matlab, a programming tool for mathematical computations and data analysis. It covers the basics of creating variables, vectors, and matrices, as well as performing matrix operations such as transposition and summation. The document also includes examples of creating matrices from scratch and importing them from external files.

Typology: Study notes

2021/2022

Uploaded on 09/12/2022

tiuw
tiuw 🇺🇸

4.7

(18)

53 documents

1 / 19

Toggle sidebar

Related documents


Partial preview of the text

Download Getting Started with Matlab: Understanding Variables, Vectors, and Matrices and more Study notes Algebra in PDF only on Docsity! A. Introduction to Matlab Possibly the best way to think of Matlab is as a fancy graphing calculator that can also allows programming. When you start Matlab off of the Start menu, you'll see something like this: • On the right hand side is the main working window (called the "Command Window") that acts kind of like your graphing calculator. • On the upper left hand side, is a window that doubles as your "Current Directory" showing all the files and folders like a Windows folder, and as your project "Workspace", showing all the variables you are currently working with IF you click on the "Workspace" tab at the top. • On the bottom left, you'll see the Command History. Since you haven't done anything yet, yours will probably be empty. After you've played with creating variables and using functions, you'll see that this window shows the history of everything you've done in Matlab in this session. Lab 6 CSE 3, Summer 2009 In this lab we will learn how to use some of the features of Matlab including Variables, Matrices, and Functions. One of the most useful things in Matlab that you will ever use is the "Help" (even though I've used Matlab for years, I use the Help constantly ). If it didn't open up automatically when you started Matlab, you can open it by clicking on the yellow question mark in the toolbar at the top of the main window. You can search on any topic you might want help on (here I've searched on "mean"). In the upper left- hand window, you can see all of Matlab's suggested matches to your query. Below that are documents that describe the topics in more detail. And on the right in the main window, you can see clear information and help about whatever topic you selected. At the bottom of the main window, you will see links to other similar or related functions and topics. You can also click on the "Contents", "Index", or "Demos" tabs in the upper-left hand corner for more info. MyColVector' Will give you: ans = 1 2 3 4 5 6 7 8 9 10 D. Matrices In Matlab, a matrix is a rectangular array of numbers. A spreadsheet in Excel can thought of as a matrix as well. • Special meaning is sometimes attached to 1-by-1 matrices, which are scalars (what we would call numbers), and to matrices with only one row or column, which are vectors. • The operations in Matlab are designed to be as natural as possible. Where other programming languages work with numbers one at a time, Matlab allows you to work with entire matrices quickly and easily. A good example matrix appears in the Renaissance engraving "Melencolia I" by the German artist and amateur mathematician Albrecht Dürer. This image is filled with mathematical symbolism, and if you look carefully, you will see a matrix in the upper right corner. This matrix is known as a magic square and was believed by many in Dürer's time to have genuinely magical properties. It does turn out to have some fascinating characteristics worth exploring. You can enter matrices into MATLAB in several different ways: • Enter an explicit list of elements. • Load matrices from external data files. • Generate matrices using built-in functions. • Create matrices with your own functions in M-files. Step 1: Start by entering Dürer's matrix as a list of its elements. You only have to follow a few basic conventions: • Separate the elements of a row with blanks or commas. • Use a semicolon, ; , to indicate the end of each row. • Surround the entire list of elements with square brackets, []. To enter Dürer's matrix, simply type in the Command Window A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] MATLAB displays the matrix you just entered: A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 Step 2: You are probably already aware that the special properties of a magic square have to do with the various ways of summing its elements. If you take the sum along any row or column, or along either of the two main diagonals, you will always get the same number (like sudoku). Let us verify that using Matlab. The first statement to try is sum(A) MATLAB replies with ans = 34 34 34 34 When you do not specify an output variable, MATLAB uses the variable ans, short for answer, to store the results of a calculation. You have computed a row vector containing the sums of the columns of A. Sure enough, each of the columns has the same sum, the magic sum, 34. How about the row sums? Step 3: MATLAB has a preference for working with the columns of a matrix, so one way to get the row sums is to transpose the matrix, compute the column sums of the transpose, and then transpose the result. For an additional way that avoids the double transpose use the dimension argument for the sum function (sum(A,2)). The transpose operators works on a matrix, just like it works on a vector. It flips a matrix about its main diagonal (you can think of this like taking each row in the vector, and making it into a column or vice versa). 100:-7:50 is 100 93 86 79 72 65 58 51 and 0:pi/4:pi is 0 0.7854 1.5708 2.3562 3.1416 Subscript expressions involving colons refer to portions of a matrix: A(1:k,j) is the first k elements of the jth column of A. So sum(A(1:4,4)) computes the sum of the fourth column. But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword "end" refers to the last row or column. So sum(A(:,end)) computes the sum of the elements in the last column of A: ans = 34 Why is the magic sum for a 4-by-4 square equal to 34? If the integers from 1 to 16 are sorted into four groups with equal sums, that sum must be sum(1:16)/4 which, of course, is ans = 34 Step 3: The Magic function Matlab actually has a built-in function that creates magic squares of almost any size. Not surprisingly, this function is named magic: B = magic(4) B = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 This matrix is almost the same as the one in the Dürer engraving and has all the same "magic" properties; the only difference is that the two middle columns are exchanged. To make this B into Dürer's A, swap the two middle columns: A = B(:,[1 3 2 4]) This says, for each of the rows of matrix B, reorder the elements in the order 1, 3, 2, 4. It produces A = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 Why would Dürer go to the trouble of rearranging the columns when he could have used Matlab ordering? No doubt he wanted to include the date of the engraving, 1514, at the bottom of his magic square. Step 4: Matrix Operations Expressions use roughly familiar arithmetic operators and precedence rules. + Addition - Subtraction .* Multiplication ./ Division ^ Power ' Transpose ( ) Specify evaluation order • Matrix addition/subtraction is fairly intuitive: If add or subtract a scalar to a matrix, that scalar is added/subtracted to every value in that matrix: A+1 ans = 17 4 3 14 6 11 12 9 10 7 8 13 5 16 15 2 Notice that each element in the matrix has increased by 1. Also, because we didn't assign this to a matrix, it is stored in the variable ans. The matrix A is still as it was before - we did not overwrite it. To do that, we would have to assign the operation to A: A = A+1 • Matrix multiplication and division are DIFFERENT from what you are used to!!!!! We are NOT going to go into how matrices are multiplied or divided with other matrices (if you take a Linear Algebra course you will learn all about it). What we are going to do is something called "scalar multiplication", where you can multiply or divide a matrix by a single number. To do this, you use the operators ".*" and "./" and every element in the matrix is then multiplied or dived by the number specified: A.*2 ans = 32 6 4 26 10 20 22 16 18 12 14 24 8 30 28 2 Step 5: Generating Matrices Matlab provides four functions that generate basic matrices. zeros All zeros ones All ones rand Uniformly distributed random elements randn Normally distributed random elements Here are some examples: Z = zeros(2,4) Z = 0 0 0 0 0 0 0 0 F = 5*ones(3,3) F = 5 5 5 5 5 5 5 5 5 N = fix(10*rand(1,10)) (the fix function rounds a number down) N = 9 2 6 4 8 7 4 0 8 4 R = randn(4,4) R = 0.6353 0.0860 -0.3210 -1.2316 -0.6014 -2.0046 1.2366 1.0556 0.5512 -0.4931 -0.6313 -0.1132 -1.0998 0.4620 -2.3252 0.3792 G. Putting it all Together Let's use all of our new-found Matlab skills to replicate some of our findings from the last Lab. Step 1: Open up Buoy100.xlsx from your Lab5 folder. From your "Daily Summary Statistics" tab, select cells B2 through J366 (that should be all of the data for the years 2001-2009 WITHOUT any labels such as the date or the year). Copy them using Ctrl-C. Step 2: Open up Notepad++ and paste the data into a new file. Save the file as TempF.txt Step 3: In Matlab, import the data using the Import Wizard by selecting File => Import Data. Click the Next button and then Finish. (You will see that many cells have the word NaN in them. This stands for "Not A Number" because those cells were empty in Excel.) You should now have a variable in Matlab called TempF. Step 4: Find out how big your matrix is by typing: size(TempF) If you selected the Excel cells I suggested above, your TempF variable should have 365 rows and 9 columns. Step 5: Look at the matrix stored in variable TempF by typing simply: TempF Notice all the NaN values. Step 6: Plot the temperatures by typing: plot(TempF) You can add labels to the axes and a title: xlabel('Day of the Year') ylabel('Degrees Fahrenheit') title('Daily Ocean Temperatures for 2001 through 2009') When you are done, you should have something that looks very familiar: Step 7: Let's create a chart with just the min, max, and mean like we did in Lab5. Create a new variable "minTempF" and set it equal to the minimum of each row. Remember, since we want to take the minimum over the rows rather than the column we either have to use the transpose operator or specify the dimension in our function: minTempF = min(TempF')' or minTempF = min(TempF, [], 2); Create another new variable "maxTempF" and set it equal to the maximum of each row in a similar way. Create another new variable "aveTempF" and set it equal to the mean of each row in a similar way. • Take a look at your values. Why do you have all those NaN's? • Even though Matlab can handle finding the min/max over data with NaN's, it CANNOT find the mean! • One way to handle this is to only take the mean of the data that exists, and make sure not to try and include any of the NaN's • To do this, let's just take the mean of the data for the years 2002 through 2008. Since we're looking at averages, that's going to be close enough. • What columns hold that data? aveTempF = mean(TempF(:,2:8),2) Step 8: Finally, let's make one big matrix with all these statistics in it so we can graph it easily. To do that, we want to concatenate our new vectors into one matrix. TempSummaryF = [minTemp maxTemp aveTemp]; Now we can graph this summary information: plot(TempSummaryF); xlabel('Day of the Year') ylabel('Degrees Fahrenheit') title('Daily Ocean Temperature Summary for 2001 through 2009') To add a legend to your data: • In the plot window, select View => Plot Browser • Double click on one of the colored lines to bring up the Property Editor - Lineseries • Enter the name you want (Minimum, Maximum, Mean) in the "Display Name" field • Right-click on the white-space of the plot itself and choose "Show Legend" • You can now close the Plot Browser and Property Editor
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved