0% found this document useful (0 votes)
5 views

Matlab Notes (5)

The document provides an overview of MATLAB, including its advantages and disadvantages, basic environment, and functionalities. It discusses the history of MATLAB, its applications in engineering and scientific calculations, and various programming concepts such as arrays, matrices, loops, and functions. Additionally, it highlights best practices for coding in MATLAB and includes examples of common operations and commands.

Uploaded by

kkirbiyik7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Matlab Notes (5)

The document provides an overview of MATLAB, including its advantages and disadvantages, basic environment, and functionalities. It discusses the history of MATLAB, its applications in engineering and scientific calculations, and various programming concepts such as arrays, matrices, loops, and functions. Additionally, it highlights best practices for coding in MATLAB and includes examples of common operations and commands.

Uploaded by

kkirbiyik7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

• Advantages and Disadvantages of MATLAB

• MATLAB Environment
• MATLAB Basics
▪ MATLAB: MATrix LABoratory
▪ Invented by Prof. Cleve Moler to make programming easier for his students
at the University of New Mexico in the late 1970s.
▪ MathWorks Inc. was founded by Cleve Moler and John N. Little in 1984.
(John N. Little is the son of John D.C. Little who is known for Little’s Law for
queueing models in operations research.)
▪ Matlab is a special-purpose computer programming language and
computing environment to perform engineering and scientific calculations
▪ Matrix manipulations
▪ Plotting functions and data
▪ Algorithm development
▪ User interface development
▪ Rich function library and toolkits as extensions

2
Advantages Disadvantages
▪ Ease of use
▪ It is an interpreted language
▪ Can be used as a scientific calculator
▪ Ideal for rapid prototyping of new programs ▪ Programs must be analyzed and
interpreted before being executed
▪ Platform independence
▪ Supported on different operating systems ▪ Can execute more slowly than compiled
languages
▪ Predefined functions
▪ An extensive library of functions
▪ Special purpose toolboxes (signal processing, image
▪ It is expensive for individuals
processing, neural networks, simulation, etc.)
▪ Device-independent plotting
▪ Plots and images can be displayed on any graphical
output device supported by computers
▪ Graphical user interface (GUI)
▪ Ability to design sophisticated programs that can be
operated by inexperienced users
▪ MATLAB Compiler
▪ Can compile a program into an executable program
that runs faster
3
▪ Command window
▪ Commands typed here and executed once you press Enter
▪ Command prompt (>>) appears at the beginning of new lines
▪ If a statement is too long, you can type ellipsis (…) at the end of the first line and continue on
the second line.
▪ Command history
▪ Shows list of earlier commands
▪ Earlier commands can be repeated by double clicking on them from the history
▪ Old commands can be deleted by right clicking and selecting Delete Selection

▪ Current folder
▪ Current directory of MATLAB files

▪ Workspace
▪ Collection of defined variables and arrays and their values
▪ A list of variables and arrays can be generated by typing whos command.

▪ Editor (Edit/Debug window)


▪ Where script files are created and modified

If you have changed the viewable windows in MATLAB, some of these windows will not
appear. To reset the visible windows, select HOME tab>LAYOUT>DEFAULT.
4
5
▪ Scalars
▪ a=2
▪ b=6

▪ Arrays (vectors, matrices)


▪ v=[1,2,3]
▪ m=[1,2; 3,4]
▪ Defined in square brackets

▪ Text (string)
▪ animal =‘cat’
▪ Defined in single quotes

▪ Boolean
▪ a>b
▪ 0 or 1

clc command clears the command window


clear command clears the workspace by deleting variables

6
Arrays ▪ Array is any set of numbers in a
rectangular pattern.

Matrices
▪ Matrix is a 2D array. (plural is “matrices”)

Vectors
▪ Vector is a 1D array.

Scalars

7
▪ Stores a list of commands and can be executed by simply typing their names
▪ Open a new M-file from the menu bar
▪ Type commands in the editor window
▪ Save as .m file
▪ Script file names cannot include any spaces!
▪ Make sure the folder in which you save the script file is defined as current
directory to be able to run the file.

8
▪ Select the green Run arrow from the Editor menu bar

