chapter  9
10 Pages

Object-Oriented Programming

Oops. You created an entirely new field in the struct, rather than modifying the existing one. Worse yet, every time you pass z to a function, a robust function would need to make sure all the required fields are present. What should it do with fields such as z.Particle that it does not recognize? And there is no way to get a list of all functions that can take this struct z as input, or produce one on output. Enter the MATLAB object. Think of it as a specialized struct with fields that cannot change unless you change a

“8primer” — #74

file that defines the object (the classdef, or class definition file). The classdef file specifies everything you can do with or to the object (these are called methods). Fields in an object act like the fields of a struct, but you cannot add or remove them arbitrarily. For this exercise, we will create an object class that represents a matrix factorization. This first version has no methods, just the L and U factors themselves (LU = A, where L is lower triangular and U is upper triangular). Open the M-File Editor with a blank classdef file (File ◮New ◮Class) and create an M-file called factor0.m. The filename and the classdef name must match:

Now in the Command Window, create an object F of class factor0, and populate its L and U fields:

A = rand(4)

F = factor0

[F.L F.U] = lu(A)


Try to create a new field by typing F.x=0 (for example) in the Command Window. MATLAB refuses to do it, and gives you a warning. Click on the underlined Methods in the display of F. This gives a list of the methods that can be used on F. The only method is factor0, which creates an empty object with the fields L and U. Clicking on the factor0 link displayed in the Command Window displays the help for the class. To add new properties, you must edit the factor0.m file. A word of caution: if you edit factor0.m when you still

“8primer” — #75

have factor0 objects in your workspace, you may get a warning message saying that those objects must be cleared first before the changes can be applied. Use clear classes to clear all your variables and classes. This can make it difficult to edit and test your code, since you must clear all your test data. Create another M-file that starts with clear classes, creates some test data, and then tests your new object class. The simple factor0 class acts just like a struct except that it is not as flexible (which is sometimes a good thing). If G is not already defined, [G.L G.U]=lu(A) acts just like F in this example, except that G is a struct, not an object of the factor0 class. So G.x=0 works, but F.x=0 does not.