elifcansu
elifcansu

Reputation: 43

Passing variable to a class in MATLAB

It is my first time asking a question here and I am quite new to MATLAB. So, I am sorry in advance if my explanation is faulty or insufficient. I'll be happy to hear any advice to improve myself.

I would like to create a class which has an array of a certain size. Let's call this class 'MyClass'. My class is as follows:

    classdef MyClass
       properties 
           A = array2table(zeros(ArraySize,1));
       end
    end

The variable ArraySize is defined in my main.m file and i want to create an object from this class within the same file:

    ArraySize = 10;
    MyObject = MyClass; 

However, the class I created does not recognize the ArraySize variable. Could somebody tell me if there is an easy way to achieve this? So far, I tried to make it a global variable, I tried using 'load' function to pass parameters between files. I tried defining the class inside a function. None of them seem to work. I read about 'handles' in forums and i got the idea that it somehow can be related to the solution of my problem, but I do not really know how to work with them. What I understood so far is that handles correspond to pointers in C++. I would like to know if they can be used to solve my problem and if so, how exactly. Thanks in advance.

Upvotes: 3

Views: 192

Answers (1)

Suever
Suever

Reputation: 65460

You should just write your constructor to accept ArraySize as an input argument and then initialize the value A inside of your constructor.

classdef MyClass
   properties 
       A
   end

   methods 
       function self = MyClass(arraySize)
           self.A = array2table(zeros(arraySize,1));
       end
   end
end

And then instantiate your class

myObject = MyClass(ArraySize);

And with regards to handle classes, check out this page of the documentation to see recommendations on when to use handle and value classes.

Upvotes: 2

Related Questions