MATLAB: multiple object instances - oop

I am new to object oriented programming, especially with MATLAB. Here is a basic question about multiple instances of objects.
I describe my problem in a simplified setting.
First I defined two classes: Node and Edge, where the Node has a property value and the Edge contains a Node:
classdef Node < handle
properties
value
end
and
classdef Edge < handle
properties
node1
end
Then I created one node and one edge
n1=Node;
e=Edge;
and I associate this node to the edge e
e.node1=n1;
Now comes the question, if I assign the value to n1
n1.value=5;
I can refer this value from e with the expected answer:
e.node1.value
ans = 5
But if I want to delete the node n1 referring the instance in e
e.node1=[]
then the object node1 in the object e is gone, but the Node variable n1 is still there.
What I had in mind (and wanted) is that the variable n1 and e.node1 is the same thing, but it looks like the MATLAB created two instances of the Node n1, one is n1 itself and the other one is node1 inside the object e, although I can refer the value of n1 from node1.
My question is that, if I want to delete n1 from its associated e, what would be an efficient way to do so? Any other explanations of the background of Object Oriented MATLAB are definitely welcomed.

You need to subclass the objects you wish to refer to by reference as handle. This will allow the reference in the workspace to match the same object referred to by the referring class. Here's an example:
classdef MyEdge < handle
properties
node1
end
end
classdef MyNode < handle
properties
value
end
end
n = MyNode
e = MyEdge;
n.value = 7
e.node1 = n
disp(e.node1.value)
7
n.value = 42
disp(e.node1.value)
42
Here's some other extraneous info, let me know if it's just totally off track. :-)
When you create an object in Matlab, and then save a reference to that object somewhere else, it does behave like a real OO reference. So, n1 and e.node1 reference the same thing. However, when you e.node1=[] you remove the reference of n1 from the e object. The n1 object still exists in the workspace, but e has no reference to it. I believe it works the way you desire, just that removing the reference, does not allow for automatic garbage collection unless there is no reference to the Matlab object in the Matlab workspace. Something like:
e1 = Edge
e1.node1 = Node
That should accomplish the garbage collection, i.e. once e1.node1 points to [] the Node object is eliminated. However if you had:
e1 = Edge
e2 = Edge
e1.node1 = Node
e2.node1 = e1.node1
e1.node1.value = 5
if( e1.node1.value == 5 )
disp('It''s equal!!')
end
So they each store the reference to the same object.

Related

What do we actually mean by like objects,tables have a STATE and tables are objects in more than one sense programming in OOP and data structures?

