Sie sind auf Seite 1von 7

# ME310 - Matlab Tutorial

ME 310
Useful Matlab Commands

## Prepared By : Hakan Mencek (C-206)

In this tutorial, some of the useful Matlab commands are listed and basic programming using m-files are
explained. Note that it is not possible to list all commands of Matlab. If another function or command
is required, help commands listed in Section 2 should be used.

1 Basic Commands

##  clear : clear variables and functions from the workspace

 ctrl + c : stop the execution of Matlab (press control and c keys simultaneously)

 % : comment

2 Getting Help

##  F1 : pressing F1 key opens the matlab help user interface

 help : display help topics in command window. General help topics are listed in Table 1. These
keywords are used to list the commonly used functions related to the subjects. Execute help
keyword command to see the related functions

## Table 1: Help keywords and their descriptions

Keyword Description
general General purpose commands
ops Operators and special characters
lang Programming language constructs
elmat Elementary matrices and matrix manipulation
elfun Elementary math functions
specfun Specialized math functions
matfun Matrix functions - numerical linear algebra
polyfun Interpolation and polynomials
scribe Annotation and Plot Editing
graph2d Two dimensional graphs
graph3d Three dimensional graphs

##  help function : display help for function

Page 1 of 7
ME310 - Matlab Tutorial

3 Variable Declaration

## 3.1 Single Variables

 a = 4⇒a=4

 b = cos(0) ⇒ b = 1

3.2 Vectors/Arrays
 a = [1 5 7 8] ⇒ a = 1 5 7 8

 b = 1 : 5⇒b = 1 2 3 4 5

## Elements of an array variable can be extracted via parantheses ( c(3) = 2.0000 ) 1

3.3 Matrices
 
1 5
 A = [1 5 ; 7 8] ⇒ A =
7 8
 linspace(x1,x2,N) : generates N equally spaced points between x1 & x2

##  eye(n) : n×n identity matrix

 transpose(A) or A’ : transpose of A

##  size(A) : display the dimensions of a vector or a matrix

Element extraction from a matrix is similar to vectors. As an example consider the following commands.

## >> A = [1 2 3 4; 5 6 7 8; 9 10 11 12] % 3x4 matrix declaration

A =
1 2 3 4
5 6 7 8
9 10 11 12

>> A(2,3) % extracting the element of A at the 2nd row and 3rd column
ans =
7

## >> A(:,2) % extracting 2nd column

ans =
2
6
1
Note that unlike C language, arrays start from 1 in Matlab

Page 2 of 7
ME310 - Matlab Tutorial

10

ans =
9 10 11 12

## >> A(2:3,3:4) % extracting a sub matrix of A

ans =
7 8
11 12

Matlab software has two different types of arithmetic operations as matrix operations and element
by element (array) operations. These two operations are distinguished by period (.) character.

## C = A * B % Matrix multiplication of A and B matrices

% C(1,1) = A(1,1)*B(1,1) + A(1,2)*B(2,1)
C = A . *B % Element by element multiplication of A and B matrices :
% C(1,1) = A(1,1)*B(1,1)

##  title(),xlabel(), ylabel() : annotate the graph

 hold on/off : hold current plot in order to add more graph to this plot

## t = −pi : 0.05 : pi; % defining the plotting range

hold on
plot(t,sin(t),'.k') % plotting sin(x)
plot(t,cos(t),'−r') % plotting cos(x)
hold off
xlim([−3 3]); % adjusting x and y limits of the plot
ylim([−1.2 1.2]);
grid % adding grids to the plot
title('Variation of Sin(x) and Cos(x) wrt x'); % adding title to the plot

5 Script/Function Development

In Matlab, a convenient way of developing programs is using m-files instead of command window. edit
command opens the m-file editor. Scripts or functions can be develop by this editor. Scripts are pro-
grams, which do not require any inputs. In addition, they cannot give any output at the end of the
program. However, in general, functions need some input parameters and can output some results to

Page 3 of 7
ME310 - Matlab Tutorial

other programs. Another important difference is that, the variables in scripts are not cleared unless spec-
ified by the user. On the other hand, declared variables in functions are removed after the termination
of the function. In order to define a function following syntax should be used.

## function [out1,out2,out3] = fun1(input1,input2)

... % 2 input / 3 output function declaration
end

This function should be saved in the working directory of Matlab with the function name in order to run
properly. Then, fun1 can be called similar to built-in functions in Matlab.

It is possible to write more than one functions in an m-file. In this case, the upper function becomes
the main function and it can be called from command window. However, the remaining functions below
become local functions and cannot be called outside this m-file.

