Skip to Main Content Skip to Search
File Exchange
MATLAB Newsgroup
Link Exchange
  Blogs  
 Contest 
MathWorks.com

Loren on the Art of MATLAB

January 5th, 2007

Class Initialization for Variables

A while ago, I wrote an article sharing some ideas for Programming for Multiple Datatypes. Recently, a colleague asked me a related question for writing some M-code to be used in an embedded MATLAB block in Simulink. He also wanted to be able to generate code from it, using http://www.mathworks.com/products/rtw/ Real-Time Workshop>, and not use it only for simulation. Together, we tried several ideas.

Contents

Conversion to a Known Class

It's typically straight-forward to convert data into a known class. Simply use the name of the class as the conversion method. If that particular conversion is supported, mission accomplished.

md = magic(3);
class(md)
ans =
double

md is a double precision magic square. Now convert md to uint16.

mu16 = uint16(md);
class(mu16)
ans =
uint16

Comparing the arrays, isequal says they are the same since isequal ignores class or type in comparison.

eqvals = isequal(md, mu16)
eqvals =
     1

If you want to check the classes are also the same, you can do something like this.

sameclass = strcmp(class(md),class(mu16))
sameclass =
     0

Conversion to the Class of Another Variable

If you want to write a generic algorithm and you need to be able to handle inputs of a variety of classes, there are some techniques you can use to ensure that the calculations are done in the class you want.

If you want to initialize some variables in your calculation to 0, but in the class of the input, you could use a switch statement and check all of the builtin types. This is tedious, error-prone, and does not scale well.

You could also use the zeros function with the final classname argument. This works for builtin numeric types.

valsaved = zeros(1,1,class(mu16));

Another method that also works for builtin types is using the function cast.

b = cast(0.0,class(mu16));

What do we do if we have an input that behaves like a builtin numeric clas but isn't built in? Some examples might be the sym object in the Symbolic Math Toolbox (assuming the variable contains values that can be converted to numeric ones) or the fi fixed-point object from the Fixed-Point Toolbox.

msym = sym(md);
mfi = fi(md);
whos
  Name           Size            Bytes  Class              Attributes

  ans            1x6                12  char                         
  b              1x1                 2  uint16                       
  eqvals         1x1                 1  logical                      
  fhfi           1x1                16  function_handle              
  fhsym          1x1                16  function_handle              
  md             3x3                72  double                       
  mfi            3x3                    embedded.fi                  
  msym           3x3               622  sym                          
  mu16           3x3                18  uint16                       
  sameclass      1x1                 1  logical                      
  valsaved       1x1                 2  uint16                       
  zfi            1x1                    embedded.fi                  
  zsym           1x1               126  sym                          
  zsym2          1x1               126  sym                          
  zsym3          1x1               126  sym                          

Here's a way to convert to an arbitrary class, using str2func

fhsym = str2func(class(msym));
zsym = fhsym(0.0);
fhfi = str2func(class(mfi));
zfi = fhfi(0.0);
whos
  Name           Size            Bytes  Class              Attributes

  ans            1x6                12  char                         
  b              1x1                 2  uint16                       
  eqvals         1x1                 1  logical                      
  fhfi           1x1                16  function_handle              
  fhsym          1x1                16  function_handle              
  md             3x3                72  double                       
  mfi            3x3                    embedded.fi                  
  msym           3x3               622  sym                          
  mu16           3x3                18  uint16                       
  sameclass      1x1                 1  logical                      
  valsaved       1x1                 2  uint16                       
  zfi            1x1                    embedded.fi                  
  zsym           1x1               126  sym                          
  zsym2          1x1               126  sym                          
  zsym3          1x1               126  sym                          

There is a limitation to this method for Simulink users who want to use embedded MATLAB in the generated code since str2func is not supported for that situation.

Methods that Should (Usually) Work for All Types

So, how to get that initial value to 0 in the right class? Do some arithmetic! Here are two possibilites, illustrated with the sym variable msym.

zsym2 = 0*msym(1);
zsym3 = msym(1)-msym(1);

Why do I say "usually" in the title of this section? The calculations should be supported for classes that behave numerically.

