How to use a method to assign a structure to a class property?
显示 更早的评论
I'm new to Matlab, and am trying to create a class definition that will allow me to dynamically assign structured property variables to an object. I've defined the following class:
classdef WAVE
%UNTITLED5 Summary of this class goes here
% Detailed explanation goes here
properties
s %string structure
v %variable structure
end
methods
function WAVE = newVar(WAVE,NAME,VALUE)
% test if variable value is text or number
if ischar(VALUE)
% if text, then store as given variable name in the "s"
% structure
WAVE.s.(NAME) = VALUE;
else
% otherwise store as a given variable name in the "v"
% structure
WAVE.v.(NAME) = VALUE;
end
end
end
end
The idea here is to create the object (ie, object1 = WAVE) but then be able to assign a new property to it as such:
object1.newVar('name','My Object')
When this method is run, I'd like to have object1 updated so its "s" property (that for string variables) becomes a structure that has a new entry "name" which contains the data "My Object".
In this manner, the idea is to be able to get this object's name at a later point by running the following:
object1.s.name
Currently the above method works, but I have to reassign the output to the original object, such as the following:
object1 = object1.newVar('name','My Object')
Is there any way to implement this as a method so the method directly alters the object's property and does not need to be reassigned? I think there may be some issue with the use of "(NAME)" in the class method, since I can use "WAVE.v = VALUE" and it works just fine; however, this simply changes the "v" property to a single value and does not let it become a structure (my intended property type).
I should add that I can create an object from this class by the following command:
object1 = WAVE;
...and then properly assign structures to the "s" and "v" properties in the following manner:
field = 'name';
object1.s.(field) = 'My Object';
This ends up working as expected, but I cannot seem to get it to work when called within the methods block of the class definition.
采纳的回答
更多回答(1 个)
per isakson
2013-5-19
编辑:per isakson
2013-5-19
0 个投票
"but I have to reassign the output to the original object" See Handle Classes Objects that share references with other objects.
2 个评论
Christopher
2013-5-19
per isakson
2013-5-19
Your questions gave me the impression that you want to add properties to an instance of a class at run time. The MathWorks has added the abstract class dynamicprops with the method addprops to support adding properties to instancies. I though that you was about the reinvent the this functionality and thus, I linked to the help on Dynamic Properties.
"have no clue how to implement it". You have to study the on-line help that I linked to.
类别
在 帮助中心 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!