Reputation: 333
I'd like to understand how Matlab works with array objecs. I've read several posts and the Matlab help for this topic, but I still don't understand it completely.
Let's take a use case: I'd like to manage several measurement channels (the amount of channels can vary). Each measurement channel is an object with several properties. Now I'd like to have a class handling the channels (channelHandler.m). In this class I can simply add a new channel to the array (later on there might be bore functionality).
So what I've tried so far:
1) create the measurementChannel.m class In the constructor I've only set the channel name so far without data.
classdef measurementChannel
%CHANNEL holds an instance of a single channel
properties
channelData
channelName = strings
channelUnit = strings
channelDataLength
channelOriginMeasurementFile
end
methods
function obj = channelTest(channelName)
if nargin > 0
obj.channelName = channelName;
end
end
end
end
To test this class I tried this:
channel(1) = measurementChannel('channelA');
channel(2) = measurementChannel('channelB');
channel(1).channelName
channel(2).channelName
which was working well.
2) Now I've created the channelHandler class:
classdef channelHandler
properties (Access = public)
channelArray
end
methods (Access = public)
function addChannel(obj, Name)
testobj = measurementChannel();
testobj.channelName = Name;
obj.channelArray = [obj.channelArray testobj];
end
end
and access this by using the following commands:
createChannels = channelHandler();
createChannels.addChannel('channel1');
createChannels.addChannel('channel2');
createChannels.channelArray(1).channelName
createChannels.channelArray(2).channelName
this fails because channelArray is not defined as an array and will give an error accessing channelArray(2). So I also tried to initialize the array (but then I need to know the amount of channels).
so my questions are: a) do I really need to initialize an array of objects? b) how can I fix the channelHandler class to add objects to the array?
Upvotes: 1
Views: 137
Reputation: 65430
The issue is that you are not inheriting from the handle
class and therefore the modifications made within addChannel
alter a copy of your object rather than the object itself. If you inherit from handle
, the code that you have pasted will work just fine.
classdef channelHandler < handle
Upvotes: 1