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

MATLAB TUTORIAL 2023

Uploaded by

sri.srikarthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

MATLAB TUTORIAL 2023

Uploaded by

sri.srikarthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

MATLAB TUTORIAL 2023

1.BASICS
1. MATLAB statements are
 expressions or assignments,
 variable declarations ,
 operations with variables,
 input- or output-instructions,
 control flow statements or function calls,
that perform specific tasks (plots, mathematical
computations etc.).

2. MATLAB statements can be terminated with a semicolon or


not. If terminated with a semicolon, a statement will not
generate any output in the command window.

1.A)COMMANDS FOR CLEARING , FORMATTING & HELP


Before starting to explore the MATLAB language, some
commands that are needed frequently to keep a clean and
organized workspace and command window.
 clear – Clears workspace variables. You can delete selected
variables or all variables. Useful when you run multiple scripts
that use the same variable names.

 clc – Clears command window (instructions and output). Useful


when you want to start over with your script and do not need
previously used commands or output.

 close all – Closes all open figures.

 format compact – Compactifies the command window output.


More generally, the format command is used for formatting.
For example format long changes the display of all floating
point numbers in the command window to double precision.
format short e is used for short scientific formatting.

 help – If you type help followed by the name of a command or


function, the corresponding help page is displayed.

1
1.B)INTERACTIVE MODE ="Hello World" Program in MATLAB
 A "Hello World" program is the smallest executable program in
a programming language and prints the text "Hello World" to
default output (here: the command window).
 We do it first in interactive mode and then in a script.

In interactive mode, we use only the command window.


Statements are entered next to the command prompt (indicated
by >>) and executed using ENTER.

1.C)SCRIPT MODE
In script mode, we first create a new script with the name
"test_hello.m", then type the MATLAB statements below in the
script file and save it, and finally execute the script by clicking the
"RUN"-Button.

Code Explanation
 The code starts in line 1 with a comment (indicated by "%"-
symbol), that states the name of the script file.

2
 Note that the following lines are also commented. In lines 2 and
3 we insert code for resetting / preparing workspace and
command window.
 In line 4 we create a new variable "text" and assign it the value
'Hello world'.
 In line 5 we print the string 'Hello World' using disp().
% Script: test_hello.m
clear;clc; % Clear workspace and command window
format compact % Compactify command window output
text = 'Hello World'
disp('Hello World!');

1.D)COMMENTS
 Comments in MATLAB start with a "%"-symbol followed by text.
 Comments are used for documentation purpose, they are not
executed by the system.
 Two percent-symbols "%%" mark a section.
 Sections can be executed separately using the RUN SECTION-
Button.

3
%% Section 1
% Comment 1: This is the first comment for section 1.
text = 'Let''s start simple' % Here we assign a value to the
variable named text
%% Section 2
% Comment 2: This is the first comment for section 2.
a = 10 % Here we assign a value to variable a
b = 20 % Here we assign a value to variable b

1.E)VARIABLES & DATA TYPES


1. Variables are named memory spaces that store the data of
your program.
2. MATLAB variables are declared by simply assigning a value to
them.
3. The data type (number, string, array etc.) is assigned
automatically by MATLAB.
For example, all numbers (integer, floating points) are stored
internally as double precision floating point numbers.
1. Knowing the data type is important, since the data type
determines the set of operations that you can perform with
your variables.
For example, you can add two numbers or concatenate two
strings with the "+"-operation as in the example below, but it is
not possible to add a number to a string: sum = a + " apples" is
an invalid statement.
2. Before appending a number to a string, it must be converted
to a string using num2string: sum = num2string(a) + "
apples" is a valid statement.
Code explanation:
 Line 2: Declare two variables a, b by assigning values to them.
Since the declarations are terminated with semicolon, output of
the variables to the command window is suppressed.
 Line 3: Add the two variables (actually, their values) and store
the result in the variable sum.
 Line 4: Declare two string variables s1, s2.
 Line 5: Concatenate the strings to form a new string.
 Line 6: Replace the "+"-character with the string ' or '.

4
% test_variables.m
a = 10; b = 20.5;
sum = a + b
s1 = "apples";s2 = "pears";
text1 = s1 + "+" + s2
text2 = replace(text1, '+',' or ')

1.F)DATA TYPES
MATLAB supports different data types, that are represented by
classes:
 Numerical data types: int, single, double
 Boolean data types: logical
 String data types: string, char
In order to find out the exact data type and size of your variables,
use the commands whos, class. With whos, you can find out size
and type of workspace objects. With class, you can find out the
data type of a variable.
Code Explanation : We declare two variables a and b by
assigning numeric values, 10 and 20.5 respectively. Then show
information about them using whos.
a = 10;
b = 20.5;
whos a
whos b

5
1.G)STRING VARIABLES
 String variables in MATLAB can be either of class "string" or of
class "character array".
 When you create a string using single quotes, it is stored as
character array.
 When you create a string using double quotes, it is stored as a
string.
 A character array is a sequence of characters, just as a numeric
