2. MATLAB Operators
An operator is a symbol that is employed to perform specific mathematical or
logical manipulations.
MATLAB is designed to operate primarily on whole matrices and arrays. Therefore,
operators in MATLAB work both on scalar and non-scalar data.
MATLAB allows the following types of elementary operations −
Arithmetic Operators
Relational Operators
Logical Operators
Special Operators
4. Relational Operators
A relational operator compares two numbers by determining whether a comparison
statement (e.g., 5 < 8) is true or false. If the statement is true, it is assigned a value
of 1. If the statement is false, it is assigned a value of 0.
Note that the "equal to" relational operator consists of two= signs (with no space
between them), since one = sign is the assignment operator. In other relational
operators that consist of two characters, there also is no space between the
characters(<=,>=,~=).
5. Relational Operators Cont…
Relational operators can be used in MATLAB commands (e.g., if) to control the
flow of a program.
When two numbers are compared, the result is 1 (logical true) if the comparison,
according to the relational operator, is true, and 0 (logical false) if the comparison is
false.
If two arrays are compared (only arrays of the same size can be compared), the
comparison is done element-by-element, and the result is a logical array of the same
size with 1s and 0s according to the outcome of the comparison at each address.
If a scalar is compared with an array, the scalar is compared with every element of
the array, and the result is a logical array with 1s and 0s according to the outcome of
the comparison of each element.
9. Relational Operators Cont…
The results of a relational operation with vectors, which are vectors with 0s and 1s,
are called logical vectors and can be used for addressing vectors. When a logical
vector is used for addressing another vector, it extracts from that vector the elements
in the positions where the logical vector has 1s.
10. Relational Operators Cont…
Numerical vectors and arrays with the numbers 0s and 1s are not the same as logical
vectors and arrays with 0s and 1 s. Numerical vectors and arrays can not be used for
addressing. Logical vectors and arrays, however, can be used in arithmetic
operations. The first time a logical vector or an array is used in arithmetic operations
it is changed to a numerical vector or array.
Order of precedence: In a mathematical expression that includes relational and
arithmetic operations, the arithmetic operations(+,-,*, I,) have precedence over
relational operations. The relational operators themselves have equal precedence and
are evaluated from left to right. Parentheses can be used to alter the order of
precedence.
11. Logical Operators
A logical operator examines true/false statements and produces a result that is true
(1) or false (0) according to the specific operator. For example, the logical AND
operator gives 1 only if both statements are true.
12. Logical Operators Cont…
Logical operators can have numbers as operands. A nonzero number is true, and a
zero number is false.
Logical operators (like relational operators) can be used as arithmetic operators
within a mathematical expression. The result can be used in other mathematical
operations, in addressing arrays, and together with other MATLAB commands (e.g. ,
if) to control the flow of a program.
Logical operators (like relational operators) can be used with scalars and arrays.
The logical operations AND and OR can have both operands as scalars, both as
arrays, or one as an array and one as a scalar.
If both are scalars, the result is a scalar 0 or 1.
13. Logical Operators Cont…
If both are arrays, they must be of the same size and the logical operation is done
element-by-element. The result is an array of the same size with 1s and 0s according
to the outcome of the operation at each position.
If one operand is a scalar and the other is an array, the logical operation is done
between the scalar and each of the elements in the array and the outcome is an array
of the same size with 1 s and 0s.
The logical operation NOT has one operand. When it is used with a scalar, the
outcome is a scalar 0 or 1. When it is used with an array, the outcome is an array of
the same size with 0s in positions where the array has nonzero numbers and 1s in
positions where the array has 0s.
16. Order of precedence
Arithmetic, relational, and logical operators can be combined in mathematical
expressions. When an expression has such a combination, the result depends on the
order in which the operations are carried out.
If two or more operations have the same precedence, the expression is executed in
order from left to right.
17.
18. Built-in logical functions
MATLAB has built-in functions that are equivalent to the logical operators. These
functions are:
19. Built-in logical functions cont.…
In addition, MATLAB has other logical built-in functions, some of which are
described in the following table:
21. Built-in logical functions cont.…
The operations of the four logical operators, and, or, xor, and not can be summarized
in a truth table:
22. Example for logical expression evaluation
In a logical expression, numerical operations are carried out first, then the relational
operations, and finally the logical operations.
23. CONDITIONAL STATEMENTS
A conditional statement is a command that allows MATLAB to make a decision of
whether to execute a group of commands that follow the conditional statement, or to
skip these commands. In a conditional statement, a conditional expression is stated.
If the expression is true, a group of commands that follow the statement are
executed. If the expression is false, the computer skips the group. The basic form of
a conditional statement is
For every if statement there is an end statement.
The if statement is commonly used in three structures, if- end, if -else-end, and if -
elseif -else-end.
29. THE switch-case STATEMENT
The switch-case statement is another method that can be used to direct the flow of a
program. It provides a means for choosing one group of commands for execution
out of several possible groups.
30. THE switch-case STATEMENT
switch switch_expression, case case_expression, end evaluates an expression and
chooses to execute one of several groups of statements. Each choice is a case.
The switch block tests each case until one of the case expressions is true. A case is
true when:
For numbers, case_expression == switch_expression.
For character vectors, strcmp(case_expression,switch_expression) == 1.
For a cell array case_expression, at least one of the elements of the cell array matches
switch_expression, as defined above for numbers, character vectors, and objects.
When a case expression is true, MATLAB executes the corresponding statements
and exits the switch block.
An evaluated switch_expression must be a scalar or character vector. An evaluated
case_expression must be a scalar, a character vector, or a cell array of scalars or
character vectors.
The otherwise block is optional. MATLAB executes the statements only when no
case is true.
32. Tips: THE switch-case STATEMENT
A case_expression cannot include relational operators such as < or > for comparison
against the switch_expression. To test for inequality, use if, elseif, else statements.
The MATLAB switch statement does not fall through like a C language switch
statement. If the first case statement is true, MATLAB does not execute the other
case statements.
Define all variables necessary for code in a particular case within that case. Since
MATLAB executes only one case of any switch statement, variables defined within
one case are not available for other cases.
The MATLAB break statement ends execution of a for or while loop, but does not
end execution of a switch statement. This behavior is different than the behavior of
break and switch in C.
33. Loops
There may be a situation when you need to execute a block of code several number
of times. In general, statements are executed sequentially. The first statement in a
function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times and following is the general form of a loop statement in most of the
programming languages:
34. The “for...end” loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
42. Loop Control Statements
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed
43. break Statements
The break statement terminates execution of for or while loop. Statements in the
loop that appear after the break statement are not executed.
In nested loops, break exits only from the loop in which it occurs. Control passes to
the statement following the end of that loop
45. continue Statements
The continue statement is used for passing control to next iteration of for or while
loop.
The continue statement in MATLAB works somewhat like the break statement.
Instead of forcing termination, however, 'continue' forces the next iteration of the
loop to take place, skipping any code in between.
48. Plot
The plot command is easily one of the most useful MATLAB commands. It needs at
least one argument as shown in following figure.
If there is no open figure, MATLAB will open a new one and will plot the argument
(an array) versus its index.
If there are two arrays as input arguments, MATLAB will take the first array to be
the x-coordinates, and the second array, the y-coordinates.
Fig.- Plot command
A third string argument can specify the type of line, colour and marker of the plotted
line.
49. Plot cont.…
If you want to plot more than one thing on the same figure, use the command hold
on.
The grid lines can be toggled on and of with the command grid (use grid on).
Fig.- Figure with axis
50. Manipulating a plot using command line
xlabel(‘String’) assigns text to your x axis. If you want to change the font size, then
add a property after the string i.e. xlabel(’String’,’fontsize’, Font size value). The
same goes for y axis i.e. ylabel(’String’,’fontsize’,Font size value’)
Title is added using title(’String’,’fontsize’,value’)
Changing the font size of the numbers on the axes is a bit different. You have to
have the figure you want to alter opened. Afterwards enter set(gca,’fontsize’, value).
This sets the font size of the current figure to the value you want.
The legend is added using legend(’String’).
The axes can be controlled by the following commands
53. Three dimensional graphics
The plot3 command plots a line from x, y and z vectors.
t=-5:.005:5;
x=(1+t.^2).*sin(20*t);
y=(1+t.^2).*cos(20*t);
z=t;
plot3(x,y,z)
grid on
FS='FontSize';
xlabel('x(t)',FS,14)
ylabel('y(t)',FS,14)
zlabel('z(t)',FS,14,'Rotation',0)
title('plot3 example',FS,14)
54.
55. Axis and Figure Properties
Plot a graph using following line of codes
x=0:0.05:10
y=1./((x-.3).^2+.01)+1./((x-.9).^2+.04)-6;
plot(x,y);
Now store current axis using ax=gca;
The axis and figure properties can be modified using different command as follows
>> ax.FontWeight='Bold’; // Change font weight
>> ax.FontSize=20; // set don’t size
Additional detail can be found on MathWorks.
56. Saving Figures
Figures can be saved in a specific file format using following commands:
saveas(fig,filename)
saveas(fig,filename,formattype)
More details can be found at MathWorks.
57. Manipulating a plot using GUI
First, generate a graph using following command
x=magic(100);
figure; plot(x(1,:));
In order to manipulate the graph using the GUI, go to “Edit“ and “Axes Properties“
in the drop down menu. A window will appear allowing you to manipulate the
labels, title, legend, font sizes, linewidths and everything else you might need to
tailor the plot for publication.
First, label the axes. You can access that in the “X axis“ and “Y axis“ tabs in the
bottom of the screen. As an example, change the x label to be “Time (s)“ and y label
to be “Current (mA)“. In the axis’ tabs you can also change the range that you want
to be displayed as well as the type of the axis, whether it is logarithmic or linear.
Now, add the title by inputting “Current over Time“ inside the box on the left hand
side of the window. You should see a title appearing on the top of your figure.
58. Manipulating a plot using GUI
In order to change the font or font size of your labels, double click on the label. A
different sub-window will change on the bottom of the “Axes Properties“ window.
Change the font size to be “16“. I find this to be used as a rule of thumb in most
cases. Also, change the font to bold. Moreover, perform the same actions on the Y
axis and the title.
In order to change the font size of the numbers on your axes, select your graph again
and go to “Font“ tab. Here, change the font size to 16 to match the labels.
Legend is added by clicking the “Insert Legend“ button in the toolbar and a legend
should appear. You can move the position of the legend on the figure as well as
change the string explaining the line. In order to change the text, double click on the
legend and type “flux“ in this case.
Finally, you can alter the way the line itself is represented. Click on the line of your
graph and you can change the style, color and line width on the right hand side of
the of the sub-window. As an example, change the line width to “2“. I usually keep it
“2“ as a rule of thumb.