Passing a variable to a class in MATLAB
This is my first question asking a question here and I am completely new to MATLAB. Therefore, I regret in advance if my explanation is wrong or insufficient. I would love to hear any advice on how to improve myself.
I would like to create a class that has an array of a specific size. Let's call this class "MyClass". My class looks like this:
classdef MyClass
properties
A = array2table(zeros(ArraySize,1));
end
end
The ArraySize variable is defined in my main.m file and I want to create an object from this class in the same file:
ArraySize = 10;
MyObject = MyClass;
However, the generated class does not recognize the ArraySize variable. Can anyone tell me if there is an easy way to achieve this? Until now I tried to make it a global variable, I tried to use the "load" function to pass parameters between files. I tried to define a class inside a function. None of them seem to work. I was reading about "pens" on the forums and I got the idea that it might somehow be related to the solution to my problem, but I really don't know how to work with them. So far I've figured out that descriptors correspond to C ++ pointers. I would like to know if they can be used to solve my problem, and if so, how exactly. Thanks in advance.
source to share
You should just write your constructor to take ArraySize
as an input argument and then initialize the value A
inside your constructor.
classdef MyClass
properties
A
end
methods
function self = MyClass(arraySize)
self.A = array2table(zeros(arraySize,1));
end
end
end
And then instantiate the class
myObject = MyClass(ArraySize);
And as far as classes are concerned handle
, take a look at this documentation page to see guidelines on when to use handle
and value classes.
source to share