필터 지우기
필터 지우기

How to initialize an object array as a class property?

조회 수: 16 (최근 30일)
Sigurd Askeland
Sigurd Askeland 2018년 4월 20일
댓글: Steven Lord 2022년 7월 21일
Here are two code snippets illustrating my problem:
classdef SomeClass
properties
foo;
bar;
end
end
and in another file:
classdef SomeOtherClass
properties
%Array of SomeClass objects.
someClassArray;
end
methods
function obj = SomeOtherClass(n)
%Initialize the array, as n can be large.
obj.someClassArray(n,1) = SomeClass();
end
end
end
When initializing an object of the second class, Matlab assusmes the someClassArray property is a double, and gives an error:
The following error occurred converting from SomeClass to double:
Conversion to double from SomeClass is not possible.
Error in SomeOtherClass (line 10)
obj.someClassArray(n,1) = SomeClass();
How do I get around this?

채택된 답변

Matt J
Matt J 2018년 4월 20일
편집: Matt J 2018년 4월 20일
      methods
         function obj = SomeOtherClass(n)
               tmp(n,1)=someClass;
              obj.someClassArray=tmp;
          end
      end
  댓글 수: 2
Jon
Jon 2022년 7월 21일
I have been experiencing the same problem, and this approach also solves my problem. I am wondering though why it is necessary, or why it works when simply initializing the property value directly i.e
obj.someClassArray(n,1) = SomeClass();
doesn't work.
Steven Lord
Steven Lord 2022년 7월 21일
It's because of how property default values are determined. See the "Property Default Values" section on this documentation page for more information.
I'd probably solve this by making someClassArray either a scalar SomeClass object or an empty SomeClass object array (like Prop4 in the documentation section I referenced above.)
But be careful with this if you initialize a property value to an instance of a handle class. See the "Initializing Properties to Handle Objects" section on that same documentation page.

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by