Module (1): Introduction to MATLAB

Module (1): Introduction to MATLAB

MATLAB: [Matrix] [Laboratory]

 

1.    MATLAB User Interface



Command Window

The Command Window is one of the main tools you use to enter data, run MATLAB functions and other M-files, and display results. 

The Command Window prompt, >>, is where you enter statements. You can enter a MATLAB function with arguments or assign values to variables.

For example, 1+2,

ans = 3.

 

Workspace Window:

Contains any variables generated as the result of working in the Command window. In this case, the Workspace window contains a variable named ans that holds a value of 3.

 

Current folder Window

Contain saved MATLAB files.

 

Command History window: 

Using Up-Down Arrows at your keyboard, you can show this widow that displays the series of formulas or commands that you type, along with the date and time you typed them. You can replay a formula or command in this window. Just select the formula or command that you want to use from the list to replay it.

 





 

2.    Saving the workspace results in MATLAB

The workspace is not maintained across sessions of MATLAB®. When you quit MATLAB, the workspace clears. However, you can save any or all the variables in the current workspace to a MAT-file (.mat).

You can then reuse the workspace variables later during the current MATLAB session or another session by loading the saved MAT file.

 

There are several ways to save workspace variables interactively:

1)    To save all workspace variables to a MAT-file, on the Home tab, in the Variable section, click Save Workspace.

2)    To save a subset of your workspace variables to a MAT-file, select the variables in the Workspace browser, right-click, and then select Save As. You also can drag the selected variables from the Workspace browser to the Current Folder browser.

3)    To save variables to a MATLAB script, click the Save Workspace button or select the Save As option, and in the Save As window, set the Save as type option to MATLAB Script. Variables that cannot be saved to a script are saved to a MAT-file with the same name as that of the script.



 

3.    Saving the Command window in MATLAB

To save the contents of your Command Window to PDF. Right-click on the Command Window bar, and then Print.

Alternatively, copy and paste the commands into an editable file.

 





 

4.    OCTAVE User Interface

If you don’t have access to MATLAB for practicing, you can download OCTAVE. It is a powerful open-source (free) and has almost the same platform as MATLAB.

To download it, please follow this link https://www.gnu.org/software/octave/

  


 


5.    Some Useful Commands in MATLAB

help: Display help text in Command Window.

doc: Opens the Help browser if it is not already running and otherwise brings the Help browser to the top.

clear: Removes all variables from the workspace.

clear AII: Removes all variables, globals, functions and MEX links.

home: Moves the cursor to the upper left corner of the window. It also scrolls the visible text in the window up out of view; you can use the scroll bar to see what was previously on the screen.

clc: Clear command window.

who: Lists the variables in the current workspace..

whos: is a long-form of WHO.  It lists all the variables in the current workspace, together with their size, bytes, class, etc..

 


 

6.    How to work with mathematics in MATLAB

Basic Arithmetic functions in MATLAB



List of Commonly Used Operators





Practice-1

>> x=10;

>> y=2;

>> z1=x+y

z1 =12

>> z2=x-y

z2 =8

>> z3=x*y

z3 =20

>> z4=x/y

z4 =5

>> z5=x\y

z5 =0.2000

>> z6=y-x

z6 =-8

>> A1=abs(z6)

A1 = 8

Practice-2

>> x=4.454

x =4.4540

>> floor(x)

ans =4

>> ceil(x)

ans =5

>> round(x)

ans =4

>> round(x,1)

ans = 4.5000

>> round(x,2)

ans =4.4500

>> y=315.214

y = 315.2140

>> round(y,-1)

ans = 320

>> round(y,-2)

ans = 300

>>sqrt (x)

ans = 2.1105


 

7.    Formatting in MATLAB

Format command can be used to set the output format to the default appropriate for the class of the variable.

format long: Scaled fixed point format with 15 digits.

format short: Scaled fixed point format with 5 digits.

format bank: Fixed format for dollars and cents.


8.    Symbolic and Numeric in MATLAB

In MATLAB, you can construct symbolic numbers using the command (sym), and you can return them to scalar using the command (double).






You can also construct symbolic variables and objects using command syms x. For more than one variable, leave a space between them.