▪ Type file name in command line

▪ Select Debug and Run from the Editor (F5 shortcut)

9
▪ Starts with the percent symbol (%)
▪ Help comments: used to explain the purpose of the script file before the
executable lines
▪ help filename.m
displays the help comments for the script file filename.m
▪ Used to explain lines of code, variables, equations, etc.

▪ The contents of a script file including the comments can be displayed by typing
▪ type filename.m

10
%MATLAB Class 1 - the starter program for IE 214
%This program is an example what NOT to do.
%It is difficult to understand the program because the variable names
%are meaningless when they do not have explanatory names.
%It would also be difficult to find errors in the statements since we
%don't recognize the equations.
A = 1
B = 1
C = pi*A^2;
D = 2*pi*A;
E = C*B
F =D*B

11
%Use the input function to get user input
EoSI = input('Enter the length units to be used: ','s');
R = input('Enter the cylinder radius: ');
H = input('Enter the cylinder height: ');
Area = pi*R^2;
Perimeter = 2*pi*R;
Volume = Area*H;
SurfaceArea = Perimeter*H;
%Use the fprintf function to generate output
fprintf('For a cylinder with radius = %0.2f and height = %0.2f \n', R, H)
fprintf(‘\t Volume = %f \n', Volume)
fprintf(‘\t Surface Area = %f \n', SurfaceArea)

12
%Get the number of cylinders from the user
N = input('Enter the number of cylinders: ');
%Calculate the volume and surface area for each cylinder
for k=1:1:N
%Use the input function to get user input
EoSI = input('Enter the length units to be used: ','s');
R = input('Enter the cylinder radius: ');
H = input('Enter the cylinder height: ');
Area = pi*R^2;
Perimeter = 2*pi*R;
Volume = Area*H;
SurfaceArea = Perimeter*H;
%Use the fprintf function to generate output
fprintf('For a cylinder with radius = %0.2f and height = %0.2f \n' , R, H)
fprintf(‘\t Volume = %f \n', Volume)
fprintf(‘\t Surface Area = %f \n', SurfaceArea)
end 13
▪ Directory issues: Change your current folder to where the file is
saved if necessary
▪ No spaces in variable or file names!
▪ Use meaningful variable names
▪ Using input to request user input
▪ , ’s’ for input of text values

▪ Repetition using for k = 1:1:N


▪ Using fprintf to generate output
▪ Format specifiers %s %f
▪ Line feed \n

▪ Tabular output using fprintf and %m.nf


14
• Initializing Variables in MATLAB • Built-in MATLAB Functions
• Arrays and Subarrays, Scalar and • Relational and Logical Operators
Array Operations
• Branches (if, switch, try/catch)
• Displaying Output Data
• Loops (while, for)
▪ While we cover the basics of MATLAB in this set of notes, follow the examples in
the companion file named IE214MATLABNotes_Examples.m

▪ Note that MATLAB variable names must begin with a letter, followed by any
combination of letters, numbers, and underscore ( _ ) character.

16
▪ MATLAB variables are created automatically when they are initialized
(no need to specify data type before assigning a value).
▪ Three common ways to initialize variables:
1. Assign data to the variable
1 2 3
▪ var = 45; array = [1 2 3; 4 5 6]; array =
4 5 6
2. Input data from keyboard
▪ in_var = input('Enter the value: ');
▪ in_var2 = input('Enter the text: ', 's');
3. Read data from file
▪ Save data from MATLAB: save IE214MATLABNotesData
▪ Read data from file: load IE214MATLABNotesData

▪ The list of variables and arrays in the current workspace and their properties
(name, size, bytes, class) can be generated by the whos command typed in the
command window after an M-file is executed.
17
▪ Multidimensional arrays can be created as follows: ▪ Size of an array can be
obtained by the size
arr23(:,:,1) = [1 2 3; 4 5 6]
function:
arr23(:,:,2) = [7 8 9; 10 11 12] >> size(arr25)
▪ Portions of arrays can be used as follows: ans =
arr24 = [1.1 -2.2 3.3 -4.4 5.5] 2 3
arr24(4) is -4.4 >> size(arr23)
arr24([2 5]) is [-2.2 5.5] ans =
▪ end function gets the highest subscript value
2 3 2
arr25 = [1 2 3; 4 5 6]
arr25(2:end, 2:end) is [5 6]

18
a = [1 5; 3 8] b = [-3 2; 4 -5]

▪ Array operations performed element-by-element


a+b = [-2 7; 7 3] a-b = [4 3; -1 13]
a.*b = [-3 10; 12 -40] a./b = [-0.3333 2.5000; 0.7500 -1.6000]
a.\b = [-3.0000 0.4000; 1.3333 -0.6250]

▪ Matrix operations follow rules of linear algebra


a*b = [17 -23; 23 -34] a/b = [-3.5714 -2.4286; -6.7143 -4.2857]

Recall matrix multiplication (inner dimensions of 𝑋 and 𝑌 must be the same):


𝑍 =𝑋∗𝑌
𝑍 𝑚, 𝑛 = ෍ 𝑋 𝑚, 𝑘 𝑌(𝑘, 𝑛)
𝑘

19
▪ The disp function requires an array input, values must be converted to string to be
displayed.
str1=['The value of pi = ' num2str(pi)];
disp(str1);
▪ The fprintf function allows string formatting and is more flexible.
fprintf('The value of pi is %6.2f \n', pi) %display as floating point
%6.2f specifies that the value of pi is a floating-point number with a field of 6 digits, including 2 digits after the decimal point.
fprintf('The value of pi is %d \n', pi) %display as integer
fprintf('The value of pi is %e \n', pi) %display in exponential format
fprintf('The value of pi is %g \n', pi) %display in either floating point or
exponential format (the shorter one)

▪ Escape characters in format strings:


\n New line
\t Horizontal tab
\b Backspace
\\ Prints a backslash (\) symbol
\' Prints a single quote (')
%% Prints a percent (%) symbol

20
▪ Mathematical functions
abs(x), mod(x), exp(x), sqrt(x), log(x), max(x), min(x)
cos(x), sin(x), tan(x), acos(x), asin(x), atan(x)
▪ Rounding functions
round(y) %round to the nearest integer
ceil(y) %round to the nearest integer towards infinity
floor(y) %round to the nearest integer towards negative infinity
fix(y) %round to the nearest integer towards zero

21
Relational Logical
Operator Operation Operator Operation
== Equal to && AND
~= Not equal to || OR
> Greater than xor Exclusive OR
>= Greater than or equal to (true when inputs differ)

< Less than ~ NOT


<= Less than or equal to

Logical
Function Purpose
ischar(a) Returns 1 if a is a character array
isempty(a) Returns 1 if a is an empty array
isinf(a) Returns 1 if a is infinite
isnan(a) Returns 1 if a is NaN
isnumeric(a) Returns 1 if a is a numeric array
22
▪ Type this to see the list: Precedence Operator
help precedence 0 Parenthesis (…)
1 Exponentiation ^ and Transpose ‘
2 Unary +, Unary -, and logical negation ~
3 Multiplication and Division
4 Addition and Subtraction
5 Colon operator :
6 Relational operators <, >, <=, >=, ==, ~=
7 Element-wise logical “and” &
8 Element-wise logical “or” |
9 Logical “and” &&
10 Logical “or” ||
23
%Solution of a quadratic equation (a*x^2+b*x+c=0):

a = input('Enter coefficient a: '); b = input('Enter coefficient b: '); c = input('Enter coefficient c: ');


discriminant = b^2-4*a*c;

if discriminant>0

disp('This equation has two distinct real roots.');

x1 = (-b + sqrt(discriminant))/(2*a);

x2 = (-b - sqrt(discriminant))/(2*a);

fprintf('x1 = %f \n',x1);

fprintf('x2 = %f \n',x2);

elseif discriminant== 0

disp('This equation has two identical real roots.');

x1 = (-b)/(2*a);

fprintf('x1 = x2 = %f \n',x1);

else

disp('This equation has two complex roots.');

real_part = (-b)/(2*a);

imaginary_part = sqrt(abs(discriminant))/(2*a);

fprintf('x1 = %f +i %f \n', real_part, imaginary_part);

fprintf('x2 = %f -i %f \n', real_part, imaginary_part);


24
end
▪ Execute a block of statements a specified number of times
%Factorial function with FOR loop
n = input('Enter an integer the factorial of which is needed: ');
n_factorial = 1;
for ii = 1:n ----------------------------→ Control Statement
n_factorial = n_factorial*ii; -------→ Body
end
fprintf('%.0f! = %.0f \n', n, n_factorial);

25
▪ Repeat a block of code as long as some condition is met

% Cylinder volume algorithm with WHILE loop


response = 'y';
while response == 'y' -------------------------------------→ Control Statement
D = input('Enter the diameter: ');
while D<=0
D = input('Enter a positive value for diameter: ');
end

Body
L = input('Enter the length: ');
Volume = pi*(D/2)^2*L;
fprintf('\n Diameter = %.2f, Length = %.2f, Volume = %.2f \n', D,L,Volume);
response=input('Do you wish to continue? (y or n): ', 's');
end

26
▪ Give your variables unique and descriptive names
▪ Must begin with a letter
▪ No spaces allowed
▪ Size of subarrays used in both sides of assignments must match.
▪ Use an array as the argument of the disp function.
▪ The fprintf function displays only the real part of complex
numbers and this can produce misleading answers when working
with complex values.
▪ Be careful about the differences between array operations and matrix
operations.
▪ Be careful not to confuse the equivalence relational operator (==)
with the assignment operator (=).
▪ Do not modify the value of a loop index inside the loop.

27
• Top-down Design (Decomposition) • Preserving Data between Function
Calls
• Functions
• Function Functions
• Variable Passing
• Subfunctions and Private Functions
• Optional Arguments
▪ Given a large task, break it down to smaller subtasks that perform a part of the
desired task.
▪ Follow this general procedure for decomposition:
1. State the problem clearly
2. Define the inputs required and outputs to be produced
3. Design the algorithm with pseudocode (a mix of code and descriptions)
4. Convert algorithm into MATLAB statements
5. Test the algorithm

▪ MATLAB has a special mechanism to make subtasks easy to develop


independently: FUNCTIONS
▪ Functions:
▪ are reusable
▪ can be independently tested
▪ avoid the danger of programming mistakes in other parts of the program

29
▪ MATLAB functions
▪ Receive input through an input argument list
▪ Return results through an output argument list

function [outarg1, outarg2, ...] = fname(inarg1, inarg2, ...)


%H1 comment line: should be a one-line summary of function purpose
%Other comment line(s): to contain a brief summary of how to use
the function
...
(Executable code)
...
(return)

30
▪ Use meaningful names that help understand what the
function does.
▪ Do not use existing Matlab function names such as sum,
sqrt, plot, etc.
▪ Check whether a function name is already used by typing this in
the Command Window:
help exist
and then:
exist(‘sum’)

31
▪ MATLAB programs communicate using a %Test function sample:
pass-by-value scheme a = 2; b = [6, 4];
▪ When a function is called, the actual
fprintf('Before sample: a = %.0f, b = %.0f %.0f\n', a, b);
arguments are copied and passed to the
function. out = sample(a,b);

▪ The original data is not affected even if the fprintf('After sample: a = %.0f, b = %.0f %.0f\n', a, b);

arguments are modified by the function. fprintf('After sample: out = %.0f\n', out);

function out = sample(a,b)

fprintf('In sample: a = %.0f, b = %.0f %.0f\n', a, b); Before sample: a = 2, b = 6 4

a = b(1) + 2*a; In sample: a = 2, b = 6 4

b = a .* b; In sample: a = 10, b = 60 40

out = a + b(1); After sample: a = 2, b = 6 4

fprintf('In sample: a = %.0f, b = %.0f %.0f\n', a, b); After sample: out = 70

32
▪ You can read and write MS Excel files:
▪ [num, text, raw] = xlsread(‘filename.xlsx’);
▪ xlswrite

▪ You can open and close text files:


▪ fid = fopen(filename, permission)
▪ fclose(fid)
▪ Permission can be reading (‘rt’), writing(‘wt’), reading and writing
(‘r+t’), etc.

33

You might also like