Professional Documents
Culture Documents
PROJECT REPORT
(5-12-2009 to 29-12-2009)
By
IGNATIUS PRAVEEN
Variables
Variables are defined with the assignment operator, =. MATLAB is a weakly dynamically typed
programming language. It is a weakly typed language because types are implicitly converted. It is a
dynamically typed language because variables can be assigned without declaring their type, except if
they are to be treated as symbolic objects, and that their type can change. Values can come from
constants, from computation involving values of other variables, or from the output of a function.
Vectors/matrices
MATLAB is a "Matrix Laboratory", and as such it provides many convenient ways for creating vectors,
matrices, and multi-dimensional arrays. In the MATLAB vernacular, a vector refers to a one dimensional
(1×N or N×1) matrix, commonly referred to as an array in other programming languages. A matrix
generally refers to a 2-dimensional array, i.e. an m × n array where m and n are greater than or equal to
1. Arrays with more than two dimensions are referred to as multidimensional arrays.
MATLAB provides a simple way to define simple arrays using the syntax: init:increment:terminator. For
instance:
------------------------------------------------------------------------------------------------------------------------------------------
array =
13579
------------------------------------------------------------------------------------------------------------------------------------------
defines a variable named array (or assigns a new value to an existing variable with the name array)
which is an array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the init value),
increments with each step from the previous value by 2 (the increment value), and stops once it reaches
(or to avoid exceeding) 9 (the terminator value).
Semicolon
Unlike many other languages, where the semicolon is used to terminate commands, in MATLAB the
semicolon serves to suppress the output of the line that it concludes (it serves a similar purpose in
Mathematica.)
Graphics
Function plot can be used to produce a graph from two vectors x and y. The code:
------------------------------------------------------------------------------------------------------------------------------------------
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
------------------------------------------------------------------------------------------------------------------------------------------
Three-dimensional graphics can also be produced using the functions surf, plot3 or mesh.
Structures
Matlab supports structure data types. Since all variables in Matlab are arrays, a more adequate name is
"structure array", where each element of the array has the same field names. In addition, Matlab
supports dynamic field names (field look-ups by name, field manipulations etc). Unfortunately, Matlab
JIT does not support Matlab structures, therefore just a simple bundling of various variables into a
structure will come at a cost.
Function handles
Matlab supports elements of lambda-calculus by introducing function handles, a references to functions,
which are implemented either in .m files or anonymous/nested functions.
Classes
Matlab supports classes, however the syntax and calling conventions are significantly different than in
other languagues, because Matlab does not have reference data types. For example, a call to a method
object.method();
cannot normally alter any variables of object variable. To create an impression that the method alters
the state of variable, Matlab toolboxes use evalin() command, which has it's own restrictions.
C++ is a variation of the C language. compared to basic C is not an easy language. however it's a fast one
and a very powerful language. unlike other languages it doesn't check many things for you as it assumes
that what you want to do is what you said to do. errors in c can be very subtle, and due to coding
shortcuts and such, can be hard to find. with it you can access any port on a computer or even your own
cards in slots. the only limitation in C is your ability. though note, that people make a living just working
in C and doing nothing else.
one gives you speed and control with all responsibility in your hands (C++).The other sacrifices speed
and provides some simplicity to complex tasks with another sacrifice to ability.
This is not an easy choice and each environment is programmed differently and has a different
approach.
Advantages of MATLAB
MATLAB is a numerical computing environment and fourth generation programming language.
Developed by The MathWorks, MATLAB allows
matrix manipulation
plotting of functions and data
implementation of algorithms
creation of user interfaces
interfacing with programs in other languages.
Although it is numeric only, an optional toolbox uses the MuPAD symbolic engine, allowing access to
computer algebra capabilities. An additional package, Simulink, adds graphical multidomain simulation
and Model-Based Design for dynamic and embedded systems.
File Handling in MATLAB
INTRODUCTION
The input and disp commands are used to obtain data for a program or to convey the results o a
program. Unfortunately, these commands only allow us to interact with the program from the keyboard
or the screen. Furthermore, these commands do not give us much control over how the output from a
program is displayed on the screen. Now we will look at ways in which we can read from, or write to, a
file, with some degree of control over the form of the output. Before we can do any reading or writing
we need to open the file.
OPENING A FILE
Often we want to write programs which will operate on data residing in a file and write out
the results of our operations to a file. To do that we need to know how to open a file and
the various commands to read to, and write from, a file. By opening a file we mean verifying
its existence, if it is a file we are going to read from, and providing the program with some
way to access the file. The command to open a file in MATLAB is fopen. The command can
have several arguments though we will mainly be concerned with two. The first argument is
the name of the file we wish to open. If we are giving the name of the file directly to the
command we have to enclose it in single quotes. The fopen command returns an integer value
greater than two which becomes the identifier for the file. This identifier value is what we
will use to read from, and write to, the file. For example, suppose we want to open a file
called test.dat that already exists and resides in the directory we are currently working with.We
type
>>handle = fopen(‘test.dat’)
handle =3
The value stored in the location handle (3 in this case) is the identifier that the read and write
commands will use to identify the file test.dat.
The second argument to the fopen command tells MATLAB how we wish to interact
with the file. We have a number of options. We may just want to read from the file or only write
to the file or, maybe do both. It is important that we make our intentions explicit for several
reasons. If the file we are opening is a file that we only wish to write to, MATLAB will create a
file with the name we gave if it does not already exist. If we want to read from a file MATLAB
will check if it exists. If the file does not exist the fopen command will return a value of −1.
This way we can put a check in your program to confirm that the file actually exists before we
try to read from it. The fopen command can also return a message to us but usually it is easier
to simply check the value of the identifier .We inform MATLAB about the type of interaction
by placing as the second argument one of the following:
id = fopen(name,‘r’)
There are a number of other options available for the fopen command. You can get all the
options by typing help fopen.
Once we have opened the file we want to read from it or write to it. Let’s first look at reading
from a file then we will look at how to write to a file. There are a number of ways we can read
from a file. The one most often used is the command fscanf. The command has three arguments,
the first is the file identifier obtained by using the fopen command. The second is the format
in which the data in the file is written, and the third is the number of data values you wish to
read. This third argument is optional. If you do not supply a third argument the entire data file
will be read into an array. The second argument specifies whether we are reading a number or a
string. If we are reading a number the format specifies whether we should expect digits to the
right of the decimal point, and if so how many. Examples of the format specifier include:
‘%d’ Read the data as integers. If you use this format statement the
program will stop reading after the first decimal point is encountered.
‘%f ’ This allows for numbers with digits to the right of the decimal point.
‘%s’ Reads the data into a character string. This format ignores white
spaces and carriage control characters. If we set the third optional
argument to 1, this format will read one space delimited word.
‘%c’ This also results in the data being read into a string. However,
white spaces and carriage control characters are preserved. If
the third optional argument is set to 1, it reads a single character.
To find out where you are located in the file structure type pwd in the command window. Then,
either change your directory (by using cd) to where your file is, or save your files to the location
where you are. To check if the file you are going to interact with is in the directory where you
are located type dir in the MATLAB command window. This will also allow you to make sure
that the name of the file is what you think it is.
Syntax:
A = fread(fid) reads data in binary format from the file specified by fid into matrix A.
The fid argument is the integer file identifier obtained from the fopen operation. MATLAB reads the file
from beginning to end, and then positions the file pointer at the end of the file.
Syntax:
count = fwrite(fid, A)
writes the elements of matrix A to the specified file. The data is written to the file in column order, and a
count is kept of the number of elements written successfully.fid is an integer file identifier obtained from
fopen, or 1 for standard output or 2 for standard error.
A simple example to read from a file and write it to
another………….
The ‘readme.txt’ and ‘readme1.txt’ files before the program was run
After running the code:
The File Comparisons tool identifies differences line by line between two files. Some other applications
refer to this as a file diff. As an example, you can use this to easily compare an autosaved version of a
file to the latest version.Running the File Comparison ToolIncrease or Decrease Line Lengths
ShownExchange PositionsShow Updated FilesFind Text in FilesCompare to Other FilesPerform New and
View Previous ComparisonsAlternative Ways to Access the ToolRunning the File Comparison ToolTo use
the tool, follow these steps:Open one of the files you want to compare in the Editor/Debugger.
open(fullfile(matlabroot,'help','techdoc','matlab_env',...'examples','lengthofline.m'))
Navigate to the file you want to compare against, select the file, and click Open.
Other options available are Tools > Compare Against > Autosave Version to compare the open file to the
Editor/Debugger's automatic copy, filename.asv.
For more information, see Autosave.Tools > Compare Against Version on Disk to compare an open file
that has been changed but not saved to the saved version.The File Comparisons tool opens, displaying
the files side by side and highlighting lines that do not match. Pink highlighting and an x at the start of a
line indicates that the content of the lines in differs between the two files. Green highlighting and a > at
the start of the line indicates a line that exists in one file but not the other.
Use features of the File Comparisons tool to work with the results.
Comparison of ‘one.txt’ and ‘two.txt’ (the output correctly shows the two differences)
Graphical User Interfaces in MATLAB
GUI Files: An Overview
M-Files and FIG-Files
By default, the first time you save or run a GUI, GUIDE stores the GUI in two files: A FIG-file, with
extension .fig, that contains a complete description of the GUI layout and the GUI components, such as
push buttons, axes, panels, menus, and so on. The FIG-file is a binary file and you cannot modify it
except by changing the layout in GUIDE. Note that a FIG-file is a kind of MAT-file. See MAT-Files
Preferences for more information. An M-file, with extension .m, that initially contains initialization code
and templates for some callbacks that are needed to control GUI behavior. You must add the callbacks
you write for your GUI components to this file. When you save your GUI the first time, GUIDE
automatically opens the M-file in your default editor. The FIG-file and the M-file, usually reside in the
same directory. They correspond to the tasks of laying out and programming the GUI. When you lay out
the GUI in the Layout Editor, your work is stored in the FIG-file. When you program the GUI, your work is
stored in the corresponding M-file. If your GUI includes ActiveX components, GUIDE also generates a file
for each ActiveX component.
There are many ways to start GUIDE. You can start GUIDE from the:
However you start GUIDE, it displays the GUIDE Quick Start dialog box shown in the following figure.
The GUIDE Quick Start dialog box contains two tabs:
Create New GUI — Asks you to start creating your new GUI by choosing a template for it. You can also
specify the name by which the GUI is saved.
Open Existing GUI — Enables you to open an existing GUI in GUIDE. You can choose a GUI from your
current folder or browse other directories.
Blank GUI
The blank GUI template displayed in the Layout Editor is shown in the following figure.
Available Components
The component palette at the left side of the Layout Editor contains the components that you can add
to your GUI. You can display it with or without names.
Description:
It has three push buttons: the top two to select the first and second file respectively and the third
button to do the comparison.
On saving this figure matlab automatically creates a .m and .fig file in the current directory.
The current directory
Now the required codes are to be entered in the respective callbacks in the .m file.
In either case, if the GUI has changed or has never been saved, GUIDE saves the GUI files before
activating it and opens the GUI M-file in your default editor.
Problems encountered:
A key thing to note here is the passage of values between different buttons.In order to pass variables
between different buttons the variables must be stored in the handles structure. As this was not taken
care of initially, it took some to get the program working.
Functions used:
Uigetfile
Open standard dialog box for retrieving files
Syntax
[FileName,PathName,FilterIndex] = uigetfile(FilterSpec)
[FileName,PathName,FilterIndex] = uigetfile(FilterSpec,DialogTitle)
[FileName,PathName,FilterIndex] = uigetfile(FilterSpec,DialogTitle,DefaultName)
[FileName,PathName,FilterIndex] = uigetfile(...,'MultiSelect',selectmode)
Description
uigetfile displays a modal dialog box that lists files in the current directory and enables the user to select
or type the name of a file to be opened. If the filename is valid and if the file exists, uigetfile returns the
filename when the user clicks Open. Otherwise uigetfile displays an appropriate error message from
which control returns to the dialog box.The user can then enter another filename or click Cancel. If the
user clicks Cancel or closes the dialog window, uigetdir returns 0.
Imshow
Display image
Description
imshow(I) displays the grayscale image I.
visdiff
Compare two files
Syntax
Visdiff(fileone,filetwo)
Fullfile
Build full filename from parts
Syntax
f = fullfile(dir1, dir2, ...,filename)
Description
f = fullfile(dir1, dir2, ...,filename) builds a full file specification f from the directories and filename
specified. Input arguments dir1, dir2, etc. and filename are each a string enclosed in single quotes. The
output of the fullfile command is conceptually equivalent to f = [dir1 filesep dir2 filesep ... filesep
filename] except that care is taken to handle the cases when the directories begin or end with a
directory separator.
Reply two:
How others do it?
WinDiff
WinDiff is a graphical file comparison program published by Microsoft, and is distributed with certain
versions of Microsoft Visual Studio as well as by source with the Platform SDK code samples.
Start Windiff.exe.
In the Select First File dialog box, locate and then click a file name for the first file in the comparison, and
then click Open.
In the Select Second File dialog box, locate and then click a file name for the second file in the
comparison, and then click Open.
The information in the right pane indicates whether there is a file difference.
To view the actual file differences, click the first line in the Windiff.exe output results, and then on the
Expand menu, click Left File Only, Right File Only, or Both Files.
Start Windiff.exe.
In the Select Directories dialog box, type the two folder names that you want to compare in the Dir1 and
Dir2 boxes. If you want to include subfolders, click to select the Include subdirectories check box.
The information in the right pane indicates the differences between the two folders.
To view the actual file differences, click the line that you want in the Windiff.exe output results, and
then on the Expand menu, click Left File Only, Right File Only or Both Files.
http://www.brothersoft.com/windiff-download-76639.html
Typing deploytool in the MATLAB command window opens the deployment window.
A screenshot of the deployment tool
Click new new deployment tool project (available on the toolbar).A new window will open as shown
below:
New deployment tool project
Choose Standalone Application and give project the name you wish. Click Ok.
Next click the option and add the .m file of the GUI whose .exe file is to be created.
Once the build is successful, a new folder by the name of this project will be created. Inside this folder
two more folders will be there as shown below:
The first is the distribute file and the second is the source file. The distribute folder is the one that
contains the executable GUI. The whole folder is required to be transferred onto the machine on which
the executable file is to run.
The contents of the distribute folder are as shown below.
On first use it will have only two files. When the executable file is run, it will create a new folder as shown
below.
This new folder (untitled2_mcr) contains a folder by the name of the project, in this case untitled2
which in turn contains the .m and the .fig files of the GUI. Any additional file required such as
background image or anything is to be placed into this folder manually to make the executable file work
as expected.
In case of our comparator GUI we need to include the background image into this new folder.
The untitled2 folder inside the untitled2_mcr folder. The background image (one.jpg) has been placed
here manually.
Problems encountered:
1)There is a list of functions that the MCR compiler cannot compile. visdiff is one such function which
prevents our GUI transforming into a full-fledged standalone executable file.
Unsupported Functions
Note: Due to the number of active and ever-changing list of MathWorks products and functions, this is
not a complete list of functions that can not be compiled.
Some functions are not supported in standalone mode; that is, you cannot compile them with MATLAB
Compiler. These functions are in the following categories:
Functions that print or report MATLAB code from a function, for example, the MATLAB help
function or debug functions, will not work.
Simulink® functions, in general, will not work.
Functions that require a command line, for example, the MATLAB lookfor function, will not
work.
clc, home, and savepath will not do anything in deployed mode.
Tools that allow run-time manipulation of figures.
Returned values from standalone applications will be 0 for successful completion or a nonzero
value otherwise.
In addition, there are functions that have been identified as nondeployable due to licensing
restrictions.
mccExcludedFiles.log lists all the functions and files excluded by mcc if they can not be compiled. It is
created after each attempted build if there are functions or files that cannot be compiled.
MCR needs to be installed on those machines where the standalone project created is to be run.
Neural networks are composed of simple elements operating in parallel. These elements are inspired by
biological nervous systems. As in nature, the network function is determined largely by the connections
between elements. You can train a neural network to perform a particular function by adjusting the
values of the connections (weights) between elements.
Commonly neural networks are adjusted, or trained, so that a particular input leads to a specific target
output. Such a situation is shown below. There, the network is adjusted, based on a comparison of the
output and the target, until the network output matches the target. Typically many such input/target
pairs are needed to train a network.
Create a perceptron network to perform the AND function in this example. It has an input vector p= [0 0
1 1;0 1 0 1] and a target vector t=[0 0 0 1]. Call the network ANDNet. Once created, the network will be
trained. You can then save the network, its output, etc., by exporting it to the workspace.
Click Create and then click OK to create an input p. The Network/Data Manager window appears, and p
shows as an input.
Next create a network target. This time enter the variable name t, specify the value [0 0 0 1], and click
Targets under Data Type. Again click Create and OK. You will see in the resulting Network/Data Manager
window that you now have t as a target as well as the previous p as an input.
Create a Network
Now create a new network and call it ANDNet. Select the Network tab. Enter ANDNet under Name. Set
the Network Type to Perceptron, for that is the kind of network you want to create.
You can use a hardlim transfer function with the output range [0, 1] that matches the target values and
a learnp learning function. For the Transfer function, select hardlim. For the Learning function, select
learnp. The Create Network or Data window now looks like the following figure.
To examine the network, click View.
To train the network, click ANDNet to highlight it. Then click Open. This leads to a new window, labeled
Network: ANDNet. At this point you can see the network again by clicking the View tab. You can also
check on the initialization by clicking the Initialize tab. Now click the Train tab. Specify the inputs and
output by clicking the Training Info tab and selecting p from the list of inputs and t from the list of
targets. The Network: ANDNet window should look like
Note that the contents of the Training Results Outputs and Errors fields have the name ANDNet_
prefixed to them. This makes them easy to identify later when they are exported to the workspace.
While you are here, click the Training Parameters tab. It shows you parameters such as the epochs and
error goal. You can change these parameters at this point if you want.
Click Train Network to train the perceptron network. The following training results appear.
The network was trained to zero error in five epochs. (Other kinds of networks commonly do not train to
zero error, and their errors can cover a much larger range. On that account, their errors are plotted on a
log scale rather than on a linear scale such as that used above for perceptrons.)
Confirm that the trained network does indeed give zero error by using the input p and simulating the
network. To do this, go to the Network: ANDNet window and click the Simulate tab. Use the Inputs
menu to specify p as the input, and label the output as ANDNet_outputsSim to distinguish it from the
training output. Click Simulate Network in the lower right corner and click OK. In the Network/Data
Manager you see a new variable in the output: ANDNet_outputsSim. Double-click it and a small window,
Data: ANDNet_outputsSim, appears with the value
[0 0 0 1]
Thus, the network does perform the AND of the inputs, giving a 1 as an output only in this last case,
when both inputs are 1. Close this window by clicking OK.
Now get rid of mynet in the GUI and retrieve it from the saved file. Go to the Network/ Data Manager
window, highlight mynet, and click Delete. Click Import. This brings up the Import or Load to
Network/Data Manager window. Click the Load from Disk button and type mynetfile as the MAT-file
Name. Now click Browse. This brings up the Select MAT File window, with mynetfile as an option that
you can select as a variable to be imported. Highlight mynetfile, click Open, and you return to the Import
or Load to Network/Data Manager window. On the Import As list, select Network. Highlight mynet and
click Load to bring mynet to the GUI. Now mynet is back in the GUI Network/Data Manager window.
Learning Advanced MATLAB
Various books are available for learning MATLAB. But I personally feel the best way to learn advanced
MATLAB is by exploiting the Mathworks website (http://www.mathworks.com) resources to the
fullest.
http://www.mathworks.com/support/books/index.html
http://www.mathworks.com/matlabcentral
http://blogs.mathworks.com/videos
References
1) http://en.wikipedia.org/wiki/Matlab
2) http://www.mathworks.com
3) http://www.mathworks.com/matlabcentral/
4) http://www.mathworks.com/access/helpdesk/help/helpdesk.html
5) http://www.mathworks.com/access/helpdesk/help/techdoc/
6) http://www.academictutorials.com/matlab/
7) MIT Open Course Ware(OCW)
http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-094January--IAP--
2009/CourseHome/index.htm
8) “MATLAB Demystified“ by David McMahon, McGraw-Hill Professional
9) “Graphics and GUIs with MATLAB”, 3rd edition by Patrick Marchand O. Thomas Holland
10) http://en.wikipedia.org/wiki/Artificial_neural_network
11) http://www.learnartificialneuralnetworks.com/
12) http://www.mathworks.com/access/helpdesk/help/pdf_doc/nnet/nnet.pdf