CS 211 Lesson 2
Values, Arrays, and Variables
Quote:
Who you are speaks so loudly, I cannot hear what you are saying. Ralph Waldo Emerson
Lesson Objectives:
Understand MATLAB's primary data structure, the array
Be able to create row vectors, column vectors, and 2-D matrices
Be able to set individual elements of array variables
Be able to display MATLAB variables
Be able to use shortcut expressions and built-in functions to initialize variables
Be able to determine a matrix's length and size
Be able to access individual elements and subarrays of matrices
Know how to access MATLAB's predefined special values
Lesson:
I. MATLAB Concepts
A. MATLAB Arrays
A data structure is an organized way of storing data (a group of values of some data type).
The fundamental data structure in MATLAB is a double array.
By default, a double array has 2 dimensions; it has 1 or more rows and 1 or more columns.
A single location in an array, the intersection of a row and a column, is called an element.
The descriptor double means that each element value is stored as an 8-byte (64-bit) double precision floating-point value. A double precision, floating-point value can have up to 15 significant digits of accuracy with a largest exponent of +308 and a smallest exponent of -308. Numbers larger than 1.7977e+308 (1.7977 x 10308) or numbers smaller than 2.2251e-308 cannot be represented in MATLAB.
MATLAB provides other types of arrays, such as character arrays for "string" data. We will study these other types in BLOCK 5 of this course.
Arrays are sometimes given special names based on their dimensions:
A scalar is a single-element array (1 row and 1 column).
A row vector is a single-row array (1 row and multiple columns).
A column vector is a single-column array (multiple rows and 1 column).
The term matrix generally refers to an array with 2 or more non-singular dimensions (not a vector).
The term array is a general term for all of the above.
A MATLAB array may have as many dimensions and elements as will fit in the computer's memory.
Some of MATLAB's mathematical operations treat scalars differently than vectors and matrices.
There are a variety of ways to create non-scalar arrays:
Arrays may be constructed directly using square brackets [ ]:
MATLAB command Description [1 2 3 4 5] % A row vector with 1 row and 5 columns [1; 2; 3] % A column vector with 3 rows and 1 column [1 2; 3 4]
% A matrix with 2 rows and 2 columns Arrays may be created with built-in functions and modified with mathematical operations:
MATLAB command Description zeros(4) % Creates a 4x4 matrix (4 rows, 4 columns) with each element equal to 0 ones(3,4) % Creates a 3x4 matrix (3 rows, 4 columns) with each element equal to 1 ones(3,4)*2 % Creates a 3x4 matrix (3 rows, 4 columns) with each element equal to 2 rand(4) % Creates a 4x4 matrix (4 rows, 4 columns) with each element equal to a random value in the range [0.0, 1.0)
floor(rand(4)*10) +1 % Creates a 4x4 matrix (4 rows, 4 columns) with each element equal to a random integer value between 1 and 10
ones(2,3,4) % Creates a 2x3x4 matrix (2 rows, 3 columns, 4 slices) with each element equal to 1 magic(4)
% Creates a 4x4 matrix (4 rows, 4 columns) where the sum of all the values in each row, column and diagonal is the same
Vectors may be created using the colon operator (startValue:increment:limitValue)
MATLAB command Description 1:5 % Creates the row vector [1 2 3 4 5] (an increment of 1 is implied) -10:3:10 % Creates the row vector [-10 -7 -4 -1 2 5 8] 10:-3:-10
% Creates the row vector [10 7 4 1 -2 -5 -8] The transpose (') operator swaps an array's row and column values
MATLAB command Description [1 2 3; 4 5 6]' % Creates the 3x2 matrix[1 4; 2 5; 3 6] (1:5)'
% Creates the column vector [1; 2; 3; 4; 5] Arrays may be created by combining one or more of the above methods:
MATLAB command Description [1:3; 4:6] % Creates the 2x3 matrix [1 2 3; 4 5 6] [zeros(3) ones(3)]
% Creates the 3x6 matrix [0 0 0 1 1 1; 0 0 0 1 1 1; 0 0 0 1 1 1] - Arrays are always rectangular -- that is, every row of an array has the same number of columns, and every column of an array has the same number of rows.
B. Array Variables
A variable is a named "value holder."
Programs use variables to temporarily store values in a computer's memory (RAM - Random Access Memory).
You can create, display the value of, change the value of, and destroy variables at MATLAB's command line.
An assignment creates a variable and gives it a value
An assignment has the form: <variable name> = <expression>
An expression is a combination of values, variables, operators, functions, and parentheses that evaluates to an array.
When the assignment executes, the interpreter evaluates the expression and assigns the result to the variable.
Note that the assignment operator (=) does not represent equality as in standard mathematics.
For example, consider the statement Count = Count + 1 which adds 1 to the variable Count
Variable names:
must begin with a letter (a-z, A-Z).
may include only letters (a-z, A-Z), digits (0-9), and the underscore character (_).
MATLAB variable names are case-sensitive (i.e., count and Count are two different variables).
Some examples of creating variables using an assignment follow:
MATLAB command Description Count = 5; % The variable Count now has a scalar value of 5 Matrix = [1 2; 3 4]; % The variable Matrix now contains a 2-row by 2-column array Twos = ones(4)*2; % The variable Twos now contains a 4-row by 4-column array Age = input('Enter your age: '); % The "user" will be prompted to enter a value for Age and the value entered by the user will be placed into the variable.
If an assignment does not end with a semicolon, the result of the assignment is "echoed" to the command window.
If an assignment ends with a semicolon, no output is generated.
Get in the habit of placing semicolons at the end of assignment lines to suppress display of the assigned value by programs.
The value of a variable may be displayed in several ways, the simplest of which are:
MATLAB command Description Count % Use the variable name "all by itself" disp(Count) % Use the display MATLAB function disp()
The value of a variable is changed when it is assigned a new value (which need not be related to the old value). The previous value of the variable is lost forever.
MATLAB command Description Count = 5;
% The variable Count now has a scalar value of 5 Count = [1 2; 3 4]; % The variable Count now contains a 2x2 matrix (the 5 is now gone) Count = 'a string'; % The variable Count now contains a row vector of ASCII characters (the 2x2 array is now gone) The built-in size() function returns a 1x2 vector giving a variable's number of rows and number of columns:
MATLAB command Description Matrix = [1 2 3; 4 5 6];
% Defines a 2x3 matrix X = size(Matrix); % Results in X equal to [2 3]
The built-in length() function returns the number of elements in the largest dimension of a variable. For example:
MATLAB command Description Squadrons = 1:12; % Creates the row vector [1 2 3 4 5 6 7 8 9 10 11 12] length(Squadrons); % Returns 12, because the variable has 12 columns (and only 1 row) length('John Doe'); % Returns 8, because the string contains 8 characters (the space is included) C. Accessing Array Elements
An index (also called a subscript) is a positive integer value used to identify a position within an array.
In MATLAB, the position of the first element (in any dimension) always has an index of 1.
No indices are needed to access the single value of a scalar.
One index is used to identify a single position within a vector (either row or column vector).
MATLAB command Description Evens = 0:2:10; % Creates the row vector [0 2 4 6 8 10] First_even = Evens(1); % First_even now has the value 0 Second_even = Evens(2);
% Second_even now has the value 2 Typically, two indices, row first and column second, are used to identify a single position within a 2-D matrix.
MATLAB command Description Matrix = [1 2 3; 4 5 6; 7 8 9]; % Creates a 3x3 matrix Center_square = Matrix(2,2); % Center_square now has the value 5 Top_right = Matrix(1,3); % Top_right now has the value 3 Bottom_left = Matrix(3,1);
% Bottom_left now has the value 7 In general, n indices are used to access a single element in an n-dimensional matrix.
When a single index is used to access a 2-D matrix element, elements are ordered first by column and then by row. Said another way, arrays are stored in memory in column major order.
MATLAB command Description Matrix = [1 2 3; 4 5 6; 7 8 9]; % Creates a 3x3 matrix Bottom_left = Matrix(3); % Bottom_left now has the value 7 Top_right = Matrix(7);
% Top_right now has the value 3 If you attempt to use an array element that does not exist, a run-time error will be generated.
MATLAB command Description Matrix = rand(3);
x = Matrix(4,5);% Creates a 3x3 matrix
% Generates a run-time error; there is no row 4, column 5 valueIf you attempt to set an array element that does not exist, the array will "grow" to the required size and all additional elements added to the array will be initialized to 0 (except the value being set).
MATLAB command Description Matrix = rand(3);
Matrix(4,5) = 10;% creates a 3x3 matrix
% the matrix now has 4 rows and 5 columnsAny rectangular subarray of an array can be accessed by specifying the desired indexes of the subarray.
MATLAB command Description Vector = [3:9] % Creates the row vector [3 4 5 6 7 8 9] First_four = Vector(1:4); % First_four now has the value [3 4 5 6] Middle_three = Vector([3 4 5]); % Middle_three now has the value [5 6 7] Matrix = [1 2 3; 4 5 6; 7 8 9]; % Creates a 3x3 array Top_left = Matrix(1:2,1:2); % Top_left now has the value [1 2; 4 5] Middle = Matrix([1 3],2);
% Middle now has the value [2; 8] When used as an index, the colon (:) represents all elements in the dimension.
MATLAB command Description Matrix = [1 2 3; 4 5 6; 7 8 9]; % Creates a 3x3 matrix Top_row = Matrix(1,:); % Top_row now has the value [1 2 3] Second_column = Matrix(:,2);
% Second_column now has the value [2; 5; 8] When used as an index, end means the last index in the dimension.
MATLAB command Description Matrix = [1 2 3; 4 5 6; 7 8 9]; % Creates a 3x3 matrix Last_row = Matrix(end,:); % Last_row now has the value [7 8 9] Last_column = Matrix(:,end); % Last_column now has the value [3; 6; 9] Last_element = Matrix(end);
% Last_element now has the value 9 You can use indices on the left-hand side of an assignment to change the values of multiple elements in an array.
If the sub-array specified on the left-hand-side of the assignment is an array, the right-hand-side of the assignment must be a scalar value or an array of the same size.
MATLAB command Description Matrix = rand(3); % Creates a 3x3 matrix of random values Matrix(2,2) = 0; % Changes the single element in the center of the matrix to 0 Matrix(1,:) = [1 1 1]; % Changes the entire first row of Matrix to all ones Matrix(2:end, 2:end) = zeros(2);
% Changes the bottom-right 2x2 sub-matrix of Matrix to all 0's
D. The MATLAB Workspace
Variables created at the command line are saved in the MATLAB workspace.
The who and whos commands display a list of variables currently stored in the workspace.
The whos command displays each variable's name, array size, bytes of memory used, and the type of data stored in each element.
Details of variables, including their values, are shown in the workspace browser window.
The clear command clears all variables from the workspace when used without arguments.
The command clear X Y would remove just the X and Y variables from the workspace.
E. Pre-defined Special Values
MATLAB provides a variety of pre-defined special values including:
MATLAB command Description pi % Pie (p) to approximately 15 significant digits (3.1415926535897931) i, j % Square root of -1 Inf % Machine infinity NaN % Not-a-Number (results from undefined math operations) clock % Current date and time [year month day hour minute second] date % Current date as a character string (e.g., 24-Nov-1998) eps % The smallest machine difference between two numbers ans
% Result of most recent equation not assigned to a variable You should not use MATLAB's special value names as your variable names
If you create a variable named pi, you will not be able to access the built-in value for pi
II. Good Programming Practices
When creating variable names:
Always use descriptive names that explain what the value stored in the variable means.
Always start your variable names with a capital letter-- this guarantees that your variables do not match or hide predefined MATLAB variable and functions.
Use underscores between "words" in variable names to make them more readable.
Typically avoid using abbreviations for variable names -- though some standard abbreviations such as hr (for hour) and mpg (for miles per gallon) are sometimes acceptable -- consult your instructor for guidance in specific cases.
Examples of good variable names | Rationale |
Cost | Descriptive, assuming the value represents a cost value of some kind |
Miles_to_target | Descriptive and easy to read |
X | If this is an x coordinate value in a graph, it is a good variable name |
Examples of invalid variable names | Rationale |
qw | Not descriptive; is not capitalized |
Cost$ | Invalid character '$' in the name |
Miles to target | Invalid characters (blanks) in the name |
xx12 | Not descriptive; is not capitalized; can be easily miss-typed |
X |
Bad if this is a value representing the cost of an item |
When accessing the values of a variable:
Do not use any indices for a scalar value.
Use a single index for vectors.
Always use 2 indices for arrays with 2 dimensions.
When creating arrays:
Use the built-in functions: zeros(), ones(), and rand() whenever possible.
Attempt to use the simplest method possible and avoid unnecessary duplication of statements. For example:
Poor | OK | Best |
Matrix(1,1) = 3; Matrix(1,2) = 3; Matrix(2,1) = 3;
Matrix(2,2) = 3; |
Matrix([1:2], [1:2]) = 3 |
Matrix = ones(2) * 3; |
If possible, create all of the memory for an array at one time and then modify its individual element values. This will greatly speed up the execution of your code. For example:
Matrix = zeros(100,200); %creates a 100 row by 200 column matrix
Matrix(1,1) = A;
Matrix(3,5) = B;
etc.
If an array "grows" in size over time, append new values to the end of the array using a statement like
Vector(end+1) = New_value;
III. Algorithms
A. Swap the contents of two variables
To exchange the values stored in two variables, e.g., X and Y, you need three(3) assignment statements as follows:
Temporary = X;
X = Y;
Y = Temporary;
Please make sure you understand why the following will NOT WORK!
Y = X;
X = Y;
Lab Work: Lab 2
References: Chapman Textbook: sections 2.1-2.5