1 / 70

CITS2401 Computer Analysis & Visualisation

Faculty of engineering, computing and mathematics. CITS2401 Computer Analysis & Visualisation. School of Computer Science and Software Engineering. Topic 5 Matlab Structures. Material from MATLAB for Engineers, Moore, Chapter 7,11 Additional material by Peter Kovesi . Overview.

luna
Download Presentation

CITS2401 Computer Analysis & Visualisation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Faculty of engineering, computing and mathematics CITS2401 Computer Analysis & Visualisation School of Computer Science and Software Engineering Topic 5 Matlab Structures Material from MATLAB for Engineers, Moore, Chapter 7,11 Additional material by Peter Kovesi.

  2. Overview • Input and Output • Elementary data structures • Cell arrays • Constructing cell arrays • Cell arrays of strings • Structures • Arrays of structures

  3. User Defined Input • To this point we have “hard coded” the values of variables into our M-file programs • The input function allows us to prompt the user to enter a value

  4. The input function is used in an M-file program to prompt the user to enter a value The prompt is displayed in the command window

  5. Input accepts a variety of data • Scalars • Matrices • enter inside square brackets • Character strings • enter inside single quotes • Or… specify string input with ‘s’

  6. Run this program twice more – once with numeric input and once with character input Matrix input Character input

  7. Indicates that the input should be interpreted as a string

  8. Output Options • Enter the name of a variable • Use the disp function • Use the fprintf function • Use the sprintf function

  9. disp The display (disp) function can be used to display the contents of a matrix without printing the matrix name The disp function can also be used to display a string

  10. Strings are really arrays of character information The result is a character array

  11. You can combine disp functions to create meaningful output from an M-file program, but the result of each disp function is on a separate line.

  12. Although these characters look like numbers, they are interpreted by the computer as part of a character array – they no longer have any numeric meaning

  13. This MATLAB program mimics a conversation, by using the input and disp functions. Watch the interactions as it runs in the next slide

  14. Formatted Output • fprintf gives you more control over your output than the disp function • You can combine text and numbers • You can control how many digits to display, and their position • Arguments: • format-string • includes place holders and formating information for numbers • List of matrices

  15. 8 total spaces2 after the decimal pointfloating point format Variable Place holder for your variable value

  16. You can also use exponential format

  17. X is a matrix /n is a carriage return

  18. Despite the way it looks, the computer always considers a matrix as one big list, working down one column at a time

  19. Other ways of giving feedback error(msg) • displays the specified error message msg and causes the function to exit. Used for "fatal" errors where there is no point (or way of) continuing. If msg is an empty string no action is taken. warning(msg) • displays the specified warning message msg, but allows the function to continue execution. Used for non-fatal errors. isnumeric(V) • returns True (1) if V is a numeric array, False (0) otherwise. ischar(S) • returns True (1) if S is a character array, False (0) otherwise.

  20. Checking function arguments • There are a number of functions that you can use to check arguments provided to a function: nargin • returns the number of arguments that were supplied to the function. This is a function that takes no arguments. nargout • returns the number of output arguments that the function result is being assigned to in the calling program. This is a function that takes no arguments. msg = nargchk(minArgNo, maxArgNo, actualArgNo) • returns an error message msg if a function is called with too few or too many arguments (i.e. if actualArgNo is outside [minArgNo, maxArgNo]). If the number of arguments is within the range an empty string is returned.

  21. The all function • There is a function called all that checks if an array contains all ones. all(V) • If V is a vector, all returns True if all the elements of V are nonzero. If V is a matrix, all operates on the columns of V, returning a vector. • For example: >> all([3 4 5 6] == [3 1 5 4]) ans = 0

  22. An example Let's make the input to trianglearea "bullet proof": % TRIANGLEAREA: A function to find the area of a triangle. % % Usage: area = trianglearea(width, height) % % Arguments: width - The width of the triangle. % height - The height of the triangle. % % Returns: area - The area of the triangle. % % Author: Lecturers % Date: August 2010 function area = trianglearea(w, h)

  23. % Check for legal number of input arguments. msg = nargchk(2, 2, nargin); error(msg); % If msg is not empty, this will print % out msg and stop the function. % If msg is empty, this command is ignored. if ~isnumeric(w) | ~isnumeric(h) % Print an error message and return. error('Arguments must be numeric.'); end if ~all(size(w) == [1, 1]) | ~all(size(h) == [1, 1]) % Print an error message and return. error('Arguments must be scalar.'); end

  24. if w < 0 | h < 0 % Print an error message and return. error('Arguments must be non-negative.'); end if w == 0 | h == 0 % Print a warning message, but do not stop % execution. warning('width or height is zero.'); end % If we get to this line, we can safely assume%the input is valid. area = w*h/2; end % function trianglearea

  25. Elementary data structures • So far the only data structure we have seen is the array - a collection of identically typed data objects (typically numbers) stored sequentially in memory. • Often one wants to work with a collection of data objects that are of different types. • We may want to link character strings, numbers, or arrays of numbers together into data structures. • We may also want to use mechanisms other than arrays for handling collections of data objects.

  26. Kinds of Data Stored in MATLAB Matrices Symbolic Objects - Symbolic Toolbox Character Logical Numeric Integer Floating Point multiple signed integer types multiple unsigned integer types single precision double precision complex real MATLAB’s arrays can store different types of data

  27. Numeric Data Types • Numeric data is stored in numeric arrays • The default data type is double precision floating point • Every time you enter a number into MATLAB, the program assumes you’ve entered a double • MATLAB conforms to the IEEE standards that specify the meaning of the double data type

  28. When you define numeric values they default to doubles Each value in a double array needs 8 bytes of memory to store

  29. Remember that 8 bits = 1 byte Each of these types require a different amount of storage Integers • Integer arrays are new to MATLAB 7 • Integers are stored in integer arrays

  30. You can determine the number of possible values allowed in the integer data type • Each of the integer types uses a different amount of storage, and can thus save different ranges of values • Determine the size range using • intmax and intmin

  31. When do we use integers • Integer arrays can be used to store image information • These arrays are often very large, but there are a limited number of colors used in many of these images to create the picture. • Storing them as unsigned integer arrays reduces the storage requirement dramatically.

  32. Complex numbers • Default is double • Twice as much storage is needed because the real and imaginary components must be stored • Could also be stored as a single or integer

  33. Character and String Data • Character arrays store character information • A character array is produced from a string • Any string represents a character array in MATLAB • Each character requires 2 bytes of storage

  34. The fifth element of the H array is the letter y

  35. Cell Arrays (Text: Section 7.2.) • A cell array is a special kind of array in Matlab. • Instead of each location in the array holding a number, each element of a cell array is an address, or pointer, or reference, to another data structure. • These "pointed to" data structures can be of any type. • A cell array is like an address book that groups together information relevant to a problem.

  36. An Example • The addresses are the addresses in memory where the relevant data objects are stored. For example: >> a = [1, 2 % A 2x2 matrix. 3, 4]; >> b = 'hello'; % A character string. >> c = [7, 8, 9]; % A 1x3 matrix. >> d = {a, b, c}; % d is a cell array that holds % the addresses of, or “points % to”, a, b, and c. • Notice curly brackets {}.

  37. Cell arrays vs. normal arrays • The key difference between cell arrays and normal arrays is that cell arrays contain pointers to data structures instead of data.

  38. Curly brackets • Cell arrays use curly brackets ({}) for selecting and displaying contents of cells. • Curly brackets indicate to Matlab that we want to refer to the data at the address stored in the cell array, rather than the address itself. • Curly brackets display the contents of the data structure contained at that position in the cell array. >> d{1} % Access data stored at first address % in d using curly brackets. ans = 1 2 3 4

  39. Round brackets • Round brackets display “what” is pointed to by the position in the cell array. >> d(1) % d(1) tells you that the first address % in d points to a 2x2 array of doubles. % You never have access to the actual % address itself. ans = [2x2 double] • But how the “what” is displayed depends on what it is! >> d{1} = 24 d(1) ans = [24] % not [1x1 double]

  40. Curly vs. round brackets (cont.) >> d{2} % Access data at second address in d. ans = hello >> d(2) % Display what is residing at the % second address of the cell array d. ans = ‘hello’ • Matlab displays the data structures in each element of a cell array in a condensed form that limits each data structure to a single line. • If the entire data structure can be displayed on the single line, it is. • Otherwise, a summary is displayed.

  41. Constructing cell arrays • You can build cell arrays in the same way you build ordinary arrays, using curly brackets ({}) instead of square brackets ([]). >> a = { [1 2], 'Jill'; [5 6 7; 8 9 10], 1 } % Construct a 2x2 cell array containing four % elements: a 1x2 array, a string, a 2x3 array, % and a scalar. a = [1x2 double] 'Jill' [2x3 double] [ 1] >> a{2, 1} % Access data at cell{2, 1} ans = 5 6 7 8 9 10

  42. Adding extra data to a cell array • If you add extra data, Matlab will automatically resize the cell array to accommodate it. • For example: >> a{1, 3} = 'new data' % Add an element in % row 1, column 3. a = [1x2 double] 'Jill' 'new data' [2x3 double] [ 1] [] • To add the new string, Matlab needs to add a third column to the cell array. • Cell arrays are themselves just arrays - they must remain rectangular. • Note that the element {2, 3} in the cell array is set to the empty matrix.

  43. What happens if brackets are wrong? • If you use the wrong kind of addressing (the wrong kind of brackets), Matlab will warn you with a message like this: >> a(1,3) = 'new data' % Attempt to set the address % stored in cell array % element(1,3) to ‘new data’ ??? Conversion to cell from char is not possible.

  44. Extract data from a cell array • We can extract individual elements from data stored in a cell array by adding the normal indexing commands to the cell indexing commands. >> c{1,1}(2) % Access element 2 of the matrix referred % to by cell array element {1,1}. ans = 2 >> c{2,1}(1:2, 2:3) % Access elements from the % matrix referred to by cell % array element {2,1}. ans = 6 7 9 10

  45. View the contents of a cell array • You can view the contents of a cell array using the celldisp and cellplot functions. For example: >> celldisp(a) % Prints out the contents of % each cell in the cell array a. a{1,1} = 1 2 a{2,1} = 5 6 7 8 9 10 a{1,2} = Jill a{2,2} = 1 etc...

  46. Graphical representation of the cell array >> cellplot(a) % Displays a graphical representation % of the cell array a.

  47. Memory pre-allocation for a cell array • You can pre-allocate memory for a cell array with the cell function. >> c = cell(1, 5) % Allocates memory for a 1x5 % cell array. • Note that this call to cell only allocates space for the 5 addresses in memory - there is no data associated with these addresses yet (all we have is an empty address book with 5 blank entries). c = [] [] [] [] [] >> whos Name Size Bytes Class c 1x5 20 cell array • The cell array uses 20 bytes of memory - 4 bytes to store each address. This will be true on a 32 bit machine.

  48. Attach data to a cell array • Having allocated space for a cell array, we can "attach" data to the array as we wish. • For example: >> c{4} = 'hello’; >> d = [11 12 13 14]; % Construct a 1x4 matrix. >> c{1} = d % Attach the new matrix to c{1}. c = [1x4 double] [] [] 'hello' [] • Actually it is a copy of d that is attached to c{1}. • If d is modified or even deleted, the contents of the data referenced by c{1} will be left intact (pass-by-value).

More Related