60

A Quick Guide to MATLAB Syntax


Article posted on Sunday, 1st, July, 2012 at 1:13 pm


MATLAB, like any other programming language requires you to be familiar with its syntax in order for you to get better at it. The good thing is that MATLAB syntax is very easy to pick up when you practise with it a bit. Here are a few pointers to help get you working with it…

Comments are written using the percent sign

% This is a MATLAB Comment

Variables are assigned using the equals sign:

% String
a_string = 'Hello, world!';
% Number
a_number = 12345;
% Numeric array (newline = ';')
an_array = [1 2 3; 4 5 6; 7 8 9];
% Cell array
cell_arr = {'A' 'a'; 'B' 'b'; 'C' 'c'};

Command line output is supressed using the semicolon:

% Does not display anything
a = 'hello';
% prints 'b = hi' in the command window
b = 'hi'

Mathematical operators use the following symbols

% Addition
a = 1 + 1;
% Subtraction
b = 2 - 2;
% Multiplication
c = 3 * 3;
% Division
d = 4 / 4;
% ... to the power of ...
e = 5 ^ 5;

Logical operators use the following symbols:

% Not (note that '!' is used in most other languages)
~
% And
&
% Or
|
% Exclusive Or
xor

Relational operators use the following symbols

% Equal to
==
% Not Equal to
~=
% Greater than
>
% Less than
<
% Greater then or equal to
>=
% Less than or equal to
<=

Note that this link on the Mathworks website gives you more info on operators: http://www.mathworks.co.uk/help/techdoc/matlab_prog/f0-40063.html

Conditional statements are written with the following format

% If statement requires a boolean output (true/false)
if my_age >= 18
    % Code to execute if statement evaluates to true
    disp('You are able to buy beer!')
else 
    % (Optional) Code to execute if statement evaluates to false
    disp('You are too young to buy beer!')
end 

For loops are written with the following format

% For loops require a variable to store a number denoting which 
% iteration the loop is currently on. The variable will change 
% each time the loop goes round.
for loop_number = 1:10
    % To be executed each time the loop iterates
    disp(loop_number)
end 

Some of these concepts will be explained in detail at a later date, so don’t worry if it’s a bit confusing at present!



Tags: , , ,

Join in the Conversation


comments powered by Disqus