Vous êtes sur la page 1sur 17

Program Files in Computer Programming Languages

Initialize variable m and store a value of 2.5 inside it


>>m = 2.5;
Initialize variable b and store a value of 15 inside it
>>b=15;
Evaluate the equation, using variables m and b together with the value of x.
disp(m*7+b);

MATLAB as an Interactive Program


Stores the result to our own variable
>>variable_name = command
If we dont want the result to be printed to the command window, we end the command
with a semicolon.
>>variable_name = command;
clear erases all of the variables
clc clears the Command Window but does not affect the variables that have been
created.
clear variable_name erases only that one variable
diary filename opens a text file with that name and records everything that happens in
the command window from that point on, including commands and outputs.
diary off stops recording.
Save filename.mat stores all the variables in the workspace to disk.
Load filename.mat retrieves all the variables stored in the file to the workspace

Data Types
logical: 0 or 1 (used for true or false calculations)
char: usually an 8-bit unsigned integer type used to represent characters (letters, numbers,
punctuation) commonly found on a standard keyboard.
int8, int16, int32, int64: signed integers with the given number of bits
uint8, uint16, uint32, uint64: unsigned integers with the given number of bits
single: 32-bit floating-point number, the binary equivalent of scientific notation for large
ranges and fractional values.
double: 64-bit floating-point number, the binary equivalent of scientific notation for even
larger ranges and fractional values.

Floating Point Numbers

The name implies that the location of the decimal point in the representation of the
number is floating and can be moved around, depending on the value stored.
>> x=45676335677665.4
x=
4.5676e+13
Changing Data Types

ceil( ) will round a floating-point number up


floor( ) will round a floating-point number down
round() will round a floating-point number towards the nearest integer
fix() will round a floating-point number towards zero
>> x=54.5;
>> a=ceil(x)
a=
55
>> b=floor(x)
b=
54

>> c=round(x)
c=
55
>> d=fix(x)
d=
54
Data Type Conversion Examples
Enter the format command below, which forces the use of more significant digits.
>> myPI = 3.14159265359
myPI =
3.1416

>> format long


>> myPI =
3.141592653950000

Scalars, Lists, and Arrays


To enter values in a row, the numbers are separated by space or commas
>> y = [1 2 3] or >> y = [1, 2, 3]

To enter values in a column, the numbers are separated by a semicolon.


>> y = [1; 2; 3]

When entering values for both rows and columns, you must enter an entire row and then
use a semicolon to start the next row, and so on.
>> y = [1 2 3; 4 5 6; 7 8 9]
y=123
456
789

The ones and zeros commands can be used to create arrays of 1s or 0s by supplying
a list of the dimensions. This is often how an array of a set size is creating without
supplying all of the values at the same time.
>> data = ones(3)
data =
111
111
111

>> data2 = ones(1,4)


data2 =
1111

Within square brackets (optional), give the starting value, the increment, and the limit.
Note that the limit will not always be in the resulting array. If the increment value is
omitted, MATLAB assumes an increment of +1.
>> data = [1:2:10]
data =
13579

>> data2 = 100:-25:0


data2 =
100 75 50 25 0

Use the linspace( ) function, which takes the starting value, the final value, and the
number of equally spaced elements in the resulting array.
>> data = linspace(1,10,4)
data =
1 4 7 10
Extracting Information from Arrays
MATLAB uses one set of parentheses for a list of dimensions separated by commas, and
the indices start counting at 1. Lets look at some examples.
>> y = [1 2 3; 4 5 6; 7 8 9]
y=
123
456
789

>> y(2,3) Row 2 ,column 3


ans = 6

>> y(1:2,1:2) Rows 1-2, column 1-2


ans = [1,2; 4,5]

>> y(1:2,:) Rows 1-2, all columns


ans = [1,2,3; 4,5,6]

>> y([1 3],2) Point in rows 1 and 3, column 2


ans = [2; 8]

>> y([1 3],[3 1 2]) Points in rows 1 and 3, columns (in order 3,1,2)
ans = [3,1,2; 9,7,8]
>> [y(1,1), 0; 0 y(3,3)] Building a 2x2 array
ans = [1,0; 0,9]

Modifying Array Elements


We can change an individual array element, or even a section of an array, by specifying it
as if we were storing the result of an equation into a variable. There are two restrictions.
1. The data type of the value that you are storing to the element of the variable must be
the same as the data type of the array variable.
2. The value or array that you are assigning to the subset of the variable must have the
same dimensions.
x = [1 4 7; 2 5 8; 3 6 9]
ans =
147
258
369