array is a sequence of numbers.
 The String class provide a set of functions for working with text
as data.
text1 = "Hello"
whos text1
text2 = 'from Kaiserslautern'
whos text2

2.INPUT & OUTPUT COMMANDS


Data stored in variables can either be viewed in the workspace or
displayed in the command window. While the workspace shows
the raw variable values, the command window is used for
formatted output.
2.A) OUTPUT TO COMMAND WINDOW

6
There are three ways to output variable values to command
window.
 Type the name of a variable in a new line, with no terminating
semicolon.
 In an assignment statement, omit semicolon at the end of a
statement.
 The content of the variable then is displayed in the command
window.
 Use disp()-function. This function takes as argument a variable
/ vector / matrix and displays it, omitting the name of the
variable.
 Use fprintf()-function. This function builds a formatted output
by using placeholders for the variables to be inserted.
In our example, the value of variable a will be inserted in the
place indicated by the first "%d", the value of variable b will be
inserted in the place indicated by the second "%d" etc.
Example : calculate the sum of two variables and generate
output in the command window.
% test_output.m
a = 10; b = 20; sum = a + b;
% (1) No semicolon
disp('(1) Output by typing variable name')
sum % output: sum = 30
% (2) Use disp
disp('(2) Output using disp()')
disp([a b sum]) % output: 10 20 30
% (3) Use fprintf for formatted output
disp('(3) Output using fprintf')
% output: a = 10, b = 20, Sum = 30
fprintf('a = %d, b = %d, Sum = %d\n', a, b, sum)

7
2.B)INPUT WITH input()
 When presenting a MATLAB script to non-technical users, it
may be helpful to let them enter configuration parameters as
input from the command window or an input dialog.
 Input entered in the command window can be stored in
variables using the input()-function.
Example : Input using prompt.
% Display a prompting text
prompt = 'Enter a: ';
% Read input
a = input(prompt);
prompt = 'Enter b: ';
b = input(prompt);
sum = a + b;
fprintf("Sum = %.2f\n", sum);

2.C)INPUT DIALOG
An input dialog as shown below is created using the MATLAB-
function inputdlg. We pass four arguments to the function:
 prompt -- the labels of the input fields
 dlgtitle -- the title of the dialog
 windowsize -- the size of the window
 definput -- specifies the default value for each edit field.

8
The definput argument must contain the same number of
elements as prompt.
The function returns an array of strings "answer", that contains
the values entered in the edit fields.
Example :Input dialog for two variables.
prompt = {'Enter a:', 'Enter b:'};
dlgtitle = 'Input';
windowsize = [1 50];
definput = {'10','20'};
answer = inputdlg(prompt, dlgtitle, windowsize, definput)
a = str2num(answer{1})
b = str2num(answer{2})

2.D) INPUT FROM FILES


1. Many applications require to read tabular data from *.txt, *.csv
or *.xlsx files, or binary data (images).
2. For this type of requirement, MATLAB offers functions such as
inputdata, readtable and load.
3. They all require as input a file, specified by its name including
the path, and return an internal representation of the data,
either as table or as struct or array.
4. If only the filename is specified, MATLAB searches for a file in
the same folder where the script is placed.
5. Alternatively, it is possible to specify the full path to the file, for
example 'C:\temp\accidents.csv'.
6. Note that when importing from Excel, the row and column
headers should be specified correctly.

9
7. Also, it is important to use the correct delimiters for the
decimal point, in a computer with German settings, this will be
comma (,), else dot (.).

 A = importdata(filename, delimiter) loads data into array


A. This function is used for importing tabular data as well as
images.
 T = readtable(filename, options) reads tabular data from a
file and stores it internally in a table object. This function is
useful when you have spreadsheet-like data as in an excel-
sheet, where each column has its own data type. Column
headers are imported (or not) by specifying the options
'ReadVariableNames' and 'PreserveVariableNames'.
 T = load(filename) loads variables or data from a file into
workspace: if the file is a *.mat-file, then in loads the variables
from this file, else if it is a text-file, it loads the data into a
double-precision array.

When developing a numerical method, it is often required to


convert the table object returned by importdata into an array or
extract single columns or rows of the imported table into a
column vector. This is done by using the function table2array as
in the next example.
Example: Importing data from files
Using importdata, readtable and load
For this example we use two input files, accidents_5.csv and
accidents_5.xlsx, that we store in the same folder as our test
script. The csv-file contains number-only entries separated with
semicolon and has no headers. The Excel-file contains the same
data as the csv-file, but with headers.
%% Load data using importdata
% (1) Load data using importdata
A1 = importdata('accidents_5.csv', ';')
% (2) Alternatively: Use readtable
T = readtable('accidents_5.xlsx', 'ReadVariableNames', true)
% Convert the table into an array
A = table2array(T(2:end, 1:end))
% Extract the second row
10
row2 = A(2,:)
% (3) Alternatively: Use load
A2 = load('accidents_5.csv')

%% Find out the type of the returned objects


whos T % It's a table
whos A1 % It's an array
whos A2 % It's an array

11

You might also like