i have been learning a roblox lua language and many times i have came across something called table has a state like objects line and i really don't understand that as i don't how to visualize it,like what it actually means
i have been reading this roblox lua article and have came across this line again: Object-Oriented Programming(https://developer.roblox.com/en-us/articles/Object-Oriented-Programming)
this is some bit of that article and it contains that line:
As Lua supports duck typing through the use of Metatables, the ability to create “objects” can be achieved. This is essentially objected-oriented programming. A Tables in Lua is an object in more than one sense. Like objects, tables have a state. Like objects, tables have an identity that is independent of their values; specifically, two objects (tables) with the same value are different objects, whereas an object can have different values at different times, but it is always the same object. Like objects, tables have a life cycle that is independent of who created them or where they were created.
can somebody help me with this i have been trying search this on google but nothing similar shows up,like what actually it is?also what do we mean by tables as objects?
A simple way to think about tables is that they are dictionaries or associative arrays. They can also act like regular arrays and lists too. But under the hood, they are storing values in a key-value pair system.
With that in mind, let's just break down that paragraph into each line talk about what it all means.
1) As Lua supports duck typing through the use of Metatables, the ability to create “objects” can be achieved. This is essentially objected-oriented programming.
This means that if an object walks like a duck and quacks like a duck it can reasonably be expected that it is a duck. Lua doesn't technically have OOP classes, but we can make lua tables walk and quack like OOP classes.
When you create an instance of a class in other programming languages, that instance has all the properties, functions, and fields of that class type. In lua, we can make tables pretend to do that by messing with metamethods.
local TestClass = {}
TestClass.__index = TestClass
function TestClass.new()
local tc = {
secret = "hello world"
}
setmetatable(tc, TestClass)
return tc
end
function TestClass:printSomething()
print(self.secret)
end
-- construct a new "object" of TestClass, and call one of its functions
local a = TestClass.new()
a:printSomething()
What's happening here is TestClass is overwriting its __index metamethod. This means that when a table tries to look up a key in its table, instead of looking up the index from its own table, it will use the table index of TestClass. The new() function creates a brand new table, then overwrites its metatable with TestClass's, ensuring that the new table behaves like the original TestClass object would.
So even though the tc object does not have an explicitly defined new() or printSomething() function, calling the functions on that object still works. This is how lua can fake being object oriented.
2) A table in Lua is an object in more than one sense. Like objects, tables have a state.
This simply means you can store things in tables like a container.
local a = {
foo = 5
}
print(a.foo) -- 5
3) Like objects, tables have an identity that is independent of their values; specifically, two objects (tables) with the same value are different objects...
local a = {}
local b = {}
print(a == b) -- false
print(a == {}) -- also false
4) whereas an object can have different values at different times, but it is always the same object.
local a = {
foo = 5
}
print(a) -- some table pointer id
a.foo = 10
print(a) -- still the same table pointer
5) Like objects, tables have a life cycle that is independent of who created them or where they were created.
Lua tables are kept alive in memory based on how many objects have reference to them. This means that their object lifecycle can exist outside of their original scope.
local function createTable()
-- make a local table to this function
local a = {}
-- make a table to return to the program
local b = {
c = a
}
print("a = ", a) -- some table pointer
print("b = ", b) -- some other table pointer
return b
end
-- a is no longer in scope, and in other languages would be cleaned up
-- but since b holds a reference to it, it is not removed.
local d = createTable()
print("d =", d) -- should print out b's table pointer
print("d.c = ", d.c) -- should print out a's table pointer
Hopefully this clears up some confusion.

.NET Reflection - Retrieve a Property Without Knowing Its Name

I've been given a collection of WCF services to use which are all the same, save for the way certain properties of the objects returned by the services are named. If I have services A, B, and C, they each return nearly identical objects except that the objects' properties have been changed to reflect the service from whence they came. So, service A returns an object called responseA with a property responseA.AValidation and B returns a similar object with a property called responseB.BValidation.
Now, as much as might like to make changes to the services, I can't. Which means I'm stuck writing the exact same code for each service all to check for various possible error conditions,
If responseA.AErrors.Length > 0
...
If responseB.BErrors.Length > 0
...
and so on
What I'd love is to write one generic class that can use any of these services and has a single method to perform the above checking on any of them However, I'm stumped on how to check the value of a property when the name of that property can be slightly different from class to class.
So, is it possible to return the value of a property that I don't know the name of until runtime?
Here's what I've tried so far
Dim responseType As Type = responseA.GetType()
For Each Prop In responseType.GetProperties()
If Prop.Name.Contains("ErrorInfoTypes") Then
Dim errorTypes()
errorTypes = Prop.GetValue(GetType(Array), Nothing)
If errorTypes.Length > 0 Then
'Deal with the fact there are errors.
End If
Exit For
End If
Next
This complies, but .GetProperties returns no properties. What am I missing?

A list of modules or classes ( in VB 2010 Express)