>> x(2:3, 2:3) = [11 12; 13 14] Modifies rows 2-3, columns 2-3
x=
1 10 7
2 11 12
3 13 14

>> x(1,2) = 10
x=
1 10 7
258
369
Mathematical Operations on Arrays

Many of the mathematical operations that can be performed on scalars can also be
performed on arrays with some restrictions. Some operations require an array of any size
and a scalar.
>> x = [1:1:4]
x=
1234

>> x+2
ans =
3456

>> x*5
ans =
5 10 15 20
Some operations are element-by-element, requiring arrays of exactly the same
dimensions. The operation will be performed on each corresponding element of the two
arrays and result in an array of answers that has the same size.
>> x = [1:1:4]
x=
1234

>> y = [2:2:8]
y=
2468

>> x+y
ans =
3 6 9 12

>> x.*y
ans =
2 8 18 32
More Mathematical Operations on Arrays
Some functions can take an array as an input instead of a scalar as were used to. When
we do this, MATLAB will perform the function on each element of the array and return
the answers as an array. This is called vectorization.
>> theta = linspace(0,90,5)
theta =
0 22.50 45.00 67.50 90.00

>> sines = sin(theta)


sines =
0 -0.48 0.85 -0.99 0.89

There are some operations that are specially defined for matrices. One of the best
examples is matrix multiplication, such as x * y. However, we may need to ability to
perform an element-by-element operation with the same operator. To distinguish the by-
element operation, we add a . in front of the operator.
>> x = [1:1:4]
x=
1234

>> y = [2:2:8]
y=
2468

>> x.*y
ans =
2 8 18 32

>> x*y Matrix multiplication


ans =
60
Array Storage and Reshaping
When an array is created in MATLAB, all the values are actually stored as a long one-
dimensional list. The dimensions are stored separately, and MATLAB formats the output
as it needs to, since the purpose of dimensions is really to make the data more
understandable to us humans. As a result, we can tell MATLAB to change the dimensions
of an array as long as the total number of elements would be the same.
>> x = [1:8]
x=
12345678

>> reshape(x, 2, 4) 2 rows, 4 columns


ans =
[1,3,5,7; 2,4,6,8]

>> reshape(x, 2, 2, 2) 2 rows, 2 columns, 2 dimensions


ans(:,:,1) =
[1,3; 2,4]

ans(:,:,2) =
[5,7; 6,8]

>> reshape(x,1,[])
ans =
[1,3,5,7; 2,4,6,8]

To determine the size and / or dimensions of a variable, we can use the size() command.
The size command will return a value for every dimension of its input variable.
>> size(zeros(200,400,3))
ans =
200 400 3

>> size(zeros(200,400,3),2)
ans =
400

Logical Data Type for Variables


In MATLAB, a logical is 1 to represent true and 0 to represent false

Relational Operators

< is less\lower than


> is greater\higher than
<= is less\lower than or equal to
>= is greater\higher than or equal to
== is equal to (check for equality)
~= is not equal to (check for inequality)

There are two MATLAB commands that will help you compare arrays:

all(array of logicals) Returns logical 1 only if all values in the array of logicals are
1s Acts like a massive AND function
any(array of logicals) Returns logical 1 if at least one value in the array of logicals is
1 Acts like a massive OR function

Logical Operators
AND operator -Operates on two logicals
Both logicals must be true for the output to be true, otherwise the output is false
MATLAB formats :
o logical1 & logical2
o and(logical1, logical2)

OR operator -Operates on two logicals


At least one logical must be true for the output to be true; the output is false only of both
inputs are false MATLAB formats
o logical1 | logical2
o or(logical1, logical2)

NOT operator-Operates on one logical


Complements the value
MATLAB formats
o ~logical2
o not(logical1)

Order of Operations- NOT, AND, OR

If Statements
The if statement tells the computer to conditionally execute a chunk of code when a
logical expression evaluates to true. Otherwise the code is skipped.

if logical
%Stuff done only when the logical is true
end

The if-else statement tells the computer to execute one chuck of code if the logical
expression evaluates to true, and a different chunk of code if false. There is no way that
both chunks of code will be executed on the same pass.
if logical
%Stuff done only when logical is true
else
%Stuff done only when logical is false
end
The if-elseif-else statement is strictly for convenience. This replaces a group of if-
elses that are implementing a complex condition. Each if and elseif will have its
own logical expression to evaluate.

if logical1
%Stuff done only when logical1 is true
elseif logical2
%Stuff done only when logical1 = false and logical2 = true
else
%Stuff done only when logical1 and logical2 are false
end

Switch Case Statements