You can also use the function pretty to present the answer in a pretty way.


 


9.    Vectors and Matrices in MATLAB

Creating Vectors in MATLAB

Vectors can be created horizontally using the following commands and functions

>> A=[1 2 3 4 5]                or       A=[1,2,3,4,5]

A =1     2     3     4     5

 

>> A=[1:5]

A =1     2     3     4     5

 

>> D=[1:2:5]

D =1     3     5

 

>> A=linspace(1,5,5)

A =1     2     3     4     5

 

>> linspace(1,10,3)

ans =1.000000000000000   5.500000000000000  10.000000000000000

 

>> A=rand(1,8)                 %to create 1 raw and 8 columns (0-1) randomly

A =0.4173    0.0497    0.9027    0.9448    0.4909    0.4893    0.3377    0.9001   

 

>> A=500*rand(1,7)

A =390.1260  194.8694  120.8456  201.9561   48.2273   65.9866  471.0253 

 

>> A=round(500*rand(1,10))

A =117   177   411     8    22    84   325   366   324   225

 

Note: if you want to create random numbers between two values, the following formula can be used: A=round(low +(up-low)*rand(m,n))

[Example: 5 integers from 100-500]

 

>> A=round(100+(500-100)*rand(1,5))

A =117   477   411   325   266


 

 

Vectors can be created vertically using the following commands and functions

>> a=[1;2;3;4;5]

a =

     1

     2

     3

     4

     5

 

 

>> a= [1:2:10]'

a =

     1

     3

     5

     7

     9

 

MATLAB can reshape an array into a specific size. So, it can be used to make arrays only verticals or horizontal using

reshape(X,M,N)

       Where X is the array, M is the number of rows wanted, and N is the number of columns needed

Example

       Write a MATLAB syntax that convert (X) horizontal array to a vertical one, and do nothing for vertical arrays.

       Here, the column=1, and rows should be any numbers according to the array size, then the syntax should be: reshape(X,[],1)

>> X=[1:5]

X =  1.00          2.00          3.00          4.00         5.00

>> Y=reshape(X,[],1)

Y =

1.00

2.00

3.00

4.00

5.00

Another functional syntax is     Y=x(:)


 

Example

       Write a MATLAB syntax that converts (X) vertical array to a horizontal one and does nothing for horizontal arrays.

       Here, the rows=1 and columns should be any numbers according to the array size. Then the syntax should be: reshape(X,1,[])

>> X=[1:5]’

X =

1.00

2.00

3.00

4.00

5.00

>> Y=reshape(X,1,[])

Y =  1.00          2.00          3.00          4.00    5.00

 

 


 

Creating Matrices in MATLAB

Matrices can be created using the following commands and functions

>> a=[1 2 3 4 5]; b=[2 3 1 4 5]; c=[1 0 3 2 4];

>> d=[a;b;c]

d =

     1     2     3     4     5

     2     3     1     4     5

     1     0     3     2     4

 

>> A=[1 2 3;4 5 6;7 8 9]

A =

     1     2     3

     4     5     6

     7     8     9

 

Special matrices can be also created using the following commands and functions

>> ones(3)

ans =

     1     1     1

     1     1     1

     1     1     1

 

>> ones(3,2)

ans =

     1     1

     1     1

     1     1

 

>> zeros(2)

          ans =

     0     0

     0     0

 

>> eye(3)

ans =

     1     0     0

     0     1     0

     0     0     1


 

Extracting, Replacing or Eliminating an element or more from Arrays and  Matrices

In order to extract an element or array from vectors or  matrices; the following commands and functions can be executed A(Row number, Column Number)

 

>> A=[1 2 3; 4 5 6; 7 8 9]

A =

     1     2     3

     4     5     6

     7     8     9

 

>> A(2,3)     

ans =6

 

>> A(2)

ans =4

 

>> A(2,:)

ans = 4     5     6

 

>> A(:,1)

ans =

     1

     4

     7

>> A(3,1:2)

ans = 7.00          8.00

 

In order to extract a small matrix from a larger one, for example to extract [2 3; 5 6]:

 

>> A=[1 2 3; 4 5 6; 7 8 9]

