Pages - Menu

Showing posts with label matlab. Show all posts
Showing posts with label matlab. Show all posts

Thursday, 11 October 2012

Basic MATLAB commands

My previous article was about defining scalar variables and evaluating arithmetical expressions in MATLAB.

Now, we're going to practice that and I will show you some basic commands.

Let's say we want to keep track of what we do in this session. For this, we have the diary command.
>> diary

This function will create a text file named diary that you can open later with any text editor.

If you want to give the file a name of your choise, use
>> diary FileName

(MATLAB automatically colours the file name in magenta).

More information about this command can be found by typing 
>> help diary

To see the current directory, where this file has been saved, use the the cd command.

You can change the current directory by specifing the path between apostrophes.
>>cd 'D:/'

Let's make the following four variables: a=2.5×1023, b=2+3i (i being the imaginary number), c=ej2π/3, d=√36.
>> a=2.5*10^23, b=2+3*i
a =
  2.5000e+023
b =
  2.0000 + 3.0000i

In this case, the e notation is used for a very large number.

Notice that to enter multiple statements at once you can use commas.

For defining the c and d variable, we'll need some help from MATLAB and we'll have to search for the exponential function, for the pi constant and for a function that computes the square root of a number. 
>> lookfor exponential
Lookfor searches in the description of each function for a match, while help searches a function with the exact same name.
>> c=exp(j*2*pi/3); d=sqrt(36)
d =
  6

As you can see, semi-colons also allow placing several statements on one line, but, unlike commas, they will supress the output. 

For a list of the variables in the current workspace type:
>> who
Your variable names are:
a b c d

To see even more details about the variables, including size, class and attributes, use whos.

Remember that at the beginning of this session, you started a diary. Now, since the article is coming to an end, we should stop recording. For this, enter
>> diary off

 To view the diary file use
>> type('FileName')

 To remove all the variables from memory, MATLAB has the clear command.
>> clear

If you want to clear the Command Window, type
>> clc


Wednesday, 10 October 2012

Defining vectors in MATLAB. Vector commands and built-in functions in MATLAB

This article will show you how to define and manipulate vectors in MATLAB using built-in functions.

A vector is a special case of a matrix. The elements of a vector must be enclosed in square brackets.

A row vector is a 1xn matrix. The entries of a row vector can be delimited by either spaces or commas. Below you have two vectors defined in both ways.
>> Rvec1=[1 2 3 4 5]
Rvec1 =
     1     2     3     4     5

>> Rvec2=[3.14,15,9,26]
Rvec2 =
     3.1400    15.0000    9.0000     26.0000

A column vector is a nx1 matrix. The components of a column vector are separated by a semi-colon.
>> Cvec1=[1;2;3;4;5]
Cvec1 =
     1
     2
     3
     4
     5

You can easily change the value of a element using MATLAB's indexing commands by typing the following in the command line:
>> Rvec1(1)=10
Rvec1 =
    10    2     3     4      5

As you can see, the first component of the vector has now the value 10.

Accessing multiple elements can be done as follows:
>> Rvec1([1 3 5])
ans =
    10    3    5

The snippet above lets you access the first, third and fifth element of the vector. You can change more than 1 element like this:
>> Rvec1([1 2])=[7 8]
Rvec1 =
    7    8    3    4    5

That has given another value to the first and second element.

Now, let's extract all the entries of the vector from the second to the last. This can be simply done by typing in:
>> Rvec1([2:end])
ans =
     8     3     4     5

If you need a vector with equally spaced elements, this can be easily done using MATLAB's construct star:increment:finish. If you don't mention an increment, it's assumed to be 1.
>> Rvec3=1:10
Rvec3 =
     1    2    3    4    5    6    7    8    9    10

Further, I will be describing some MATLAB built-in functions that you can use when working with vectors.

The number of elements in a vector is known as the length of a vector.
>> length(Rvec1)
ans =
     5

To generate a specific number of points between two given values, use linspace:
>> linspace(1,2,3)
ans =
    1.0000      1.5000      2.0000

For a logarithmically spaced vector, use logspace:
>> logspace(0,1,5)
ans =
    1.0000    1.7783    3.1623    5.6234    10.0000

To initialise a vector having n elements with 0, use zeros.
>> zeros(1,3)
ans =
    0    0    0

There is a similar function that will initialise all the elements of a vector with 1: ones.
>> ones(3,1)
ans =
     1
     1
     1

Next, I will be working only with  Rvec1  and Cvec1 previously defined, so you might want to clear any other variables existing now in the Workspace.
For that, do the following:

>> clear('Rvec2','Rvec3')