A Switch statement is much like a streamlined version of an if-elseif-else statement.
However, it has more limitations. First, the switch statement is given a single variable
used to make decisions. Each case statement lists numerical values that can match the
variables value, and commands to execute it there is a match. Notice below that each
case statement may contain one or more values. You CANNOT list a range of values
using comparison operators (like < or >). You MUST specify each value.

switch variable
case {value1, value2}
%commands executed if variable matches value1 or value2
case {value3}
%commands executed if variable matches value3
otherwise
%commands executed if variable not val1, val2 or val3
end

For Loops
A for loop uses a variable, referred to as a counter, to track how many times to go
through the loop. The counter is specified with a start value, a final value or upper limit,
and an increment.

for countername = start : step_size : maximum_value


%Stuff done each time through the loop
end

for i = [gridsize:gridsize:size(f18,1)]
i; % remove the ; to see rows
f18(i , : , 1) = 0*ones(1, size(f18,2));
f18(i , : , 2) = 255*ones(1, size(f18,2));
f18(i , : , 3) = 0*ones(1, size(f18,2));
image(f18)
end
While Loops
This loop should be used when the program cant determine how many times the loop
will be executed as the loop section starts. The computer will check a logical condition,
and if the condition is true, the program will execute the loop, return to the logical
condition, and check it again.

while (logical)
%do stuff here over and over until logical = false
end

limit = 20; % maximum Fib numbers to check


bound = 1000; % upper limit of last Fib number
fib(1:2) = [ 1 1 ]; % initialize Fibonacci Sequence
i = 2; % ...already have 2 Fibonacci numbers
count = 2; % count the number of iterations tried

% find largest Fibonacci number less than bound


while ((fib(i) < bound) & (count < limit))
i = i+1;
fib(i) = sum( fib( [i-2,i-1] ) );
count = count+1;
end

if count < limit


fib(i-1) % returns answer
else
-1 % returns error
end
Text and Outputs

To store letters instead of numbers within a variable. A variable which holds a character
rather than a number is given a datatype of char
>> x = 'A'; %store ASCII character A (65) inside variable x
>> y = '7'; %store ASCII character 7 (55) inside variable y
>> a = uint8(70); %holds numeric value of 70
>> b = char(70); %holds ASCII value of 70, which is capital F

Storing string variables


>> mystr = 'some text';

Accessing string variables


>> mystr([3:7])

Display Function
>> var1 = uint8(65); >> disp(['my num = ' num2str(var1)]);

sprint() Function
To combine text and variable contents in the same output line. We can do this using a new
function called sprintf().

The sprintf() command cant tell the difference between text and variable names, so by
default, everything in the single quotes is text. We can get MATLAB to insert numeric or
other values into the text though, but we need to use conversion characters instead of the
variable name.

>>Var1 = 27;
>>mytext = sprintf('My num is Var1');
>>disp(mytext);
Output: My num is Var1

>>Var1 = 27;
>>mytext = sprintf('My num is %d', Var1);
>>disp(mytext);
My num is 27
Conversion Characters
disp(sprintf('%s %f rad', 'pi', 3.1415));
prints a string and a float, and some text

disp(sprintf('%s %d degC', 'absolute zero', -273.15));


prints a string and float (scientific notation), and some text

disp(sprintf('%7s %7f', 'e', 2.7182));


forces width of string and float to be 7 characters wide, right-aligned

disp(sprintf('%7s %7.2f', 'negative', -1.23456));


forces width of 7 and only 2 decimal places on the float

disp(sprintf('%-7s %-7.2f m/s^2','g', 9.80665));


width of 7, 2 decimal places, left-aligned

disp(sprintf('%-7s %07.2f', '2pi', 6.2832));


width of 7, 2 decimal places, text left-aligned, float right-aligned w/ zero padding

Escape Characters
Some the characters that you might want to write to a display are already being
used for special purposes. For example, you cant write a single quote, ', because
a single quote is used to mark the start and end of string variables. Also, you cant
write a percentage sign, %, since those are used to start conversion characters.
To access these characters and other, you use an escape character
Examples
'' single quote (two single quotes, not a double quote)
\\ - backslash
\n newline, move the cursor down one line
\r carriage return, move the cursor to the beginning of the line
\t tab %% - percentage signwhich oddly requires itself for the escape character
PLOTS
The syntax of the plot() function is plot( array_of_x-coordinates, array_of_y-coordinates)
plot( array_of_x-coord, array_of_y-coord, 'line_specifier')
Linespacers
LineStyle:
- solid
-- dashed
: dotted
-. dash-dot
LineColor:
r red
g green
b blue
c cyan
m magenta
y yellow
k black
w white

