SIMPLE INPUT & OUTPUT: Output: Printing to the screen (command window) using the disp() command. If you want to print out the value(s) of a variable to the screen, you simply can type the variable at the command line without using a semicolon to suppress the output. >> x = 5 x = 5 Same thing applies for variables that are character strings. >> z = 'hello' z = hello You can write character and numerical data on the same line, although it won’t print out that way. >> 'The value of x is: ', x ans = The value of x is: x = 5 This doesn’t look very good and is probably not the output we were looking for. We would like to have more control with the output so that we can present data in a clear and meaningful way. Specifically, we would like to get rid of that annoying x =, z =, and ans = after every statement is executed. The disp() command is useful if you want to print something to the screen without fancy formatting. For example, lets define a variable called score, using a semicolon at the end of the line to suppress the output to the command window. When you terminate a line with a semicolon, it prevents any output from being printed to the command window. However, the variable is still defined (stored in memory) so that we can access and use it later.

1

>> score = 90.2; >> disp('Your score is: ') Your score is: >> disp(score) 90.2000 Here, we defined a variable and suppressed the output with a semicolon, but the variable was still stored in memory so that we can use the disp() command to output the value in a more clear way. However, our output is still spread over multiple lines. If you want to print different types of data (e.g., character and floating-point) on the same line using a single disp() command, you must convert the floatingpoint data to a string using the num2str() command. >> score = 90.2; >> disp(['Your test score is: ', num2str(score)]) Your test score is: 90.2 Now the output is clear, neat, and labeled. It is important that appropriately label all output from your code so that the user (anyone who uses your code, which could be you, your boss, a co-worker, the instructor of MAE10, etc.) knows exactly what the value they are seeing represents. In general, this means labeling the output (e.g., saying that it is a test score) and including units whenever applicable (there are no units for a test score). The importance of including units cannot be overemphasized in engineering. Remember, a number missing units can be easily misinterpreted. Notice also the use of brackets [] around everything you want printed to the screen. Here are some important points to remember when using the disp() command: 





The use of brackets is required when the disp() command has more than one argument (i.e., more than one variable, a variable and a character string, etc). This is shown in the example above, where we display the text ‘Your test score is: ’ and the variable score using a single disp() command. If you do not use the brackets when they are required, you will get an error. Using brackets is optional when the disp() command has only one argument (e.g., just one variable, just a character string, etc.). The example at the top of the page shows the disp() command with just one argument at a time. No brackets are used, since they are not required. However, we could still use brackets even if there is only one argument – this would not produce an error. You must use numstr()(on the number) when printing both a number(s) and a character string(s) in a single disp() command. Not doing so will not produce an error, but it will produce unexpected output. This is because floating point data (numbers) must be converted to character strings when printing both data types in a single disp() command. o It is never necessary to use num2str() on a character string. o It is not necessary to use num2str() when printing only numbers in the disp() command (since you are not mixing variable types).

Based on these set of rules you should realize one thing: Technically it is safest to always use brackets in the disp() command if you are in doubt. 2

Input: Getting input from user using the input() function. Sometimes you want a program to read in data provided by the user and then use that data to perform some calculations. For example, the user inputs the number of hours and the program converts that number to minutes and seconds. To read in data from the screen (command window), use the input() function in the following way: variable = input(‘some instructions/prompt for the user’) Note that the prompt that is given to the user in the input() command must be enclosed in single quotes, just like all other character strings in MATLAB. For example, in mfile.m: hours = input('Enter the number of hours: ') % Matlab will wait for a value minutes = hours * 60; seconds = minutes * 60; disp(['This is ' num2str(minutes) ' minutes']) disp(['This is ' num2str(seconds) ' seconds']) At command line, running mfile.m: >> mfile Enter the number of hours: 5

(MATLAB waits here until I type a value and press enter)

hours = 5 This is 300 minutes This is 18000 seconds Inputting character data is a little trickier. If you use the same syntax for inputting character data as you use for inputting numerical data, the user must put single quotes around the text they enter. In mfile.m: name = input('What is your name? '); disp(['You have entered: ', name]) At command line: >> mfile What is your name? 'Peter' You have entered: Peter

(Notice that I had to use single quotes when inputting ‘Peter’)