You can notice that those two variables have now been deleted from your Workspace.

The  sort command sorts the elements of the vector is ascending or descending order.
>> sort(Rvec1,'ascend')
ans =
    3    4    5    7    8

>> sort(Cvec1,'descend')
ans =
    5
    4
    3
    2
    1

The mode parameter is optional and is assumed by MATLAB to be  ascend if left blank.

To find the largest or the smallest component, use max, respectively min.
>> max(Cvec1)
ans =
     5

>> min(Rvec1)
ans =
     3

To sum all the elements of a vector, MATLAB has a very suggestively named function: sum
>> sum(Rvec1)
ans =
    27

To compute the product of the elements of a vector, use prod:
>> prod(Cvec1)
ans =
   120

Most of the commands can also be used for matrices since a vector is a matrix that has only one row or column. More details and examples about working with matrices will be found in another post.

For the last section of this article, I will be talking briefly about character arrays in MATLAB.

You can create a string by enclosing a sequence of letters/numbers/special characters in single quotation marks. Here's an example:
>> str1='Vintage'
str1 =
Vintage

To convert characters to their ASCII code or to find their numerical equivalent, use unicode2native:
>> str2=unicode2native(str1)
str2 =
     86     105     110     116     97     103     101

To convert a integer vector to characters use native2unicode or the char function:
>> native2unicode(str2)
ans =
Vintage

>> char(str2)
ans =
Vintage

To determine whether the input is a char array or not, use  ischar. This functions will return 1 if the argument is a string and 0 otherwise.
>> ischar(str1)
ans =
     1

To check if a character is a letter, use isletter. This MATLAB function will return 1 if the character is a letter of the alphabet and 0 otherwise.
>> isletter('*')
ans =
     0

The isspace functions behaves similar and is used to verify spaces in a string.

To compare two strings, use one of the following functions: strcmp (determines if the two input strings are identical), strncmp (determines if the first n characters of the strings are identical), strcmpi, strncmpi. The last two ignore case.
>> strcmp(str1,'vintage')
ans =
     0

>> strcmpi(str1,'vintage')
ans =
     1

Also, all the relational operators (==, ~=, >, >=, <, <=) can be used to compare arrays with equal dimensions.

To horizontally concatenate two or more strings, you can use the strcat function.
>> s1=strcat(str1,'Coding')
s1 =
VintageCoding

For a vertical concatenation, MATLAB has the strvcat function that will return a column vector containing string elements.
>> strvcat(str1,'Coding')
ans =
Vintage
Coding

You can search any string for any occurrence of another string by making use of the findstr function. This will return the starting index of each appearance of the shorter string in the longer one. This search is case sensitive. 
>> findstr('i', 'Vintage Coding')
ans =
    2 12

For a search where the order of the input character arrays is important, use strfind.

Remember that for more details about each of these functions, you can see the help MATLAB provides.

For vector operations in MATLAB, see my next article.

Monday, 8 October 2012

Defining matrices in MATLAB. Matrices commands and built-in functions in MATLAB

This article will show you how to define and manipulate matrices in MATLAB using built-in functions.


A matrix consists of a one or more rows vectors of the same lenght or one or more column vectors of the same lenght.


To define a matrix in MATLAB, each element of a row must be folowed by a space or comma and each row must be delimited by either a semi-colon or a new line.

>> A=[1 2 3;0 -2 6;8 10 14]
A =
    1      2     3
    0     -2     6
    8     10    14
>> B=[5 3 1
     12 9 10
      4 7 0]
B =
     5     3     1
    12     9    10
     4     7     0

You can easily change the value of a matrix element using MATLAB's indexing commands by typing the following in the command line:
>> A(1,2)=0
A =
    1      0     3
    0     -2     6
    8     10    14

As you can see, the second element of the first row of the matrix has now the value 0.

To extract a specific column of a matrix in MATLAB, use the semi-colon:
>> A(:,2)
ans =
     0
    -2
    10

The snippet above selects the entire second column of the A matrix previous defined and it essentially means "every row, second column".

Selecting a specific row of a matrix in MATLAB is done in a similar manner:
>> A(end,:)
ans =
    8      10      14

This will extract the entire last row of the matrix.

Accessing a submatrix in MATLAB is done as follows:
>> A(2:3,1:2)
ans =
    0     -2
    8     10

This passage will select rows 2 to 3 and columns 1 to 2.

If you want to extract scattered elements from a matrix, you'll need to use linear indexing, that is indexing the elements of the matrix as if they were part of a long column vector.  