MarkerType: + o * . x ^ v < > s d p h

>>plot([1 2 3 4 5], [2 4 9 4 6], '--rd');


>>plot([1 2 3 4 5], [2 4 9 4 6], 's:m');
>>plot([1 2 3 4 5], [2 4 9 4 6], 'g-.');

Additional Line Properties


plot(x-array, y-array, 'property','value', 'property','value',)

The list of valid properties is


LineStyle Color
Marker LineWidth
MarkerSize MarkerEdgeColor
MarkerFaceColor
>>plot([1 2 3 4 5], [2 4 9 4 6], '--rd');

Adjusting Limits
xlim([low_limit high_limit]);
ylim([low_limit high_limit]);

Multiple Line per Plot


>>plot([1:1:5],[1 2 5 4 7],'-r+', [3:1:7],[0 1 4 3 6],'-k+');
>>plot([1:1:5],[1 2 5 4 7], '-r+'); >>hold on;
>>plot([3:1:7],[ 0 1 4 3 6], '-k+'); >>hold off;

Adding Details to a Plot


xlabel('text', 'property', 'value',)
ylabel('text', 'property', 'value',)
zlabel('text', 'property', 'value',)
title('text', 'property', 'value',)
text(x, y, 'text', 'property', 'value',)
legend('name', 'name',)

Plotting a function
fplot('function', [low_limit high_limit], 'property', 'value',)

Multiple Plots per figure


>> subplot(2,3,2);
subplot(rows_of_graphs, columns_of_graphs, selected_graph)

Graphs
Histogram
>>hist(x) x is a one-dimensional array of data values data is automatically separated
into 10 equal sized bins MATLAB uses the high and low values from the data to
determine the ranges for the bins
>>hist(x, number_of_bins) still uses the min/max of data to determine range of bins
number_of_bins specifies how many equal sized bins the graph will have
>>hist(x, bin_centers) bin_centers is a one-dimensional array containing the center
value of each bin; the separation between bins is the midpoint between adjacent points

Bar
>>bar(y, 'color') y is a one-dimensional array of bar heights x coordinates are assumed
to be 1, 2, 3 'color' is single-character line specifier for bar color, blue by default
>>bar(x, y, 'color') y is a one-dimensional array of bar heights x is a one-dimensional
array of bar locations and cannot have duplicate values; if values are unevenly spaced,
the bars will be, too
>>bar(x, y, 'type') y is a two-dimensional array of bar heights Each row of y contains
multiple measurements for the same x value (bar) i.e. the number of elements in x is
equal to the number of rows in y. Type is either stacked or vertical (default).

3D Plots
>>plot3(x, y, z, 'property', 'value');
Example plot3(cos(theta), sin(theta), theta, ... 'LineWidth', 2, 'Marker', 'Diamond');
>>mesh(x, y, z); x is a one-dimensional array of x-axis values y is a one-dimensional
array of y-axis values z is a two-dimensional array of elements that correspond to the
output for each combination of x and y.

ADDITIONAL OPERATIONS
g(g<-10)=-10; >> or(y<=2,y==5)
STAIRS
>> stairs([3 4 3 2 5.1 5.1])
The stairs() command is a graphing command that also plots x and y points. Instead of
connecting adjacent points with angled lines like the plot command, the stairs() command
will create a horizontal line from the current point to the next point, then jump to the next
points y value.

PIE GRAPH
>> pie([5 14 2 11], [0 1 0 0],
{'SWTOR','Skyrim','STO','ME2'})
1. The first parameter is an array of data values. It does not need to sum to 100%.

2. The second parameter is optional. It must have the same number of elements as
the first, and contain only 1s and 0s. If an entry is 1, the corresponding pie slice
from the first array will be pulled out of the pie slightly Essentially Exploded.

3. The third parameter is optional and is used to label the slices if you want
something other than percentages. It must have the same number of labels and the
first array. Notice the labels are in an array that uses curly brackets, not square
brackets.

Adding labels, titles and legend to the graph