## function [out1,out2,out3] = fun1(input1,input2)

... % main function
end
function out4 = fun2(input3)
... % sub−function 1
end
function out5 = fun3(input4)
... % sub−function 2
end

Here, main function fun1 can be called from command window and from other m-files. But sub-functions,
fun2 & fun3 can only be used in this m-file. fun1 can use these functions and fun2 and fun3 can also call
each other. These sub-functions cannot be used by other m-files. Because these functions are cleared
once the main function is terminated similar to other local variables in a function. Note that the name
of this m-file should be fun1.m in order to run properly.

##  if : conditionally executes a statement. Conditional operations are listed below

1. == : equal to
2. >, >= : greater than, greater than or equal to
3. <, <= : less than, less than or equal to

satisfied

## Example usage of for loop with if structure is given below.

Page 4 of 7
ME310 - Matlab Tutorial

## for i=1:1:10 % this loop is executed for values of i from 1 to 10

if i ≥ 5 % if condition, satisfied for values of i greater than or equal to 5
b = −1*i;
elseif i==2 % elseif condition, satisfied if i is equal to 2
b=20;
else % else statement, if other conditions are failed, the statements
b=i; % in else block are executed
end
b % print b to the command window
end

## 7.1 Reading from and Writing to Command Window

 input : ask for a user input

% Asks for user input and assign the given value to variable a
>> a = input(['Please enter a number : '])
Please enter a number : 5.5
a =
5.5000

##  disp : display a string in the command window

% script
a = input('Enter a number to calculate its square root: ');
b = sqrt(a);
disp(['the square root of ' num2str(a) ' is ' num2str(b)]);
% output
Enter a number to calculate its square root: 20
the square root of 20 is 4.4721

Note that, in order to display a numerical variable using disp command, this number should be converted
to a ‘string’. This conversion be performed by num2str() function.

## 7.2 Reading from and Writing to a File

 FID = fopen(filename,permission) : Open a file from a specified directory with given
permission and assign it to a file ID.

## Table 2: File opening permissions

Permission Description
‘w’ write (create if necessary)
‘a’ append (create if necessary)

##  fprintf(FID,’...’,var1,var2) : Write to a file

Page 5 of 7
ME310 - Matlab Tutorial

## Example usage of these I/O functions is shown below.

% Opening input and output files. Note that these files must be
% in the working directory of Matlab. Otherwise full path should be defined
% e.g. : input file = fopen('D/temp/input.txt','r');
input file = fopen('input.txt','r');
output file = fopen('output.txt','w');

## % reading data from the input file

data = textscan(input file,'%f %f %f');
column1 = data{1}; % Notice that these paranthesis are different !!!
column2 = data{2};
column3 = data{3};

## % writing to the output file

fprintf(output file,' col 1 \t col 2 \t col 3');

for i = 1:size(column1,1)
% here arrays are printed to the file using a for loop. it is possible to
% directly write an array or a matrix. check help document of fprintf function
fprintf(output file,'\n %f \t %.2f \t %.4f',column1(i),column2(i),column3(i));
end
% closing files
fclose(input file);
fclose(output file);

## Necessary input file and the resulting output file

input file :
0.8147 0.0975 0.1576
0.9058 0.2785 0.9706
0.1270 0.5469 0.9572
0.9134 0.9575 0.4854
0.6324 0.9649 0.8003

output file:
col 1 col 2 col 3
0.814700 0.10 0.1576
0.905800 0.28 0.9706
0.127000 0.55 0.9572
0.913400 0.96 0.4854
0.632400 0.96 0.8003

##  inline : used to define a function quickly

>> g = inline('xˆ2+3*x+5')
g = Inline function:
g(x) = xˆ2+3*x+5
>> g(3)
ans =
23

Page 6 of 7
ME310 - Matlab Tutorial

## >> s = 'a = 1:0.5:2'; % here s is a string variable

>> eval(s)
a =
1.0000 1.5000 2.0000

## % effective use of eval function to generate variable names

for i = 1:3
eval(['M' num2str(i) ' = i'])
end
% the for loop above generates 3 variables M1,M2 and M3 with respective values
M1 =
1
M2 =
2
M3 =
3

## % plots f(x) = xˆ2 −2*x +1 wrt. x changing from −10 to 10

ezplot('xˆ2 − 2*x + 1',[−10 10])

 tic/toc : measure elapsed time between them. Write tic at the beginning of a script and toc
at the end to measure the execution time of the script.

Page 7 of 7