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)

288 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

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.

And you will see this in your command window: MyRowVector =

1 2 3 4 5 6 7 8 9 10

Step 2: To create the same vector as a column vector, simply add semicolons between each element in the list MyColVector = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

And you will see this: MyColVector =

1 2 3 4 5 6 7 8 9

Step 3: You can change a row vector into a column vector by taking its TRANSPOSE. The transpose is a matrix algebra function that turns a row vector into a column vector and vice versa. To transpose a vector, use an apostrophe (') at the end of the vector name.

If you were to type: MyRowVector'

Will get you: ans =

1 2 3 4 5 6 7 8 9

While typing:

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.

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).

So A'

produces ans = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1

and sum(A')'

produces a column vector containing the row sums: ans = 34 34 34 34

The sum of the elements on the main diagonal is obtained with the sum and the diag functions: diag(A)

produces ans = 16 10 7 1

and sum(diag(A))

produces ans = 34

The other diagonal, the so-called antidiagonal, is not so important mathematically, so Matlab does not have a ready-made function for it. But a function originally intended for use in graphics, fliplr, flips a matrix from left to right: sum(diag(fliplr(A))) ans = 34

You have verified that the matrix in Dürer's engraving is indeed a magic square and, in the process, have sampled a few Matlab matrix operations.

is 100 93 86 79 72 65 58 51

and 0:pi/4:pi is 0 0.7854 1.5708 2.3562 3.

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)/

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+ 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+

  • 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).

Step 6: Importing Matrices To import a matrix that you have found or created elsewhere, use the Import Wizard by selecting File => Import Data. This is very similar to importing a text file into Excel.

The data will be given the same name as the file it was saved in. If your file was Population.txt for example, after you import the file into Matlab, you would have a variable called Population that contains all of the numerical data from the text file. Non-numerical data is stored in separate variables.

Step 7: Concatenation Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements.

The pair of square brackets, [], is the concatenation operator.

For an example, start with the 4-by-4 magic square, A, and form B = [A A+32; A+48 A+16]

The result is an 8-by-8 matrix, obtained by joining the four submatrices: B = 16 3 2 13 48 35 34 45 5 10 11 8 37 42 43 40 9 6 7 12 41 38 39 44 4 15 14 1 36 47 46 33 64 51 50 61 32 19 18 29 53 58 59 56 21 26 27 24 57 54 55 60 25 22 23 28 52 63 62 49 20 31 30 17

This matrix is halfway to being another magic square. Its elements are a rearrangement of the integers 1:64. Its column sums are the correct value for an 8-by-8 magic square: sum(B) ans = 260 260 260 260 260 260 260 260

But its row sums, sum(B')', are not all the same. Further manipulation is necessary to make this a valid 8-by-8 magic square.

Step 8: Deleting Rows and Columns You can delete rows and columns from a matrix using just a pair of square brackets. Start with X = A;

Then, to delete the second column of X, use X(:,2) = []

This changes X to X = 16 2 13 5 11 8 9 7 12 4 14 1

If you delete a single element from a matrix, the result is not a matrix anymore. So, expressions like X(1,2) = []

result in an error.

F. Useful Functions

Some useful functions that we're going to be using in Matlab include: sum(A) Returns the sum of the elements in each column of A. Use sum(A,2) to find the sum of the rows of A

min(A) Returns the minimum of the elements in each column of A. Use min(A, [], 2) to find the minimum of the rows of A.

max(A) Returns the maximum of the elements in each column of A. Use max(A, [], 2) to find the maximum of the rows of A.

mean(A) Returns the mean or average of the elements in each column of A. Use mean(A,2) to find the mean of the rows of A

std(A) Returns the standard deviation of the elements in each column of A. Use std(A,2) to find the standard deviation of the rows of A

size(A) Returns the size of the matrix A in rows and columns.

find(A) Returns the indices of the non-zero elements in A

plot(A) Plots the columns of matrix A in a graph. There are many options for graphs in Matlab. Search "plot" in the help for more details.

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

Credits: Much of the content of this lab was borrowed from the Matlab Help pages.