figure(3); %Third figure plots real & imag components
plot(t,real(foo),'b',t,imag(foo),'r'); grid on;
title('Real and Imag values of Spiral vs.
Time','FontSize',14);
xlabel('Time (sec)');
ylabel('Magnitude');
legend('Real component','Imaginary component',...
'Location','NorthWest');
Legend location uses Cardinal coordinates

Complex Numbers
We can define a variable as an imaginary number using the strict definition of the
imaginary number:
>>i = sqrt(-1) i = 0 + 1.000i
If the variable i has not yet been defined (i.e. there is no variable named i in the
workspace), MATLAB will assume this definition automatically
>>a = 3 + 4*i
a = 3.000 + 4.000i
Vs
>>i = 10; % i is defined
>>a = 3 + 4*i a = 43

The magnitude of a complex number can be found by using Pythagoreans Theorem. and
the angle can be found using the arc-tangent of the ratio of the real and imaginary
components

MATLAB has two functions which perform these operations on complex numbers; they
are the abs() command and the angle() command.
The abs() command is actually the same as absolute value, used to flip the sign of
negative numbers.

Extracting the real or imaginary components of an imaginary number


We can also extract only the real or imaginary components of a complex variable, using
the real() and imag() commands
>> plot(real(foo), imag(foo), 'LineWidth', 2) %same spiral plot >> axis square;

If we directly feed a purely real variable and a complex variable to a plot() command,
MATLAB will issue a warning saying that the imaginary components are ignored.

Lastly, if we omit the first X vector input, and only supply the plot command with a
Y vector which is complex, MATLAB will automatically split it up into real and
imaginary parts, yielding the same result as before:
MATLAB Function Template
The template for the first line of a function is shown below.

function [output1 output2 ] = function_name(input1, input2,


)

The function line must be the first executable line of the file. This line is
commonly called the function declaration.

o All comment lines should come after it (may come before). These
comments are displayed when the help() command is ran with the
function name as an input (e.g. >> help myfunc;).

o The function declaration defines the number of inputs, outputs, the


names of the inputs and outputs, and the name of the function.
The function_name is whats used to run the function from another
program or from the command window.

o It can be any valid variable name, which means it can contain letters,
numbers, and the underscore, it must start with a character, and it
cannot be the same as a MATLAB keyword.
o The file should be named function_name.m, since MATLAB will look
for this function by searching for a file with the same name. (Actually,
the two names can be different, but MATLAB will look for the file
name when using the function, not the name written in the file.)

o The function_name should be somewhat descriptive, to help humans


understand what the function does (e.g. sin(), round(), disp(), ).

Outputs of a Function
o Function outputs are defined on the left-side of an assignment
statement within the function declaration, inside square brackets
[output1, output2, ] and separated by commas or spaces.

o A function with no outputs can use empty square brackets [] in the


declaration.

o To use an output, simply write to the output variables as the function


executes, and they will automatically be reported back to the caller
when the function ends.
Notice that when you dont store the outputs into separate variables, only the first one is
returned. You need to explicitly give variables for the outputs to capture them all.

Inputs of a Function
o Inputs are defined by the function declaration (input1, input2, )
next to the function_name, inside parenthesis and separated by
commas or spaces.

o A function with no inputs can use empty parenthesis () in the


declaration.

o To use an input, you can simply assume that the particular variable
already exists and is populated with the data you expect, or in some
cases, you may have to error-check your inputs.

Exiting the function


Exit the function at any time by using the return command

Functions can optionally be terminated / ended in code with the end


command.
o This allows for multiple functions per m-file.
o Only the function which the file is named after can be used
externally. Other functions declared in a file are local functions and
can only be accessed from within the m-file.

Example
function [centers] = rangecen1(bounds)
% Place comments here...
for i = [1 : 1 : length(bounds)-1]
centers(i) = ( bounds(i)+bounds(i+1) )/2;
end %The variable centers grows inside the loop
end
Example of calling the function
cen = rangecen1([1:2:9])
cen =
2468

Length(), size() and numel()


The length() command is similar to the size() command, except length() only returns a
single number, rather than the size of every dimension. Actually, length() only
returns the size of the largest dimension of its input. So if your input has more
than 1 dimension, length() may not return the value you want

There is also another similar command called numel(), which returns the total number of
elements in a variable, regardless of its dimensions.
length([1 2 3; 4 5 6])
ans =
3
numel([1 2 3; 4 5 6])
ans =
6

function [centers bounds] = rangecen2(minval, maxval, nbins)


%Calculates the centers / bounds of bins for a histogram plot
bounds = linspace(minval, maxval, nbins+1);
for i = [1 : 1 : nbins]
centers(i) = ( bounds(i)+bounds(i+1) )/2;
end %The variable centers grows inside the loop
end

The function help command should be :


1. Description and format of input
2. Description and format of outputs
3. Summary of the operation performed
4. Any dependencies on other functions

Like any other file that you submit, the function file should also contain

1. Names of group members


2. Days and times of class
3. Number of the assignment
4. Data last modified

Exam Outline
Generate data using equation
Vectorization with arrays/ equation
Use a loop to build data point by point
Print to a text file
Plot the same or different data .

Open Blackboard/ closed notes and book

Vous aimerez peut-être aussi