A =

     1     2     3

     4     5     6

     7     8     9

 

>> A(1:2,2:3)

ans =

          2.00          3.00

          5.00          6.00

 


 

Changing a vector in MATLAB

If you want to change a value of a vector in an array or a matrix, you can double click in the workplace; this will open a window contains all variables, so you can change the value you want.




In order to replace an element or array in a vectors or matrix

 

>> A=[1 2 3; 4 5 6; 7 8 9]

A =

     1     2     3

     4     5     6

     7     8     9

 

>> A(1:2,2:3)=0

A =

     1     0     0

     4     0     0

     7     8     9

 

In order to remove elements from an array, [] can be used as follows

>> A=[1 2 3 4 5]

 

A = 1.00          2.00          3.00          4.00          5.00

 

>> A(2)=[]

 

A = 1.00          3.00          4.00          5.00


 

10.      Some useful commands in Matrices and Vectors

Find: To find the location of a vector

A =

     1     2     3

     4     2     5

     2     8     1

 

>> find(A==2)

ans =

     3

     4

     5

 

>> find(A==5)

ans =8

 

Sort: To sort the vectors of each column.

A =

     1     2     3

     4     2     5

     2     8     1

 

>> sort(A)               %ascending by default

ans =

     1     2     1

     2     2     3

     4     8     5

 

>> sort(A,'ascend')

ans =

 

     1     2     1

     2     2     3

     4     8     5

 

>> sort(A, 'descend')

ans =

     4     8     5

     2     2     3

     1     2     1

 

numel, length, size: To calculate the number of vectors, length of vectors, and size of a matrix.

A =

     1     2     3

     4     2     5

     2     8     1

 

>> numel (A)

ans =9

         

>> length (A)

ans =3

>> size(A)

ans = 3     3

 

 


 

11.      Some Useful Statistical Commands

A =

     1     2     3

     4     2     5

     2     8     1

 

To find the min for each column.

>> min(A)

ans =1     2     1

To find the minimum value in a matrix

>> min (min(A))

>> min(A(:))

>> min(A, [], 'all') % Starting in R2018b

ans =1

 

To find the max for each column.

>> max(A)

ans = 4     8     5

 

To find the maximum value in a matrix

>> max (max(A))

>> max(A(:))

>> max(A, [], 'all') % Starting in R2018b

 

 

To find the mean in a matrix

>> mean(A)

>> mean(A(:))

 

To find the median in a matrix

>> median(A)

>> median(A(:))

 

To find the standard deviation in a matrix

>> std(A)

>> std(A(:))

 

To find the variance in a matrix

>> var(A)

>> var(A(:))

 

To find the correlation coefficient in a matrix

>> corrcoef (A)

>> corrcoef (A(:))

12.      Mathematical Operations in Arrays/Matrices in MATLAB

The absolute value of the elements

 

>> A=[1 2 3;-4 5 6; 7 8 -9]

A =

     1     2     3

    -4     5     6

     7     8    -9

 

>> abs(A)

ans =

     1     2     3

     4     5     6

     7     8     9

 

 

Trigonometric functions of the matrix

 

>> cos(A)

ans =

          0.54         -0.42         -0.99

         -0.65          0.28          0.96

          0.75         -0.15         -0.91

 

>> sin(A)

ans =

 

          0.84          0.91          0.14

          0.76         -0.96         -0.28

          0.66          0.99         -0.41

 

 

>> log(A)

ans =

          0.00          0.69          1.10

          1.39          1.61          1.79

          1.95          2.08          2.20

 

The root of the matrix

 

A =

          4.00          9.00         16.00

          8.00         27.00         64.00

 

>> sqrt(A)

ans =

          2.00          3.00          4.00

          2.83          5.20          8.00

 

 

>> nthroot(A,2)

ans =

          2.00          3.00          4.00

          2.83          5.20          8.00

 

 

>> nthroot(A,3)

ans =

          1.59          2.08          2.52

          2.00          3.00          4.00

 

 

Multiplication of arrays and matrix

A =

4.00          9.00         16.00

8.00         27.00         64.00

 

>> 2*A

ans =

8.00         18.00         32.00

16.00         54.00        128.00

 

>> A/2

