TDDD34 Programming with Applications in Engineering
Statements in Matlab
To write any programs of interest you will need to know the most basic set of statements and expressions and operators available in Matlab. This is a list of what you need for the course:
Input and output (user interaction)
disp('some text') Displays "some text" on the screen. disp(variable) Displays the variables value. disp(['Sum = ' num2str(x)]) Displays the text "Sum = " followed by the content of the variable x (x is an integer number). Notice the necessary brackets. x = input('enter a number') Displays the text "enter a number" and waits for the user to enter something that can be assigned to the variable x. x The content of the variable x is displayed. OBS! Only use to trace the execution when you try to localize errors. Use disp(x) by default. format Change how numbers are displayed (format, number of digits etc.).
Assignment to a variable
variable = expression The expression can be a constant or a calculation. The result is stored in the variable. Notice that this is an assignment. The equal sign here has a completely different meaning from what you are used to in math. The variable is changed to become equal to the expression.
Comments in the code
Every line in your program that starts with the character "%" is interpreted by Matlab as a comment (Matlab ignore the line). Comments are not useful to Malab, but very useful to the human programmer to remember the reasoning behind the calculations performed by the program. Comments can actually start anywhere on a line, everything from the "%"-character to the end of that line is a comment and ignored by Matlab. An example:
% This is a comment
Expressions and operators
When writing math expressions in Matlab you write them just as you would have on paper. Matlab is clever enough to know the strange order in which we perform addition, subtraction, multiplication and division, and you can use parentheses as usual to change the order (if for example an addition should be performed before a following multiplication. You are encouraged to use parentheses whenever the order of computations is not entirely clear. This make it much easier for you (humans) to interpret the calculation, and reduces risk of errors.
+ - * / Addition, subtraction, multiplication and division. ^ Exponentiation. rem(a, b) The remainder of the division a / b. mod(a, b) The remainder of the division a / b. They behave different for negative quotients.
When we program we need a few other operators than what you normally use in math. You will see they look very similar to the comparison operators in math, but they are not quite the same. In math they simply state whether the left hand side *is* equal to, less than etc... or greater than the right hand side. When we program we perform the comparison *to find out* if that is the case. If it is the result is "true" (1) else it is "false" (0). A list of comparison operators follow.
== In A == B, find out if A is equal to B < In A < B, find out if A is less than B <= In A <= B, find out if A is less than or equal to B > In A > B, find out if A is greater than B >= In A >= B, find out if A is greater than or equal to B
Once we start using the above operator to find out things we will need some more operators to combine the result. We may for example want to find out if A == B and, if at the same time, B < C. Then we need this set of logical operators. LHS and RHS in the following means the left and right hand side respectively.
and Logic AND, true if both LHS and RHS are true & Logic AND, true if both LHS and RHS are true or Logic OR, true if any of LHS or RHS is true | Logic OR, true if any of LHS or RHS is true ~ Logic NOT, true if RHS is false xor Logic EXCLUSIVE OR true if exactly one of LHS or RHS is true
The result of any combination of comparisons and logic operators will always be either "true" (1) or "false" (0). It can be used in statements to perform different operations in each case. You may for example want to display a different message to the user if a certain expression is false.
Conditions (selective execution)
Matlab has two kinds of conditional statements. We start with "if":
if expression1 statements end
The above perform the statements between "if" and "end" only if the expression evaluates to "true". If the expression is "false" nothing is done.
if expression1 statements else statements end
The second "if"-statement example above is almost as the first, but in this case the statements between "else" and "end" is performed when the expression is "false", instead of doing nothing.
if expression1 statements elseif expression2 statements end if expression1 statements else if expression2 statements end end
The statements between "if" and "elseif" is performed when "expression1" is "true". Perform the statements between "elseif" and "end" if "expression1" is "false" and "expression2" is "true". Otherwise it perform nothing. It is actually just a tidier way of writing a second "if"-statement withing the first:
if expression1 statements else if expression2 statements end end
As said, the above is no different from the previous. Of course we can add an else part in the inside "if" above. Written in the tidier way you should use it become:
if expression1 statements elseif expression2 statements else statements end
The functionality is the same, except the added last "else" is performed only when none of the previous expressions are "true". Observe that there are no limits on how many "elseif" you can add, but the "else" part must always be last if it occur.
Finally, the second kind of conditional statement is "switch":
switch switch_expression case case_expression1 statement1 case (case_expression2_1, case_expression2_2) statement2 otherwise statement3 end
The switch expression is first evaluated and then the case expressions is searched in order until one is equal to the switch expression. The corresponding statements are preformed. If no case expression match, then the statements between "otherwise" and "end" is executed.
Before we deal with repetition we need to be able to specify an interval, and which numbers in the interval we are interested in. It can be done in the following ways:
N:M Specifies all numbers starting with N to and including M in steps of one. Thus 1:5 specifies the numbers 1, 2, 3, 4 and 5. N:S:M As above but in steps of S. I.e. N, N+S, N+2S, N+3S, ... up to the last value smaller than or equal to M. Thus 1:2:5 specify 1, 3 and 5, but 1:2:4 specify only 1 and 3. Observe that any of N,S,M may be negative. If S is negative M must of course be smaller than N to get a valid interval.
Two types of repetition statements are available. "for" is the first one:
for variable = interval statements end
The statements are executed once for every value in the interval.
The second repetition statement is "while":
while expression statements end
The statements are executed over and over again while the expression is "true". As soon as the expression become "false" executions of the statements are stopped. If the expression is "false" from start the statements are not executed at all.
Some other useful things
... Continues an expression on the next line without executing the current line. ; Put at end of line to not display the result. break Stops an iteration ("while" or "for"). clear x Removes the variable x. clear Removes ALL variables. rand Generates a random number in the interval [0,1[. ans The result of last calculation. eps Least value/precision. pi The math constant Pi. Inf Infinity. NaN "Not a Number" result of for example division by zero. i, j Marks the imaginary part of a complex number. x=2+3i Store the imaginary number 2+3i in the variable x. real(x) The real part of the variable x. imag(x) The imaginary part of the variable x. complex(1, 2) Create the complex number 1+2i. pause Stop the program for a short period of time. date Todays date (as a string (text)). realmax Largest possible floating point value in MatLab. realmin Smallest possible floating point value > 0. intmax Largest possible integer in Matlab. intmin Smallest possible (negative) integer. floor Round a floating point value down to nearest integer. ceil Round up to nearest integer. round Round to nearest integer. OBS! It is always interesting to think of what the result of round(X.5) is with different values of X. It is not very well defined mathematically. abs The absolute (positive) value of a number. sqrt Calculates the square root. gcd Calculates the greatest common divisor. str2num Convert a string (text) to a numeric value. num2str Convert a numeric value to a string (text). strcmp Compares two strings. upper Convert a string to UPPERCASE. lower Convert a string to LOWERCASE.
Page responsible: Erik Nilsson
Last updated: 2012-08-07