MATLAB Guide
MATLAB Guide
1 Introduction
MATLAB (Matrix Laboratory) is a powerful programming language widely used
in engineering, mathematics, and numerical computing. This guide will help you
quickly start using MATLAB for numerical methods.
1
2.3 Getting started
The MATLAB interface consists of:
• Command Window: Directly execute commands.
2
3.2 Defining a Function as a script
Functions in MATLAB are defined using the function keyword. Create a script
in the Editor and save it as myFunction.m:
1 function y = myFunction ( x )
2 y = x ˆ2 + 2∗ x + 1 ;
3 end
Call it in the command window:
1 >> r e s u l t = myFunction ( 3 ) ;
2 >> d i s p ( r e s u l t ) ;
5 Debugging in MATLAB
To debug:
• Use dbstop if error to pause at errors.
• Add breakpoints in the Editor.
• Step through code using the Debug toolbar.
3
6 Number Precision and Formatting
MATLAB operates in double precision by default. Formatting options:
• Default: format short
• Full precision: format long
• Scientific notation: format short e or format long e
7 Arrays in MATLAB
MATLAB works efficiently with arrays. Example: plotting sin(x) and cos(x)
over 0 ≤ x ≤ 10:
1 t = 0:0.1:10;
2 x = cos ( t ) ; y = sin ( t ) ;
3 plot ( t , x , t , y ) ;
7.1 Vectors/arrays
A row vector is created using:
1 >> R = 1 : 5
which results in:
R= 12345
It is transformed to a vertical array (column) using the transpose operation:
1 >> V = n ’
which results in:
1
2
3
V =
4
5
4
8 Array Operations
• Addition: C = A + B
• Scalar multiplication: D = 2 ∗ A
• Matrix multiplication: G = E ∗ F
9 Special Arrays
MATLAB provides built-in functions for generating special matrices:
1 zeros ( 2 , 3 ) % 2 x3 z e r o m a t r i x
2 ones ( 2 , 3 ) % 2 x3 m a t r i x f i l l e d w i t h ones
3 eye ( 3 ) % 3 x3 i d e n t i t y m a t r i x
10 Array Functions
MATLAB has functions that operate on arrays:
• max(x) - Maximum element of x
• min(x) - Minimum element of x
5
11 Numerical Methods in MATLAB
11.1 Bisection Method
Finding the root of f (x) = 0 by iteratively dividing an interval in half.
xn+1 = g(xn )
6
11.3 Newton-Raphson Method
Given an initial guess x0 , keep refining the root iteratively as:
f (xn )
xn+1 = xn −
f ′ (xn )
7
13 Practice Exercises
13.1 Basic MATLAB Commands
Exercise 1: Compute the following using MATLAB.
√
1. Compute 25 + 50.
2. Find the sine and cosine of 30◦ (convert degrees to radians).
3. Define a variable x = 10 and compute y = x2 + 3x − 5.
4. Add labels for the x-axis and y-axis, a title, and a legend.