English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

3 answers

Interesting challenge.

I would use the dir command, filter it to get the image names.
Load them up, convert to grayscale (so they are one-dimensional data) set a higher value number to be a file delimeter then use the resize and catenation function.

That gives you a directory of images loaded, converted, and put in a very long train of values.

Im not sure why you want to do that, but that is how it could plausibly be done.

Dont let the verbose person who just photocopied the book get to you. Thats a lot of confusing text, and very very basic stuff, so it doesnt answer your question.

Review:

Dir
- get file names
- get number of file names

loop
imread - to get image
mean and "./" or dot-divide to convert to grayscale
[ ] functions to catenate

end loop

2007-01-20 10:58:16 · answer #1 · answered by Curly 6 · 0 0

its not eazy mam you
have to study for it c-language ok
just join an institute and u can get the right answer

2007-01-18 05:01:34 · answer #2 · answered by RAVI KUMAR 1 · 0 0

Introduction
Thank you for your initial interest in Matlab programming. We would like to invite you to another session, to be held Thursday, June 19, at 2pm, in the same place – the computer teaching labs (CTL 0810/0811).
If you came to the first session on June 12, we hope that you got an idea of what Matlab is about. For example, it is not a program for high level graphics, like Sigma Plot. Rather, it is a program for programming. Its value is not best realized in a general environment of shared users. Instead, it is best in a specialized environment, where users need to get their hands around data in unusual, perhaps unique ways.
Next session, those in the Restrepo group will spend time examining some of the items in the 'menu' below, especially Matlab's special tool for creating GUI's (Graphical User Interfaces), called GUIDE. Betz et al (who spent most time in the first session examining GUI objects like sliders and buttons) will move on to some of the other topics described below, especially array addressing and getting data into and out of Matlab (e.g., to and from disk).
In both classes, we will be aim to identify topics of special interest to YOU. We want you to begin to create your own special projects.
The menu for the next session is listed below; there are 9 categories. We can discuss them or not, in any order. The aim, as we said, is to move on to specific programming needs and interests of anyone left standing. We will not be able to cover them all in one session!
Menu | Arrays | Strings | File I/O |
| Debugging | Make list of files | Keyboard/mouse input |
| Programming tips | GUI objects | Miscellaneous |




1. ARRAYS
A brief primer on Arrays
Array formats: Described below are the major ways in which Matlab holds information. Arrays may be one dimensional – a row or a column of values. A one dimensional array is also called a vector. An example is created by this operation: a=[1:10] . It makes an array with one row and 10 columns. Two dimensional arrays are probably the most common – these are like a table, and contain rows and columns. Each unique address is called an element (or cell). Elements in a two dimensional array are addressed by specifying its row and column. For example, first make an array: a=rand(2,5) makes a table (2 dimensioal array) containing 2 rows and 5 columns of random numbers (The Matlab command ‘rand’ generates random numbers). Elements are addressed like this: a(2,3) addresses the second row, third column. To address more than one element simultaneously, use the colon operator. For example, a(2,1:3) addresses the first three columns of row 2. The colon by itself addresses all elements. For example, a(:, 1:3) address the first three columns of all rows.
To exchange rows and columns, use the single quote after an array. For example, as above, a=rand(2,5) makes a table with 2 rows and 5 columns. If you then enter b=a’ the array b will have 5 rows and 2 columns.


Numeric arrays hold numbers only. For example, a=[1:10] creates a 10-element numeric array named ‘a’.


String arrays (same as Character arrays) hold text, not numbers. Avoid using string arrays! The reason is that each element of a string array must be the same length. So if you have two strings (a=’hello’ and b=’bye’) and try to put them into a string array (c=[a; b]) you will get an error because ‘a’ and ‘b’ are not the same length. What a pain. The solution? Use cell arrays (see next)