In the following example, each element of the matrix has the same value as its index. 
>> M=[1 5 9 13;2 6 10 14;3 7 11 15;4 8 12 16]
M =
    1   5    9   13
    2   6   10   14
    3   7   11   15
    4   8   12   16


>> M(7)
ans =
     7

To determine the number of rows and columns of a matrix, use size
>> C=[11 3 2;25 6 14]
C =
   11   3   2
   25   6  14
>> size(C)
ans =
     2    3

MATLAB has a few build-in functions you can use to create special matrices.

For a matrix with all its elements having the value zero, use zeros.
>> zeros(2,2)
ans =
     0   0
     0   0

For a matrix with all its elements having the value one, use ones.
>> ones(2,3)
ans =
     1   1   1
     1   1   1

To create a m x n identity matrix, use the eye command.
>> I=eye(3)
I =
    1   0   0
    0   1   0
    0   0   1

For a diagonal matrix, first define a vector containing the elements on the diagonal of the matrix, then use diag.
>> d=[1 2 3]
d =
    1   2   3
>> diag(d)
ans =
      1   0   0
      0   2   0
      0   0   3

For a similar article on vectors, see this article.

Vector operations in MATLAB

In my most recent article I presented you a large list of commands that will ease your work with vectors in MATLAB.

Now, it's time to discuss about some operations that can be performed on vectors.

I will start by defining the following two vectors:
>> vec1=[1 2 3 4]
vec1 =
     1     2     3     4
>> vec2=[4 3 2 1]
vec2 =
     4     3     2     1

To sum two vectors, they must have the same dimension. Summing two vectors means to sum the elements of the two vectors found on the same position. In order to do this, the vectors must have the same dimension.
>> vec1+vec2
ans =
    5    5    5    5

The observations I made on suming two vectors in MATLAB also apply to substraction.
>> vec1-vec2
ans =
    -3    -1    1    3

Since a row vector is a 1xn matrix and a column vector is a nx1, to multiply vectors, the number of rows of the first one must have the same dimension as the number of columns of the second one.
>> vec1*[1;2;3;4]
ans =
    30

Array operations are done element by element. In order to differentiate them from the matrix operations, the . character is used before the arithmetical operator. However, this character it is not used for addition and substraction since they are the same for both matrices and arrays.

To calculate a element by element operation between two vectors, they both must be either a row or column vector with the same length.

For a element by element multiplication, type in: 

>> vec1.*vec2
ans =
    4    6    6    4

The following sequence computes a element by element division:
>> [1;2;3]./[3;2;1]
ans =
    0.3333
    1.0000
    3.0000

An array raise to power can be performed as follows:
>> vec1.^vec2
ans =
    1    8    9    4

The second vector can also be a scalar:
>> vec1.^2
ans =
    1    4    9    16

For a cross product of two vectors, use cross The two vectors must have the size 3. 
>> v1=[1 2 3]
v1 =
    1     2     3
>> v2=[4 5 6]
v2 =
    4     5     6
>> cross(v1,v2)
ans =
   -3     6     -3

For the scalar product of two vectors, use dot.
>> dot(v1,v2)
ans =
   32

My next post will be about MATLAB commands when working with matrices.

Sunday, 7 October 2012

Using MATLAB as a calculator

The purpose of this article is to show you how you can use MATLAB for evaluating an arithmetical expression.

After launching MATLAB, in the Command Window you can see the prompt sign >>.
Let's say we want to evaluate the following expression: 1+3*2^2/4.
In order to do this, simply type it after the prompt, then press Enter.
>> 1+3*2^2/4 
ans =

     4

You can notice that MATLAB has automatically created and assigned  the result to a variable, ans (shortening for answer). However, after performing another evaluation, this variable will be overwritten. In order to avoid this, you can create a new variable ( I will call it res) and assign the outcome to it.

Be aware that variable names are case sensitive, must start with a letter and can contain only letters, numbers and the underscore character.
(After the prompt you can type res, then press the up-arrow key. This will recall a previous command, in this case 1+3*2^2/4. Command History window shows the list of commands used in the past).

The order of precedence in MATLAB is the same as in algebra, so you're free to use parentheses if necessarily.

The expression assigned to a variable can be a combination of numerical values, mathematical operators, variables, build-in functions and functions defined by user (those shall be discussed later).

You can use a variable name to refer to the result of a expression in other computations. For example: 
>> 2*res 
ans =

      8

Now, to terminate MATLAB, you can either go File, then Exit MATLAB, press Ctrl+Q or type one of the following commands in the Command Window: quit or exit.

My next post will focus on basic MATLAB control commands, like the two mentioned above.