필터 지우기
필터 지우기

adding property dynamically in the class

조회 수: 16 (최근 30일)
Gopalakrishnan venkatesan
Gopalakrishnan venkatesan 2017년 2월 23일
댓글: Arun Aiyer 2022년 7월 16일
I have a class,
classdef data < dynamicprops
properties
result1 = []
result2 = []
end
end
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
Adam
Adam 2017년 2월 23일
Why wouldn't you just use a single property
results
as an array of results that you can index into?
Stephen23
Stephen23 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
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
properties
results = {[], []}; %two empty results in the results container
end
methods
function addresult(this, result)
this.results = [this.results, {result}];
end
function setnthresult(this, n, result)
validateattributes(n, {'numeric'}, {'integer', 'positive', '<=', numel(this.results)});
this.results{n} = result;
end
end
end
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
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?!
  댓글 수: 2
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
Arun Aiyer
Arun Aiyer 2022년 7월 16일
If you want to use inspect function to create a dynamic settings table related to hardware for example.
The inspect function creates a dynamic interface for the object handle properties, which needs to be changed. The function that creates the dynamic props is to generate these settings objects.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Properties에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by