Jump to content

MATLAB Programming: Difference between revisions

From Wikibooks, open books for an open world
[unreviewed revision][unreviewed revision]
Content deleted Content added
Line 190: Line 190:
:[[Programming:Matlab Basic vector operations| Basic vector operations]]
:[[Programming:Matlab Basic vector operations| Basic vector operations]]
==[[Programming:MATLAB/Data Types and Operators|Data Types and Operators]]==
==[[Programming:MATLAB/Data Types and Operators|Data Types and Operators]]==
Function list:
* [[/char|char]]
===Arithmetic Operators===
Add, Subtract, multiply, divide, exponent operators:
%addition
a = 1 + 2

%subtraction
b = 2 - 1

%multiplication
c = a * b

%division
d = a / b

%exponentiation
e = a ^ b
The modulo function returns the remainder when the arguments are divided together, so a modulo b means the remainder when a is divided by b.
%modulo
remainder = mod(a,b)

===Boolean Operators===
The boolean operators are given by the characters & (boolean AND) | (boolean OR) and ~ (boolean NOT /negation). A value of zero means false, any non-zero value (usually 1) is considered true.
Example:
>>%boolean AND
>> y = 1 & 0
y = 0
>> y = 1 & 1
y = 1

>>%boolean OR
>> y = 1 | 0
y = 1
>> y = 1 | 1
y = 1

>>%boolean negation (NOT)
>>y = ~1
y = 0

===Relational Operators===
Equality '==' returns the value "TRUE" (1) if both arguments are equal. This must not be confused with the assignment operator '=' which assigns a value to a variable.
>>a=5;b=5;
>>a==b
ans = 1
>>a=5;b=3;
>>a=b
a = 3
Note that in the first case, a value of 1 (true) is returned, however for the second case a gets assigned the value of b.

Greater than, less than and greater than or equal to, less than or equal to are given by >, <, >=, <= respectively. All of them return a value of true or false.
Example:
>>a=3;b=5;
>>a<=b
ans = 1
>>b<a
ans = 0

===String Operators===
strcmp(a,b) returns 'true' if a and b are equal, and 'false' if not equal.


==Scripts==
==Scripts==

Revision as of 16:08, 7 March 2006

Template:Programmingnav

A Tutorial Introduction

MATLAB is a programming language developed by the The MathWorks. It started out as a matrix programming language where linear algebra programming was simple. It can be run both under interactive sessions as well as a batch job.

Calculator

Numbers

MATLAB, among other things, can perform the functions of a simple calculator. Let us try to solve a simple problem: Sam's car's odometer reading was 3215 when his car ran out of gas. He adds 10 gallons of gas to his car's fuel tank. Yesterday when he checked his odometer it read 3503 and his car ran out of gas again. This time he fills the tank and notices that it took 15.4 gallons to do that. How long can he drive before he is going to run out of gas again, assuming the gas mileage is the same as before.

First let us compute the distance Sam's car has travelled in between the two gas fillings

>> 3503-3215

ans =

   288

Gas mileage of Sam's car is

>> 288/10
 
ans =

   28.8


With this, he can drive

>> 28.8 * 15.4

ans =

  443.5200


443.52 miles before he runs out of gas again.

Let us do the same example, now by creating named variables

>> distance = 3503-3215

distance =

   288

>> mileage = distance/10

mileage =

   28.8000

>> projected_distance = mileage * 15.4

projected_distance =

  443.5200

To prevent the result from printing out in the command window, use a semicolon after the statement. The result will be stored in memory. You can then access the variable by calling its name. Example:

>>projected_distance = mileage * 15.4;
>>
>>projected_distance

projected_distance = 

  443.5200

Strings

Besides numbers, MATLAB can also manipulate strings. They should be enclosed in single quotes:

>> fstring = 'hello'

fstring =

hello

If you would like to include a single quote you can do it in this way

>> fstring = 'you''re'
 
fstring =
 