If you don’t want the user to have to enter character data in single quotes, you can use a slightly different form of the input() command. In mfile.m: % The 's' tells MATLAB that the input is a character string (not a #) 3

name = input('What is your name? ','s'); disp(['You have entered: ' name]) At command line: >> mfile What is your name? Peter You have entered: Peter We will discuss how to enter in multiple pieces of information at once later. To summarize, here are some key points for the input() command:     

Be sure to always have a variable to the left-hand side of the equals sign when using the input command – this is the variable that will hold (save in memory) any value(s) that are input so that you can use them later. Be sure to enclose your prompt for the input command in single quotes (since it is a character string). When inputting numbers, do not include the ‘s’ in the input() command. When inputting character strings, always include the ‘s’ in the input() command. You can prevent any data that is input from being repeated to the user (e.g., re-printed in the command window) by terminating the input command with a semicolon as in the above examples. Once again, using a semicolon only prevents the information from being printed in the command window – the variable is still stored in memory.

While the input() command may seem simple, it is actually very important conceptually. Remember that a computer is just a machine that reads, stores, and manipulates data to provide the desired output. The only way a computer can read data is through some form of input from the user – your computer’s mouse and keyboard are input devices, for example. The mic on your phone is an input device – if you give it a verbal command, it reads this input, manipulates it (e.g., by converting the frequency of your voice into words for a search engine), and provides the desired output (such as the weather in Irvine or directions to your destination). While in MATLAB you will primarily be inputting numbers or character strings, the idea is the same. You provide an input and a set of instructions (your code), and MATLAB provides you with an output (the result of your calculations).

4

ARRAYS: MATLAB is designed for handling matrices (arrays). You can think of arrays as a series of boxes that contain similar items (each element is one box). We use arrays when we want to store a lot of similar data in a single variable. For example, if we want to find the mean and standard deviation of student test scores, we first need to store all the scores in memory. It would be quite lengthy and complicated to make a new variable for each test score. Instead, we can store all of the scores in a single variable – this variable will be an array. Although in theory arrays can have many different dimensions, we usually only deal with 1D arrays (vectors) or 2D arrays (matrices) in MAE10. For 2D arrays, the size of the array is expresses as #ROWS x #COLUMNS. A 1D array is a 2D array with only one row or only one column. 1x6:

3x1:

4x2:

An array is made of elements. A 1x6 array is 1-dimensional and has 6 elements. A 3x1 array is 1-dimensional and has 3 elements. A 4x2 array is 2-dimensional and has 8 elements. Extending this concept into 3+ dimensions, a 4x2x3 array is 3-dimensional and has 24 elements and a 2x10x3x2 array is 4-dimensional and has 120 elements. 5

1D Arrays: First we will discuss 1D arrays since they are simpler to understand than 2D arrays. Every time you create a variable with a single value, you create a 1D array that is 1x1 in size. A 1x1 array is typically referred to as a scalar, meaning that it is just a single value. >> a = 52.4 a = 52.4000 >> whos Name a

Size

Bytes

1x1

8

Class

Attributes

double

The variable a is a 1x1 array. Let’s create a bigger array. You can define arrays by enclosing numbers in brackets. Each individual element in the array is separated by a comma, a space, or both. >> cat = [0.1 , 0.2, 0.4] cat = 0.1000

0.2000

>> dog = [1.1

1.2

0.4000

2.4]

dog = 1.1000

1.2000

>> whos Name

Size

cat dog

1x3 1x3

2.4000 Bytes 24 24

Class

Attributes

double double

We have created two 1x3 arrays that contain double precision data (e.g., floating point numbers). Here are graphical illustrations of the cat and dog arrays. You refer to a particular element in the array by putting the element number in parenthesis following the array name.

6

0.1 0.2

0.4

cat(1)cat(2)cat(3) 1.1 1.2

2.4

dog(1)dog(2)dog(3) >> cat(3) ans = 0.4000 >> dog(1) ans = 1.1000 >> dog(4) Index exceeds matrix dimensions. Notice that we get an error message if we try to access a non-existent array element. You can use elements of an array to do mathematical operations or anything else that you would do with a scalar variable. >> dog(1) + cat(2) ans = 1.3000 >> rat = cat(1)^2 rat = 0.0100 You can change the values stored in an array. In this case you will replace (overwrite) the old value in the position that you give (by the element #) with a new value that you specify (whatever is to the right hand side of the equals sign). >> dog(1) = 5 7

dog = 5.0000

1.2000

2.4000

>> dog(2) = dog(3) dog = 5.0000

2.4000

2.4000

We can add elements to arrays very easily in MATLAB. However, in many other programming languages (such as FORTRAN), this is not allowed – you would need to declare the size of your array ahead of time. >> dog(4) = 10 dog = 5.0000

2.4000

>> whos Name

Size

ans cat dog rat

1x1 1x3 1x4 1x1

2.4000

10.0000

Bytes 8 24 32 8

Class

Attributes

double double double double

The array dog is now a 1x4 array. Entering array values over multiple lines – MATLAB’s line continuation: If you want to define a long 1D array and do not have enough room to easily fit all the value on one line, you can use an ellipsis (…) to continue inputting values on the next line. The ellipsis essentially tells MATLAB to treat the next line as part of the same line that is terminated with an ellipsis. >> turtle = [1 3 5 6 3 5 3.3 ... 55 66 77 888] turtle = Columns 1 through 6 8

1.0000

3.0000

5.0000

6.0000

3.0000

5.0000

Columns 7 through 11 3.3000

55.0000

66.0000

77.0000

888.0000

2D Arrays: 2D arrays are very similar to 1D arrays, except you now need to worry about both rows and columns. You separate rows by using a semicolon (;) or by hitting the return key (starting a new line). >> temp = [2, 4, 5 ; 6, 3, 2] temp = 2 6

4 3

5 2

>> temp2 = [2 4 5 6 3 2]

(when I hit return, no command is executed yet)

temp2 = 2 6

4 3

5 2

(we get the same 2D array using different methods of entering data)

To access elements in a 2D array, we need to specify both a row and column position. For example: >> temp(1,2) ans = 4 >> temp(2,3) ans = 2 >> whos Name

Size

temp

2x3

Bytes

Class

48

double 9

Attributes

temp2

2x3

48

double

Both temp and temp2 are 2x3 arrays. As with 1D arrays, we can manipulate and change specific elements in the 2D arrays (without affecting the other elements). >> temp(1,1) = 300 temp = 300 6

4 3

5 2

>> temp(2,2) = temp(1,1) + 1 temp = 300 6

4 301

5 2

>> a = temp(2,2) + temp(2,3) a = 303

Arithmetic with Arrays: There will be times where you will want to perform an operation on all the elements of an array. For example, multiply all the elements of an array by a constant (a scalar). >> a = [2, 3, 9 ; 4, 4, 7]

(a is a 2x3 array)

a = 2 4

3 4

9 7

>> d = 3 d = 3

10

>> b = d.*a b = 6 12

9 12

27 21

Notice we used the .* operator instead of just the * operator. Adding a period in front of the operator means “apply this operation to every element of the array.” When we only are multiplying, dividing, adding, or subtracting an array by a scalar (1x1 array), the dot operator is not necessary. In fact, using the dot operator with addition or subtraction will produce an error. The dot operator should only be used for multiplication and division. >> b2 = d*a

(We get the same result using .* and * in this case)

b2 = 6 12

9 12

27 21

>> a = a + 1 a = 3 5

4 5

10 8

>> a = a .+ 1 a = a .+ 1 ↑ Error: Unexpected MATLAB operator. >> a = a/10 a = 0.3000 0.5000

0.4000 0.5000

1.0000 0.8000

The real use for the dot operator comes when we are doing multiplication or division between two arrays, where both arrays are larger than 1x1. >> a a = 11

0.3000 0.5000

0.4000 0.5000

1.0000 0.8000

>> b b = 6 12

9 12

27 21

>> c = a*b Error using * Inner matrix dimensions must agree. >> c = a.*b c = 1.8000 6.0000

3.6000 6.0000

27.0000 16.8000

You can see that in the first attempt to create c, we got an error. This is because MATLAB interpreted this as traditional matrix multiplication (as in linear algebra). Using the .* operation tells MATLAB to do element-wise multiplication. That is, multiply every element of a by every corresponding element of b. Note that in this case, a and b must be the same size. Note that the same rules apply if we try to raise the array a to the power of 2: >> a^2 Error using ^ Inputs must be a scalar and a square matrix. To compute elementwise POWER, use POWER (.^) instead. >> a.^2 ans = 0.0900 0.2500

0.1600 0.2500

1.0000 0.6400

This is because MATLAB is trying to multiply the array a by itself (a 2x3 array multiplied by another 2x3 array), which is forbidden by the rules of traditional matrix multiplication. If you want to square

12

each element of the array a, use .^ as we did above. You can see that MATLAB even gave you this as a hint. To summarize some key points for the dot operator: 



Use the dot operator (a period) before multiplication or division between two arrays when you want to apply the operation to every corresponding element of the two arrays. o Do not use the dot operator for addition or subtraction between two arrays. Addition and subtraction automatically operate element-wise between to arrays and between a scalar and an array. Doing so will result in an error as we saw above. o Any two arrays must be the same size in order to perform any element-wise operation between them. The dot operator is never required when doing arithmetic between a scalar and an array. The operation automatically applies the scalar element-wise to every element of the array.

13