User:Eml4500.f08.group.setlak

5. Matrix Building Functions:

eye             identity matrix zeros		matrix of zeros ones		matrix of ones diag		create of extract diagonals triu		upper triangular part of a matrix tril		lower triangular part of a matrix rand		randomly generated matrix hilb		Hilbert matrix magic		magic square toeplitz

6. Loops, if statements, and relations

For Loop

For loop syntax example, to produce a certain n-vector for a given n:

x = []; for i=1:n, x=[x,i^2], end

or can be written:

x = [];

for i= 1:n

x = [x, i^2]

end


 * Note: x = [] creates an empty matrix

The for statement permits any matrix to be used instead of 1:n. The variable consecutively assumes the value of each column of the matrix. The following example shows this syntax as it sums all the entries of matrix A by adding its column sums. s = 0;

for c = A

s = s + sum(c);

end

While loop

General form:

while relation

statements

end

The statements will be repeated continuously while the relation is true. Once the relation is no longer true the loop ends.

An example for a given number a, will compute and display the smallest nonnegative integer n, such that 2^n >= a:

n = 0;

while 2^n < a

n = n + 1;

end

n


 * Note: The semicolon after the statement keeps the values of n from printing on screen until after the loop is over and then the program calls to print n on the screen.

If statement

General form:

if relation

statements

end

The statements are executed only if the relation is true.

Multiple branching is also possible as shown in the following example:

if n < 0

parity = 0;

elseif rem(n,2) == 0

parity = 2;

else

parity = 1;

end

Relations

The relational operators in MATLAB are:

<	less than

>	greater than

<=	less than or equal

>=	greater than or equal

==	equal

~=	not equal


 * Note: = is used in an assignment statement while == is used in a relation

Relations may be connected or qualified by the following logical operators:

&	and

|	or

~	not

When applied to scalars a relation is just the scalar 1 (if true) or 0 (if false). Similarly for matrices of the same size a relation is a matrix of 1’s or 0’s. When a relation between matrices is interpreted by a while or if to be true each entry of the relation matrix must be nonzero.

Examples:

To execute statement 	when matrices A and B are equal:

if A == B

statement

end

To execute statement when A and B are not equal:

if any(any(A ~=B))

statement

end

Or

if A == B else

statement

end


 * Note: The above example does not work with the syntax:

if A ~= B, statement, end

This will not give the intended result because statement would only execute if each of the corresponding entries of A and B differ.