Cell arrays hold anything - numbers, strings, whole other arrays. Usually, cell arrays are created by enclosing a miscellaneous collection of things in curly braces, { }. For example, a={[1:10] ‘hello’} makes a two-element cell array. The first element of the cell array contains the array [1:10] (that is, a ten element array containing the integers from 1 to 10); the second element contains the string ‘hello’.
The curly braces are also used with subscripts to access the contents of various cells, that is, to ‘unpack’ the array. Compare typing a(1) with a{1}.
Cell arrays are hard to get used to, but are necessary for lots of Matlab operations. For example, most types of input to a program from the keyboard come into a cell array (so the input can be either a number or a string).
The main thing to remember with cell arrays is that you create them and ‘unpack’ them by using curly braces.


Structure arrays are like cell arrays in that their individual elements can contain anything – numbers, strings, arrays, whatever. The difference is how the elements are addressed. Cell arrays are addressed like numeric arrays, with numeric subscripts (e.g., a{2, 3}). Structure arrays use a dot (.) followed by a unique name. For example, a.number=[1:10] and a.string=’hello’ will make a two element structure array.
The advantage of structure arrays is that it is easy to remember where the variable is, because it has a friendly name (it is easier to remember ‘a.string’ than ‘a{2}’, especially when you have dozens of variables).
There are other types of arrays in Matlab, but the ones described above are the ones that are used most often.


Now let's look at some common ways of addressing array contents.

A. Making a vector (a one dimensional array) of consecutive integers
a=[1:10] % makes a vector of 1 row, 10 columns, with values from 1 to 10..
a=[1:10]' % does the same, but the single quote switches rows and columns, giving 10 rows, 1 column

B. Making 2D arrays
a=ones(4,5) % makes an array with 4 rows, 5 columns; every element has a value of 1
a=zeros(4,5) % same, but the value of each element is zero
a=rand(4,5)% each element is a random number

C. Addressing parts of arrays
The colon operator (:) is used to address rectangular subsets of an array.
Given that a=rand(4,5):
b=a(2:3,1) % How big is array b? (answer: 2 rows, 1 column)
b=a(:,1) % How big is array b? (answer: 4 rows, 1 column)
a(3,:)=[] % How big is array a? (answer: row 3 is deleted, so the result is 3 rows, 5 columns)

D. The max command finds the maximum value(s) of an array.
Given that a=rand(4,5): the array looks like this (the max value is highlighted):

0.83812 0.8318 0.30462 0.30276 0.37837
0.01964 0.50281 0.18965 0.54167 0.86001
0.68128 0.70947 0.19343 0.15087 0.85366
0.37948 0.42889 0.68222 0.6979 0.59356


b=max(a) % How big is b? (1 row, 5 columns, because the command max operates on each column of an array. Thus, it returns the max value in each column, for a total of 5 values.)
b=max(a(:)) % How big is b?(1 element, that is, 1 row, 1 column, because a(:) means the entire array, so the max command returns the max value of the entire array.)

E. Manipulating arrays without regard to the structure of the array. Suppose we want to change the array above so that all values below 0.5 are zeroed out.
a=rand(4,5); % makes the array
a(a<0.5)=0; % sets any value below 0.5 to 0

F. Using binary arrays
Elements in binary arrays have values of 1 or 0, nothing else. They are really useful for segmenting (partitioning) an array into two parts. For example, suppose we want to know how many elements in the array a have values below 0.5.
a=rand(4,5); % makes the array
b=(a<0.5); % array b contains all 1's and 0's
c=sum(b(:)); % array c is the number of values in array a that are less than 0.5. Why is array b addressed as b(:), and not just b? Answer: The Matlab command sum, like max, works on columns. So sum(b) returns 5 values (the sums of each of the 5 columns), while sum(b(:)) returns one value (the sum of the entire array).
All of this can be done in one line:
c=sum(sum(a<0.5));
The sum-sum structure returns the sum (1 value) of the sum (5 values).