you're
>> fstring = ''''
 
fstring =
 
'

Arrays

Arrays are the fundamental data type of matlab. Indeed, the former data types presented here, strings and number, are particular cases of arrays. As in many traditional languages, arrays in matlab are a collection of several values of the same type (by default, the type is equivalent to the C type double on the same architecture. On x86 and powerpc, it is a floating point value of 64 bits), indexed through an integer.

A simple way to create an array is to give a comma separated list of values inside brackets:

>> array = [0, 1, 4, 5]

array =

    0     1     4     5

Contrary to low level languages such as C, an array in matlab is a more high level type of data: it contains various informations about its size, its data type, etc...

>> length(array)

ans =

    4

Arrays can be multi-dimensional. To create a 2 dimensional array (a matrix in Linear Algebra terms), we have to give a list of comma separated values, and each row should be separated by a semi colon:

>> matrix = [1, 2, 3; 4, 5, 6]

matrix =

    1     2     3
    4     5     6

It should be noted that a matrix, as its mathematical equivalent, requires all its rows and all its columns to be the same size:

>> matrix = [1, 2, 3; 4, 5]
??? Error using ==> vertcat
All rows in the bracketed expression must have the same
number of columns.

The number of rows and columns of the matrix can be known through the built-in size function. Following the standard mathematical convention, the first number is the number of rows, the second number the number of columns

>> size(matrix)

ans =

    2     3

Mono-dimensional arrays are actually a special case of multi-dimensional arrays:

>> size(array)

ans =

    1     4

As we've already said before, an array is a high level object, much higher than in C, or even a C++ vector. The goal is to have a type similar to mathematical vectors and matrices. As such, a vector can be a row vector or a column vector, and they are not equivalent:

>> column = [1; 2; 3] 

column =

    1
    2
    3
>> row = [1, 2, 3]

row =

    1     2     3

row and column do not have the same size:

>> size(column)

ans =

    3     1
>> size(row)

ans =

    1     3

Arrays are a fundamental principle of Matlab, and almost everything in Matlab is done through a massive use of arrays. To have a deeper explanation of matlab arrays and their operations, see Arrays and matrices.

Arrays and matrices

Introduction to array operations
Basic vector operations

Scripts

Matlab scripts and functions are stored in M-files, with the extension *.m. Custom functions follow the syntax:

function outputname= function_name(input_arg1,input_arg2)
        statements
return;

Function files must have the same name as function_name, and be added into MATLAB's PATH environment variable by selecting File-Set Path-Add Folder, then adding the folder containing function.m.

Comments

comment lines begin with the character '%', and anything after a '%' character is ignored by the interpreter. Comments are useful for explaining what function a certain piece of code performs.

Entering data at the command line

The input() function lets your scripts process data entered at the command line. All input is converted into a numerical value or array. The argument for the input() function is the message or prompt you want it to display. Inputting strings require an additional 's' argument. Example:

%test.m
%let's ask a user for x
x = input('Please enter a value for x:')

Then running the script would produce the output:

Please enter a value for x:3

x = 3

>>

Examples

Saving to a File

There are many ways to save to files in MATLAB.

  • save - saves data to files, *.mat by default
  • uisave - includes user interface
  • hgsave - saves figures to files, *.fig by default

File Naming Constraints

MATLAB for Windows retains the file naming constraints set by DOS. The following characters cannot be used in filenames:

  "  / : * < > | ?  

Inserting Single Quotes

The escape sequence for the single quote, ', is to type it twice. Another option is to use the char command, char(39). Here are some examples:

>> ''''

and

>> char(39)

both return

ans =

'

which is just a single character, the single quote.

Inserting Newlines into Plot Labels

Cell arrays are the easiest way to generate new lines when using the functions xlabel, ylabel, zlabel, text, title, and gtext. However, cell arrays do not always work (see next section).

When displaying text on plots, "\n" is typically interpreted as '\' followed by 'n' instead of the newline character. To generate multiple lines, use cell arrays. This is done by separating each string line of text with a comma and enclosing all comma-separated strings in curly braces as follows.

>> title({'First line','Second line'})

Sometimes it is nice to put the value of a variable and a newline into the plot title. You can do this like so:

n = 4;
x = -n:1:n;
y = x.^2;
plot(x,y)
title( [ 'plot of x squared', 10, 'from x = ', num2str(-n), ' to x = ', num2str(n) ] )

The 10 outside the single quotes is the ascii value for a newline. You don't have to use the char() function, just the number will work.

The output should look like this:

plot of x squared
from x = -4 to x = 4

Inserting Newlines into Disp, Warn, and Error

The functions warning, error, sprintf and fprintf will interpret '\n' as a newline character. For example

>> error('This error\nhas a newline.')
??? This error
has a newline.

This functionality was introduced in MATLAB 6.5 (R13), when formatted error strings were introduced. This is described in the Release Notes for that release. To do this in previous versions, use SPRINTF or CHAR(10):

>> error(sprintf('This error\nhas a newline.'))
??? This error
has a newline.
disp(['abcd' char(10) 'efgh'])
abcd
efgh

This works as well:

disp(['abcd', 10,  'efgh'])
abcd
efgh

Toolboxes

Guide

  • GUIDE allows the creation of interactive user interfaces.
  • Simulink is a set of tools for modeling, simulating and analysing systems.

Psychtoolbox

Distributed Computing toolbox

  • The distributed computing toolbox is a set of tools that aid in distributing models over a cluster.