I would like to do something like the following code where all 3 properties are statically known to be size (1,10) without having to explicitly re-write the 10 at the property declaration.
classdef Example
properties(Constant)
length_of_vector = 10;
end
properties
x_data(1, Example.length_of_vector);
y_data(1, Example.length_of_vector);
z_data(1, Example.length_of_vector);
end
end
This syntax is not valid, is there a way to accomplish this without re-writing 10 in all three places? My real use-case has several dimensions that have statically known sizes and I'd really like to be able to specify what length they are in the declaration so that maintainers will know what size is expected but the constants can be changed and it automatically updates all the property sizes that depend on it.
To clarify there are a few alternatives I can do:
classdef Example
properties(Constant)
length_of_vector = 10;
end
properties
% this gives the behaviour at runtime I want but don't want to have to specify the 10 literally
x_data(1, 10);
% this gives the correct initial conditions but is not quite the same thing
y_data(1, :) = zeros(1,Example.length_of_vector);
% this is what I am using now, if you change length_of_vector without modifying the
% 10 here it throws an error immediately so you get pointed to where you have to fix it
z_data(1, 10) = zeros(1,Example.length_of_vector);
end
end
The way these are different is that obj.x_data = pi with the size set to (1,10) means it sets the x_data to a 1x10 vector where each element is pi where as x.y_data = pi which was size (1,:) sets it to a 1x1 pi which means that functions that expect inputs to have the exact same size break (and writing the number literally into the size is less painful than refactoring the initialization code which does do obj.z_data = 50; to initiate the simulation at a given height.)
Example.length_of_vectoris valid inside methods of the class, and outside the class as well. I guess it is not valid in your code because MATLAB is still loading the class definition when it encountersExample.length_of_vector, butExampleis not yet loaded.I can think of two ways to work around this:
Declare the size of the properties in the constructor:
Define your constants in a different way. A common method is to use a function. You can put this function at the end of your
classdeffile, outside theclassdefblock:With this method, your constant is private to your class, it cannot be accessed from outside. To make it public, you would have to add a static method to your class that returns the constant.