G. The 'find'command
Sometimes you need to know where the max value resides in the array, that is, which element holds the max value. The next examples show how to find elements of interest in Matlab arrays.
b=find(a==max(a(:))) % The answer (b) is a single number, because, given the opportunity, Matlab would rather number elements in an array with a single number (because it can calculate things faster). It numbers from top down, starting in the first column, then moves to the top of the next column. So element #4 of the array named a is actually the same as a(4,1). Element #5 is a(1,2). This is a big pain for most purposes. The next method (below) is easier, using row and column values
[r,c]=find(a==max(a(:))) % Now the answer is r=2 and c=5; that is, the max value is indeed in the second row, fifth column. Why the square brackets? Answer: Because there is only one answer (output of the operation), with 2 numbers; the brackets mean ‘collect everything inside together’.
Suppose we want to know the locations of all elements with values below 0.5.
[r,c]=find(a<0.5);
This returns two vectors of the row (r) and column (c) locations of values below 0.5.

H. Concatenating arrays
This means joining together 2 arrays. Be careful! It is easy to make errors, since the result of the concatenation must be a rectangular array, which means the various arrays joined together must make a rectangle of elements.
Arrays are concatenated by enclosing their names in square brackets.
Given a=rand(4,5), as above.
b=[a a] % What are the dimensions of b? (answer: 4 rows, 10 columns)
b=[a; a] % What are the dimensions of b? (answer: 8 rows, 5 columns)
Notice how [a a] joins the arrays horizontally, while [a; a] joins vertically. This makes sense, because the semicolon (;) denotes the end of a line.

I. Here are a few other Matlab commands that operate on arrays. They work best on square arrays, since they split the array diagonally.
Given: a=rand(4,4).
b=diag(a) % This returns the values lying along the diagonal of the array (top left to bottom right) as a 4 row, 1 column array.
b=triu(a) % This sets every value below the diagonal to zero (TRiangle Upper).
b=tril(a) % This sets every value above the diagonal to zero (TRiangle Lower).

J. Array SIZE
Given: a=rand(5,4).
s=size(a) % Since the array named a is 2 dimensional, this returns 2 values: the number of rows and the number of columns. Thus, the number of rows in array a is size(a,1) and the number of columns in array a is size(a,2).


2. STRINGS
Matlab is not especially friendly when it comes to strings. For example, at least one of us recommends that you never use string arrays. Instead, use cell arrays, and convert ('unpack') them using curly brackets – { }.
For single strings (not arrays of strings), there are several useful Matlab commands, described below.
num2str(n1) turns the number n1 into a string. It looks the same whether displayed as a number or string, but you can't do math on a string, and you can't use numbers in some Matlab operations (e.g., data input with 'inputdlg' - see below). The Matlab command str2num(s1) turns a string into a number. If s1 contains any letters, you get an error.
strcmp(s1,s2) is used a lot. It means STRing CoMParison, and returns a value of 1 if s1 and s2 are identical; otherwise it returns a value of zero.
findstr(s1,s2) finds the first occurance of string s1 within string s2. For example, findstr('b','abc') returns a value of 2.


3. FILE I/O: GETTING DATA INTO AND OUT OF MATLAB
Moving data back and forth between a program and disk or another program is one of the most important functions of just about any program. Matlab has extensive techniques for reading and writing data - there are literally hundreds of different ways of formatting strings and numerical data. Three of the most useful kinds of operations are described below; they are: copying data from Matlab to another program, saving Matlab data to disk in Matlab format and reading it back into Matlab, and reading non-Matlab formatted data from disk. These are described below.


