Global variables for class library in matlab
Asked Answered
T

1

5

I have several matlab classes declared. How could I declare constants which are seen in all classes?
For instance: these constants can be physical constants which are used in methods of all classes. The first thing coming to mind is using global variables. Is there any better way? It will be nice to declare these constants in a separate file.

Tomtit answered 14/10, 2013 at 13:13 Comment(4)
Did you consider creating a class that contains all these constants? Call it physicalConstants.m, then refer to physicalConstants.myConstant etc.Dissert
Do you mean create more abstract class with these variables only and use the inheritance?Tomtit
ah, ok, I've got the point.Tomtit
If your classes are all "instances of the real world", then "properties of the real world" can be an abstract superclass. I was thinking of just having a structure (class) in which you "park" these values.Dissert
D
7

A class containing the constants is a nice clean way to do this. See the article in Matlab documentation: http://www.mathworks.com/help/matlab/matlab_oop/properties-with-constant-values.html

For example, if you create a class called NamedConst as follows:

classdef NamedConst
   properties (Constant)
      R = pi/180;
      D = 1/NamedConst.R;
      AccCode = '0145968740001110202NPQ';
      RN = rand(5);
   end
end

You can reference values with

radi = 45*NamedConst.R

You can find more details in the link given.

Dissert answered 14/10, 2013 at 13:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.