ans =

2.00          4.50          8.00

4.00         13.50         32.00

 

 

Note the following command

>> A=[1 2 3]; B=[4 5 6];

>> A*B

Error using *

Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise multiplication, use '.*'.

 

The number of columns in the first matrix should match the number of rows in the second matrix.

 

 

Write the following command

>> A=[1 2 3]; B=[4; 5; 6];

>> A*B

ans =32.00

 

Why??, Because it is (1*4+2*5+3*6)=32

 

So, in order to perform it, you run the following commands

 

>> A*B'        %Transpose

ans =32.00

or

>> dot(A,B)

ans =32.00

If you want to perform a Cross Product, run the following commands

 

>> cross(A,B)

ans = -3.00          6.00         -3.00

 

If you want one by one multiplication then.

Write the following commands

>> A=[1 2 3]; B=[4; 5; 6];

>> A.*B

ans =

4.00          8.00         12.00

5.00         10.00         15.00

6.00         12.00         18.00

 

Write the following commands

>> A=[1 2 3]

A =

1.00          2.00          3.00

 

>> B= [2 4 6]

B =

2.00          4.00          6.00

 

>> A.*B

ans =

2.00          8.00         18.00

>> A.^B

ans =

1.00         16.00        729.00

 

 

LU: To find the Lower triangular  and upper triangular matrices for a matrix.

 

 


 

13.      Input/output functions

Input function prompts the user for values directly from the command window. and its syntax is

n=input(‘promtstring’)

Similarly, the output can be displayed as a value or a string, and its syntax is

disp(variable)

disp(‘string’)

 

if you want to combine both string and variable or value in the same line, you can write the syntax as  

disp([‘string’ , num2str(variable)])

 

Practice

 

Can you calculate the area of a circle, where the diameter is an input variable? Properly display the results.

 

>> x=input('Insert the Circle Diameter: ');

Insert the Circle Diameter: 5

>> A=pi*x^2/4;

>> disp(['The area is: ' ,num2str( A)])

The area is: 19.635

 

 

 

 

Another valuable way to display several strings and values is by using the function fprinf  

 

>> fprintf('The Area of the Circle is %f cm \n', A)

The Area of the Circle is 19.634954 cm

>> fprintf('The Area of the Circle is %0.2f cm \n', A)

The Area of the Circle is 19.63 cm

>> fprintf('The Area of the Circle is %0.0f cm \n', A)

The Area of the Circle is 20 cm

 

Notes:

 

%s                →                 print a string

%c                →                print a single character

%d                →                print a whole number

%f                 →                 print a floating point number

%0.2f            →                 print a number with two decimal

%0.1f            →                 print a number with one decimal

%0.0f            →                 print a number with no decimal (as Integer)

 

\n                  →                 print a new line (go to the next line to continue printing)

 

 

msgbox

msgbox is a display tool to display a message in a box

msgbox(‘Good Morning’)

 

error

error can be used also to display a massage with a notification sound

error('Good morning')


 

14.      Plotting

Plot, xlabel, ylabel, title

You can plot X vs Y and put titles for the axis using these function





You can also change the line style



You can change the line color and style


 

Color

Description

y

yellow

m

magenta

c

cyan

r

red

g

green

b

blue

w

white

k

black

Line Style

Description

-

Solid line (default)

--

Dashed line

:

Dotted line

-.

Dash-dot line

Marker

Description

o

Circle

+

Plus sign

*

Asterisk

.

Point

x

Cross

s

Square

d

Diamond

^

Upward-pointing triangle

v

Downward-pointing triangle

> 

Right-pointing triangle

< 

Left-pointing triangle

p

Pentagram

h

Hexagram

 

Subplot

If you want to have more than one plot in the same page, then the subplot can be used

subplot(number of rows, number of columns, location of figure)

Scale limits

To assign limits for x and y axis, you can use the functions ylim and xlim

ylim([min max])

xlim([min max])

 

Grid

To add gird to your plot

grid on

To remove gird from your plot

grid off

 

End of This section

No comments:

Post a Comment

Welcome to Practical Numerical Methods for Scientists and Engineers. This Blog contains modules that cover numerical methods topics Module (...