A. Taking Matlab data to another program. Often it is necessary to get numeric data out of Matlab and into another program (for example, moving Matlab data into a spreadsheet). It is simple to do this by displaying the numeric data in the Matlab editor, and then copying to the Windows clipboard and pasting into the new program. In a program, this can be accomplished by saving the numeric data in ASCII (string or character) format in a dummy file on disk, and then reading it back into the Matlab editor, from which it can be copied and pasted. Suppose the numeric data are in an array named a:
dlmwrite('junk.txt',a,'\t')
edit 'junk.txt' %
In the first line, dlmwrite means to write DeLiMited data to disk; the last argument ('\t') means that the delimiter is the tab (i.e., each element of the array is separated from its neighbors by a tab). The name of the file is 'junk.txt', and the variable written is our friend named a. The information is in ASCII (text) format.
The second line opens the file in the Matlab editor. Copy and paste some or all of it to your favorite destination.
You may also be able to use the import function in a different program to read the data from the disk file (junk.txt).
If you want to read the data from 'junk.txt' back into a Matlab numeric array, try this: a=textread('junk.txt') or a=textread('junk.txt', '%s'). The Matlab command textread is the counterpart of dlmwrite.


B. Saving Matlab data (either numeric or string or both) to disk, for accessing by Matlab.
Sometimes it is necessary to save data and read it back into Matlab. For example, you might want to read it into another Matlab program, or into the same program at a later time. This is incredibly easy, and it can be done for strings or numbers, and any number of variables. Suppose, for example, you want to save three arrays, a, b and c (their format - numeric or string - doesn't matter).
[fname,pname]=uiputfile('*.mat','Title');
if ischar(fname); save([pname fname],'a','b','c');end
The first line prompts for a path name (pname) and for a file name (fname). The Matlab command uiputfile opens a familiar-looking, standard window in which you move to the folder (directory) you want, and type a file name (or select a preexisting file). The first argument ('*.mat') determines the suffix of the displayed files (use '*.*' to display all files in the directory) and of the file you save. The second argument ('Title') is just the title of the dialog window.
The second line tests to see if a file name was entered (ischar asks if fname contains characters). If a file name was indeed entered, then the variables a,b, and c are saved in that file.
Loading these variables back into a Matlab program is really simple:
[fname,pname]=uigetfile('*.mat','Title');
if ischar(fname); load ([pname fname]); end
The first line displays a dialog window to get (uigetfile) the file.
The second line just loads the file. Note that no variables are named in this line (no 'a','b','c' here). That's because the names are saved with the data, so Matlab knows to load the data into variables named a,b, and c. Cool.


C. Any data into Matlab. Sometimes it is necessary to access data that were created by some other program and saved on disk. Reading such data into Matlab can be more complex than the other two examples above, and usually requires that something is known about the structure of the data in the disk file. Sometimes Matlab can sniff out the file and figure out the data format; other times you need to know the format and make it explicit in your program, which can be a pain.
As an example, consider images obtained, for example, with a fluorescence microscope fitted with a digital camera, and stored in TIF format. The images were taken of the same field of view over time - a time lapse movie. We want to display the images as a movie.
Here is one way to do it: First read all of the images into a 3D array (each image is like one page of a book). Then create a Matlab image object, and just load each image successively into the 'cdata' property of the image. For example, assume that the images are loaded into an array named M (which is a 3D array, with rows, columns, and frames, where rows=height of each image (in pixels), columns=width of each image, and frames=total number of images. To display the movie, the following code is all we need:

vh.image=image; % create the image object; give it a handle (vh.image)
for j=1:size(M,3); % from first to last image in M
set(vh.image, 'cdata', M(:,:,j)) % display the new image
pause(0.1) % pause 0.1 second
end


So displaying the images successively as a movie is pretty simple. But how do we get the data off of the disk and into the array named M? This takes a bit more work because images come in a variety of flavors. They have different formats (e.g., tif, jpeg, gif), different color types (e.g., grayscale, truecolor), and different bits-per-pixel (e.g., 8, 16, 24), making for dizzying combinations. We will check to make sure our images are 8 or 16 bit grayscale TIF images, and nothing else (this is what most digital cameras produce).
But before we read the data into the computer, we have to make a list of the files on disk that we want to read. This is done in a function called makelist (a home grown function). We will desribe it in the next section. For now, it is just called in the third line (list=makelist).
The following function gets the list, creates the array, reads the images into the array, and displays the movie.
function aamovie1
%% load and play a movie

%%%% MAKE A LIST OF IMAGE FILES
list=makelist; % makelist is a program that interactively creates a cell array of selected files (see Part 5 below)
len=length(list);

%%% SNIFF IMAGE INFO
i=imfinfo(list{1}); % the Matlab command imfinfo returns a structure array
wd=i.Width;
ht=i.Height;
bitdepth=i.BitDepth;
fmt=i.Format;
ctype=i.ColorType; % truecolor (24 bit), grayscale,

%% MAKE SURE IMAGE IS TIF AND GRAYSCALE AND 8 OR 16 BIT
if ~strcmp(fmt,'tif'); msgbox('Must be TIF format'); return; end
if ~strcmp(ctype,'grayscale'); msgbox('Must be grayscale (intensity) images'); return; end
if bitdepth < 8 | bitdepth > 16; msgbox('Must be 8 or 16 bit'); return; end
%%%%%%%% CREATE M ARRAY TO HOLD ALL DATA
% This next bit of code is nasty! A Matlab expert, Morri Feldman, spent days figuring it out.
switch bitdepth
case 8
M = uint8(0); % Create a one-element array of the correct format (uint8 means 8 bit)
case 16
M = uint16(0);
end
M= M(ones(1,ht),ones(1,wd),ones(1,len)); % Now expand the array to full size. This is a weird line of code!
%%%%%%%%%% READ IMAGES (from disk to array named M)
for frame = 1:len
M(:,:,frame)=imread(list{frame},fmt); % This crashes if images are not all the same size
end
%%%%%%%%%%%% CREATE THE 3 GUI OBJECTS (window, axes, image)
close all;
figure('doublebuffer','on'); % doublebuffer keeps the movie from 'blinking' between frames
axes('dataaspectratio',[1 1 1],'visible','off') % correct aspect ratio (width relative to height)
himg=image;
%%%%%%%%%%%%%%%% SET UP COLOR
colormap gray(256); % lookup table (other choices: jet, hot, bone, cool, many others)
set(gca,'clim',[min(M(:)) max(M(:))]) % set axes color scale to min and max
set(himg,'cdatamapping','scaled')
%%%%%%% PLAY THE MOVIE
for j=1:len
set(himg,'cdata',M(:,:,j)); drawnow
disp(j)
pause(0.2) % pause 200 msec
end

The above program (named aamovie1) is enhanced in other programs as follows:
aamovie2: the movie loops repeatedly, and a 'quit' button is added to stop it
aamovie3: two sliders that control the brightness level are added
aamovie4: a popup menu of different color lookup tables (pseudocolor choices) is added


4. DEBUGGING
While your programs probably run flawlessly, ours don't, and we need to debug them - often! There are a couple of tools that are really useful for tracking down glitches.
Pause the program. Open a program - any program – in the Matlab editor. Notice that next to most line numbers there is a dash. Click on one of these dashes; a red circle should appear in its place. This means that when the program gets to this line, it pauses (and a green arrow appears next to the red circle). At this point, you can check out what's going on. For example, if you type whos, you will see all of the variables that exist at that time.
You can also pause the program by inserting a line in the program that consists of one word: keyboard. The program will pause here.
In either case, you make the program resume by typing the word 'return' in the Command window. Note that when a program is paused in the debug mode, the prompt in the Command window becomes 'K>' (K for Keyboard).
Proceeding one line at a time. Type 'dbstep' (DeBug STEP) in the Command window; the program will move forward one line. To quit the debug mode, type 'dbquit'.


5. MAKE A LIST OF FILES
Some operations, especially involving image processing, require that multiple files (e.g., images) be read into Matlab. This function was written to enable one interactively to make a list of files. The list is made initially by typing a 'base name' with one or more 'wild cards' (*, which means ‘any character, and any number of them’). For example, to make a list of all files that begin '030612a', type 030612a*. The list can then be modified in a number of ways. It can be displayed in the edit window and edited directly. It can be culled, for example, by taking n files, then skipping m files, taking n, skipping m, etc., or by including or excluding files in the list that contain a particular string. These operations only concern the list - the files themselves are not altered.
The function named makelist is called from any other program like this: list=makelist; This will call the function named makelist, and take its output and put it into the variable named list, which is a cell array, which is subsequently 'unpacked' by using curly brackets. For example, to display the third member of the list: disp(list{3})

function list=makelist
% returns a list of files (in a cell array named list), made interactively
exit=0; % The program quits when exit=1
list={};
while (exit == 0)
%%% SET UP DISPLAY
wd=pwd; % current directory
disp(['Current directory ' wd]);
sz=size(list,1);
if (sz);
disp(' '); disp(['CURRENT LIST: ' num2str(sz) ' entries: ' list{1} ' ... ' list{end}])
else
disp('List: 0 entries')
end
choices={'MENU:'; 's=show list'; 'i=Info about image';...
'd(or ls)=dir'; 'sk=skip'; 'c=cut';...
'cc=include'; 'x=erase list & start over';...
'cd=change directory'; 'e=edit'};
disp(char(choices))
beep

%%% GET INPUT FROM USER
inp=input ('Type base name (wild cards OK) (ENTER=use current list)\n\n','s');

switch inp
case '' % ENTER pressed, time to quit program (unless list is empty)
clc;
if ~(isempty(list)); exit=1; end
case 'i' % get information about file(s) in list
prompt=['Which number? (1-' num2str(sz) '; ENTER=all)\n\n'];
inp=input(prompt,'s');
if isempty(inp);
for j=1:sz
try
info=imfinfo(list{j})
catch; disp (['Error reading ' list{j}])
end;
end
else
try
info=imfinfo(list{str2num(inp)})
catch; disp (['Error reading ' list{inp}])
info
end;
end
case 'cd' % change directory
[f picpath]=uigetfile('*.*','Pick any file in Directory');
cd (picpath) % change to new directory
case 's' % show list
clc
disp(char(list))
input ('Press ENTER');
case 'ls' % display all files in this directory
ls
disp('Press ENTER'); pause
case 'd' % display all files in this directory
dir; disp('Press ENTER'); pause
case 'c' % Cut files from list that contain string
c=input('Omit if it contains string - type string (ENTER=abort)\n\n','s');
if ~(isempty(c));
nn=1; list2={};
for j=1:length(list);
if isempty(findstr(c,list{j}));list2(nn)=list(j);nn=nn+1;end
end
end
list=list2';
case 'cc' % CCut files from list that do NOT contain string
c=input('Include if it contains string - type string (ENTER=abort)\n\n','s');
if ~(isempty(c));
nn=1;list2={};
for j=1:length(list);
if findstr(c,list{j}); list2(nn)=list(j); nn=nn+1; end
end
end
list=list2';
case 'sk' % skip files
inp=input('Take how many, skip how many? (ENTER= 1 1)\n\n','s');
[n1 n2]=strtok(inp,' '); % strtok splits inp at spaces
% e.g., '1 3' becomes '1' and '3'. Still strings, not numbers
if (isempty (n1)); n1='1'; n2='1';end
nn=0; n1=str2num(n1); n2=str2num(n2);list2={};
for j=1:n1+n2:size(list,1)
for k=1:n1
nn=nn+1;
try;list2(nn)=list(j+k-1);
catch; nn=nn-1; end
end
end
list=list2';
case 'x' % erase list
list=[];
case 'e'
dlmwrite('junk.txt',char(list),'')
edit 'junk.txt' %
input ('Press ENTER when done','s')
list=textread('junk.txt','%s');
otherwise % something was entered
structlist=dir(inp); % DIR returns a structure (4 fields: name, date, byes, isdir)
celllist={structlist.name}; % make cell array
celllist=celllist'; % 1 row becomes 1 column
list=[list; celllist]; % append to old list
list=sortrows(list); % sort alphabetically
end % switch inp
end % while exit==0


6. KEYBOARD/MOUSE INPUT
Communicating with a Matlab program using the keyboard and mouse
When a program is running, the UICONTROLS - sliders, push buttons, radiobuttons, and so forth - provide a powerful method of controlling program flow. In addition, it is often necessary to type in information at a prompt, or to use the mouse to mark a region of a graph or image for special attention.

A. Using the Keyboard. Use the 'input' command for a single line of input, and the 'inputdlg' command for multiple lines, as described below.


INPUT: This command is quick and useful for taking in a single line of keyboard entry.
a=input('Type a number, press ENTER') This form will take only a number. Entering any letter creates an error.
a=input('Type anything, press ENTER','s') Notice the 's' (for 'string') at the end. This form will take either numbers or strings; the variable named a is a string, even if a number is entered.


INPUTDLG: This command is useful for taking in multiple lines from the keyboard all at once. The format is like this: inp=inputdlg(prompts,title,lineno,defaultanswers). The four arguments (prompts, title, lineno, and defaultanswers) are variables; they must be defined in advance.
The result of the operation is returned to a variable named inp. It contains strings (no numbers) in a cell array. Likewise, the prompts and default answers must be strings stored in cell arrays. The title is a string; the lineno is a number. Whew!
The inputs (arguments) to the operation should be set up in advance. For example, suppose you want to acquire input for a text label on a graph. You might want to know three things: the string itself (the text label), its font size, and its color. The text string of course will be a string, the font size will be a number, and the color will be a three-number array (i.e., RGB mode), like [1 0 0] for red.
prompts={'Text?', 'Font size?', 'Color? (use RGB, e.g., [1 0 0] for red)'}; % Set up prompt - a cell array of 3 strings
title='Title'; % just a string
lineno=1; % this is the number of lines to allow for each entry - almost always 1
defaultanswers={'', '12', '[1 0 0]'}; % another cell array of 3 strings
inp=inputdlg(prompts,title,lineno,defaultanswers); % this makes the dialog box
if isempty(inp{1}); return; end % If no text entry, abort % Abort if no string is entered
str=inp{1}; % unpack the string from the cell array
fsize=str2num(inp{2}); % unpack and convert to a number
fcolor=str2num(inp{3}); % unpack and convert to numbers
text('string',str,'fontsize',fsize,'color',fcolor) % Add the text

B. Using the mouse. Besides the keyboard entries described above, it is often necessary to use the mouse to click on a button, to draw out a rectangle, to pick multiple points, and so forth.


QUESTDLG: This command opens a window with 2 or 3 buttons. The user chooses (clicks on) one of the buttons. The syntax is as follows:
inp=questdlg(prompt, title, button1_label, button2_label, button3_label, default)
The default (last argument) must match the label on one of the buttons. That button is highlighted. Pressing ENTER without clicking any button selects the default button. For example:
inp=questdlg('Pick one','Title','A','B','C','B');
This creates a box with 3 buttons labeled A, B, and C. Pressing ENTER picks the default (B). Clicking any button picks that button. The result returned to the variable named inp is a string - the name on the button.


GETRECT waits for a rectangle to be drawn in the current axes (left click and hold, drag out rectangle, release button). Getrect returns a 4-element vector giving x, y, width, and height of the rectangle.

close all; axes('xlim',[0 100],'ylim',[0 100]) % prepare the axes
a=getrect;


GETPTS returns the x,y value of each point when the left mouse button is clicked. An asterisk marks the point. Select as many points as you like. To delete the last point selected, press backspace or delete. To end selections, right click (adds the final point and quits) or press ENTER (no final point added).

window; axes;
[x,y]=getpts; % x and y are separate numeric vectors.


7. PROGRAMMING TIPS
A. CONTROL FLOW statements are used extensively in Matlab. They control the flow of the program by testing for various conditions.
for .. end % loops a specified number of times
while .. end % keeps going until a condition is fulfilled
switch case .. end % looks for one choice from a menu of choices
if else elseif .. end % tests for a condition
try catch end % for trapping errors

B. LOGICAL OPERATORS are for testing conditions
& means AND
| means OR
~ means NOT
Examples: Which of these will cause a beep to occur?
if (1>0) & (2>1); beep; end
if (0>1) | (2>1); beep; end
if ~(0>1) & (2>1); beep; end
(answer: all 3 will cause a beep)

C. NAVIGATING AROUND the Command window. Here are a few Matlab commands that are used a lot.
clc= CLear Command window
pwd = Print Working Directory - that is, the current directory
ls = LiSt files in current directory
dir = same as ls
cd= Change Directory (e.g., cd work/img; cd .. means move up to parent directory)
clear= delete all variables (except global)

D. The Matlab EVAL command is used to execute a string as a Matlab command. For example, the following code will cause a beep.
a='beep';
eval(a)
Another example:
inp=questdlg('Pick one','Title','beep','clc','figure','beep');
eval(inp)
This program will either beep, make a new figure (graph window), or clear the Command window. The default (the last argument) is to beep; this is chosen by pressing ENTER (and not clicking any button).


8. GUI OBJECTS
In the first session we spent most of our time examining graphical objects, their handles, and how they are used to make a GUI (Graphical User Interface). Here are a few further aspects of GUI's.

A. WORKING WITH OBJECTS
findobj
gcf, gca, gco
get, set
delete

B. GUIDE
is used to make UICONTROLS.


9. MISCELLANEOUS
A. Starting up
When Matlab is first loaded, it looks for a file named STARTUP.M, and runs it. This is a good place to set some basic preferences. Probably the most important is the PATH - the directories that Matlab searches when looking for a program to run. Here is one example:

homedir='.\'; % Set the home directory to the current directory
pathold = path; % copy the current path into an array named pathold
pathnew = [homedir,'img;',homedir,'color;']; % This adds two directories (named img and color) to the path
path(pathnew,pathold); %
% Here are some other things that can be set in startup.m
format compact; % no double spacing
format short g; % precision of numbers - balance between resolution and memory requirements
iptsetpref('imshowborder','tight'); % no border around images
more on % display big things one page at a time (you must press space_bar to see the next page)
% 'more off' will cause big displays to show all at once; you have to scroll back to see it all
clear % clear preexisting variables (except globals)

B. WEBSITES
Click to go to the Matlab home page
or their free file exchange page.

C. MAKE A BUTTON FOR ABORTING AN OPERATION.
Some operations can take considerable time, and you may want to abort before it finishes. This code will create a big button labeled 'Abort'. Clicking it causes the operation to terminate nicely.
1. Create the 'abort' button at the beginning of the program; make it invisible
vh.abort=uicontrol('tag','abort','callback',[cb ' abort'],...
'visible','off','position',[10 10 150 50],... % BIG button
'string','ABORT','foregroundcolor','red',... % big, BOLD, red letters
'fontweight','bold','fontsize',18)
2. Create the callback in the appropriate place. The operation should simply set the global variable v.abort.
v.abort=1;
3. When you begin an operation that can be aborted, make the button visible
set(vh.abort,'visible','on'); v.abort=0;
4. Now start the operation. Put this check at the top of the loop, and anywhere else it might be needed
if abort; set(vh.abort,'visible','off'); v.abort=0; return; end
5. At the end of the operation, make the button invisible again
set(vh.abort,'visible','off')

2007-01-18 04:59:50 · answer #3 · answered by jithu k 2 · 0 1

fedest.com, questions and answers