adding property dynamically in the class

22 ビュー (過去 30 日間)
Gopalakrishnan venkatesan
Gopalakrishnan venkatesan 2017 年 2 月 23 日
編集済み: per isakson 2017 年 2 月 27 日
I have a class,
classdef data < dynamicprops
result1 = []
result2 = []
Now I need to add dynamically many properites to the class. For example
reult 3, result 4, result 5 etc
I tried using data.('result3') = [] like how we add a field in the strcture. But i am getting the error.
how can i do this?
Thanks a lot
  2 件のコメント
Stephen 2017 年 2 月 23 日
@Gopalakrishnan venkatesan: as Adam already said, using an array (possible cell array) would be a much better solution. You should really consider using the simpler solution rather than making this complicated with dynamic properties.



Guillaume 2017 年 2 月 23 日
A rule in any programming language: if you*re numbering variables, you're doing it wrong. These obviously related variables should all be just one variable, a container for whatever is in each of these variables. In matlab, it's matrix or cell array or table.
Assuming your results are going to be matrices of varying size, then:
classdef data < handle
results = {[], []}; %two empty results in the results container
function addresult(this, result)
this.results = [this.results, {result}];
function setnthresult(this, n, result)
validateattributes(n, {'numeric'}, {'integer', 'positive', '<=', numel(this.results)});
this.results{n} = result;
would make your life much easier.
If you really insist on using dynamic properties, then this page explains exactly how to do it, with example.

その他の回答 (1 件)

Adam 2017 年 2 月 23 日
編集済み: Adam 2017 年 2 月 23 日
doc dynamicprops
gives details on the addprops function which I would assume you need to use. I have never wanted to do any dynamic properties on my own classes as it seems a bit of a suspicious design premise, but how did you manage to come across knowing you need to use dynamicprops yet not find addprops?!
  1 件のコメント
Gopalakrishnan venkatesan
Gopalakrishnan venkatesan 2017 年 2 月 23 日
i known the addprops also but i dont known how to apply it. I was not able to add a new property to my class


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by