Well, first, it allows me to refer you to a great numerical computing reference.

  • Numerical Methods that [Usually] Work, Forman S. Acton, Harper & Row, Publishers, ISBN 0883854503 (first published in 1970. On my copy the words on the cover are embossed in gold ink, except the word "usually" which is simply impressed.

Second, I have to admit that these methods only work for finite values of the first input. What would you do if you had to guard against non-finite values?

Other Methods or Preferences

Do you have other methods that would work for the conversion to an unknown class? Or preferences on a method to use? If so, please post here.


Get the MATLAB code

Published with MATLAB® 7.3

11 Responses to “Class Initialization for Variables”

  1. Dan K replied on :

    I’m not really sure if this is applicable to this forum, but the conversion which I most often face is not knowing whether a variable that I want to use will be:
    A=’linear’; or
    A={’linear’};

    I can do a messy check & convert whenever I need to use it, but I wonder: is there a squeeze like command that removes the cell structure surrounding a single cell? This seems particularly useful to me in the case of varargin.

    Thanks,
    Dan

  2. Loren replied on :

    Dan-

    You could use char() if you know A is a single string, either in a cell or not. But it doesn’t work for numeric types. Would that help?

    –Loren

  3. Dan K replied on :

    Loren,
    Yes, it does help in at least some cases. On the other hand it might be nice to have a command which easily extracts the contents of singleton cell arrays. Maybe in R2008 : )

  4. Loren replied on :

    Dan-

    Here’s a quick anonymous function:

    c1contents = @(c) c{1}

    >> s = {'fred'}
    s =
        'fred'
    >> c1contents(s)
    ans =
    fred
    >> c1contents({2})
    ans =
         2
    >> c1contents({1 4 17})
    ans =
         1
    

    –Loren

  5. Darius replied on :

    interesting

    ——————
    http://privacy.emigrantas.com - all about privacy in the Internet

  6. Aliza replied on :

    Hi,
    I am using simulink-embedded RTW - Tornado, and my target is a power PC. Up to now i’ve used the software emulation to generate the math for simulink’s default double signals. But we’ve come up with execution time problems.
    For this reason we’ve switched to the hardware ALU for math computations. The problem is, it can only work with single-precision signals.
    Do you know of any way to create a totally single float model (including, for instance, the use of sinf rather than sin that works only on doubles etc.)?
    I have been having much difficulty with this issue and would greatly appreciate the help.
    Thank you,
    Aliza

  7. Loren replied on :

    Aliza,

    You’d be better off contacting technical support for issues about Simulink. Here’s the link:

    http://www.mathworks.com/support/service_requests/contact_support.do

    –Loren

  8. Martin replied on :

    Hi,

    is there a way to work with variables that belong to a class rather than to an instance of a class ?
    In Java I would write “private static” inside the class definition. I tried it with “persistent”, but Matlab doesnt like constructions like: “persistent n.Input” e.g. inside the constructor with n being my object.

    Thanks for your help,
    Martin.

  9. Loren replied on :

    Martin-

    The short answer is, not easily. persistent requires variable and n.Input is a temporary variable since it is a field in a struct or object. You could have a persistent variable in your constructor and then assign its value to a field in the object. Or you could have some state in your object by storing your “persistent” variable in the constructor where the constructor uses nested functions to preserve state. There is a relatively new example on the File Exchange that does something similar: http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=17240&objectType=FILE

    –Loren

  10. Martin replied on :

    Hi,

    I am using Matlab 2007b and get the following error:

    Exception in thread “AWT-EventQueue-0″ java.lang.OutOfMemoryError: GC overhead limit exceeded.
    And another one concerning java-heapspace.
    There is no bug in the program, since on a linux-workstation it works well. But on a plain Windows machine (java 1.5 / 1.6) I get this messages.
    How do I handel java memory issues under Matlab 7.5 ??

    Thanks a lot.

  11. Loren replied on :

    Martin-

    Please contact tehcnical support for your issue.

    –Loren

Leave a Reply


Loren Shure works on design of the MATLAB language at The MathWorks. She writes here about once a week on MATLAB programming and related topics.

  • J.B. Brown: Ah, and I am at fault for simply testing collinearity with the origin in the example above.
  • J.B. Brown: Indeed, > collinear( [0 3],[0 8],[0 -1e21+2e-15] ) ans = 1 > collinear( [0 3],[0 8],[0 -1e22+2e-15]...
  • OkinawaDolphin: Loren, thank you for telling me where to download timeit. Here are the two functions I just tested...
  • Loren: JB- It looks to me like Ilya’s solution and therefore yours are equivalent to the determinant. As Tim...
  • Loren: OkinawaDolphin, timeit can be downloaded from the File Exchange. Steve Eddins is the author. It does not ship...
  • OkinawaDolphin: It seems that neither R2007a nor R2007b have the function timeit, but I investigated computation time...
  • J.B. Brown: It would appear to me that Ilya Rozenfeld’s solution would be the cleanest. Just to help those who...
  • Loren: Markus- Congratulations on winning! And a nice illustration of how the size matters. Small enough, and the...
  • Markus: Hi Loren, which version is fastest also depends very much on the matrix dimensions. Look at my test function:...
  • Duncan: OkinawaDolphin, Regarding why your third example is slower than your second example, the result is in fact...

These postings are the author's and don't necessarily represent the opinions of The MathWorks.

Related Topics