I have a set of modules, e.g., itemOne, itemTwo, ... , itemTen, which have similar methods and sub-classes within themselves. I have used "Delegate" and "Enum" to keep track of these methods, and have a systematic way of calling them in a for loop. HOWEVER, I am not sure how to make a collection or array of the modules, with the goal of being able to loop through them.
End goal below, in pseudo code
For Num = One to Ten
With item<Num> % This could be itemOne, or itemTwo, etc. I do NOT know how to do this
% Call function with the help of for loops. I know how to do this
End With
End For
It would help if there is a way to use a array of strings, and execute them as code during runtime. Something like -- Call String2Code("ItemOne").Something.SomeMethod(), where SomeMethod is a subroutine.
It doesn't necessarily have to be a String2Code type of implementation. In general, I am looking for a way to keep track of an array of "delegates to modules". Of course, "Delegate" only works for Sub/Function in VB, and I have been unable to find a technique to handle modules in a similar fashion. If the address pointers of these modules are stored in an array, I should be able to loop through them.
I will be grateful for any advice. Thank you.
In retrospect this might be simpler. You should be making them classes in my opinion not modules...
Please note that I have used One, Two, and Three below to represent an object of your different types.
Dim col as List(Of Object)
col.add(One)
col.add(Two)
col.add(Three)
For i as integer = 0 to col.Count -1
If typeof col(i) is [ModuleType1] Then
CTYPE(col(i), ModuleType1).SubClass.Method()
Else If TypeOf col(i) is ModuleType2 Then
CTYPE(col(i), ModuleType2.SubClass2.Method2()
End If
Next
Optionally, you can just make col an array of Objects.
Dim col() as Object = {One, Two, Three}
Ideally you would avoid using Object and instead all of your modules would use inheritance to group like methods together. They instead of Object you could use the ParentObject which would maintain the like functionality instead of casting all of the time.
Is this clear as mud?
Steve

MATLAB OOP: Communication between objects of different subclasses

I am at the beginning of a bigger project, where I have to rewrite existing MATLAB script code. I was asked to use MATLAB's object oriented programming support to get a more flexible and robust program.
I got to a point, where I wondered how to let objects of different subclasses communicate or better: what is the best or most elegant/efficient/user friendly way to do that.
Example:
Superclass A (handle class):
classdef A < handle
properties
myvar
end
methods (Access = protected)
function calc_myvar(obj)
%calculate myvar with some code
obj.myvar=...;
end
end
end
Subclass B:
classdef B < A
properties
subclassvar
end
methods (Access = protected)
function calc_subclassvar(obj)
%calculate subclassvar with some code
%needs myvar of an object of class C
%C.myvar
obj.subclassvar=...;
end
end
end
Subclass C:
classdef C < A
properties
%some other properties
end
methods
%some other methods
end
end
So subclass B needs a variable of subclass C that is defined in A. At the moment I always pass an object of C as additional input parameter to the function. Additionally I don't know if C.myvar already has a value.
Current implementation:
function calc_subclassvar(obj,C)
if isempty(C.myvar)
C.calc_myvar;
end
obj.subclassvar = do_something_with_C.myvar;
end
Is there another, better way? I read of overloading the get function, so I don't have to check everytime if the variable exists? And I read about events and listeners but couldn't get it to work satisfactorily. For example if I want to add a listener to C it has to know from which specific object of A the event is sent. Or is there a way that C just listens for any object of A?
Maybe you know another way. It's kind of confusing. =)
I think you are over complicating the problem a bit. Either that, or I do not completely understand what you are asking for.
First of all, you are not using any constructors. I would normally use those to pass references to objects needed in a given class at instance-time. Secondly, you write that you don't know if C has been initialized when you need it in B. I see that as a lack of structure in your program, so if a part of your restructuring task is to make the program more robust, this would be a good place to start. Unless you have really good reasons against it, you should be able to tell in which order different objects are being initialized. Using constructors as explained above forces you to consider this, as you can't instance C without an instance of B in your example.
Below are my version of B and C. I excluded A as the need for inheritance is not really concerned with this problem.
Class C:
classdef C < handle
properties
some_const = pi;
end
methods
%some other methods
end
end
Class B:
classdef B < handle
properties
C_handle
end
methods (Access = public)
function obj = B(C_handle)
obj.C_handle = C_handle;
end
function disp_c_var(obj)
disp(obj.C_handle.some_const)
end
end
end
Use of the classes:
c_inst = C();
b_inst = B(c_inst);
b_inst.disp_c_var();
Now, all subsequent uses of b_inst already have a reference to c_inst, so it wont have to be passed again.

Create a "clone" of this object, not point to it

Let's say I got a list called
myFirstList
And then I want to create a copy of that list so I can do some tweaks of my own. So I do this:
mySecondList = myFirstList
mySecondList.doTweaks
But I noticed that the tweaks also affect the myFirstList object! I only want the tweaks to affect the second one...
And afterwards I will want to completely delete mySecondList, so I do mySecondList = Nothing and I'm good, right?
Adam Rackis, I don't like your "Of course it does", because it is not at all obvious.
If you have a string variable that you assign to another string variabe, you do not change them both when making changes to one of them. They do not point to the same physical piece of memory, so why is it obvious that classes do?
Also, the thing is not even consistent. In the following case, you will have all elements in the array pointing at the same object (they all end up with the variable Number set to 10:
SourceObject = New SomeClass
For i = 1 To 10
SourceObject.Number = i
ObjectArray.Add = SourceObject
Next i
BUT, the following will give you 10 different instances:
For i = 1 To 10
SourceObject = New SomeClass
SourceObject.Number = i
ObjectArray.Add = SourceObject
Next i
Apparently the scope of the object makes a difference, so it is not at all obvious what happens.
Here is how you do it:
'copy one object to another via reflection properties
For Each p As System.Reflection.PropertyInfo In originalobject.GetType().GetProperties()
If p.CanRead Then
clone.GetType().GetProperty(p.Name).SetValue(clone, p.GetValue(OriginalObject, Nothing))
End If
Next
in some cases when the clone object got read-only properties you need to check that first.
For Each p As System.Reflection.PropertyInfo In originalobject.GetType().GetProperties()
If p.CanRead AndAlso clone.GetType().GetProperty(p.Name).CanWrite Then
clone.GetType().GetProperty(p.Name).SetValue(clone, p.GetValue(OriginalObject, Nothing))
End If
Next
Since you have not divulged the type of item that you are storing n your list, I assume it's something that's implementing IClonable (Otherwise, if you can, implement IClonable, or figure out a way to clone individual item in the list).
Try something like this
mySecondList = myFirstList.[Select](Function(i) i.Clone()).ToList()
But I noticed that the tweaks also
affect the myFirstList object! I only
want the tweaks to affect the second
one...
Of course it does. Both variables are pointing to the same object in memory. Anything you do to the one, happens to the other.
You're going to need to do either a deep clone, or a shallow one, depending on your requirements. This article should give you a better idea what you need to do
Expanding on Adam Rackies' answer I was able to implement the following code using VB.NET.
My goal was to copy a list of objects that served mainly as data transfer objects (i.e. database data). The first the class dtoNamedClass is defined and ShallowCopy method is added. A new variable named dtoNamedClassCloneVar is created and a LINQ select query is used to copy the object variable dtoNamedClassVar.
I was able to make changes to dtoNamedClassCloneVar without affecting dtoNamedClassVar.
Public Class dtoNamedClass
... Custom dto Property Definitions
Public Function ShallowCopy() As dtoNamedClass
Return DirectCast(Me.MemberwiseClone(), dtoNamedClass)
End Function
End Class
Dim dtoNamedClassVar As List(Of dtoNamedClass) = {get your database data}
Dim dtoNamedClassCloneVar =
(From d In Me.dtoNamedClass
Where {add clause if necessary}
Select d.ShallowCopy()).ToList
Here's an additional approach that some may prefer since System.Reflection can be slow.
You'll need to add the Newtonsoft.Json NuGet package to your solution, then:
Imports Newtonsoft.Json
And given a class type of MyClass, cloning can be as easy as:
Dim original as New MyClass
'populate properties of original...
Dim copy as New MyClass
copy = JsonConvert.DeserializeObject(Of MyClass)(JsonConvert.SerializeObject(original))
So the approach is to first use the JSON converter to serialize the original object, and than take that serialized data and deserialize it - specifying the class type - into the class instance copy.
The JSON converters are extremely powerful and flexible; you can do all sorts of custom property mappings and manipulations if you need something the basic approach above doesn't seem to address.
this works for me:
mySecondList = myFirstList.ToList
clone is the object you are attempting to clone to.
dim clone as new YourObjectType
You declare it like that.