Updating a Property in an Array of Objects
조회 수: 16 (최근 30일)
이전 댓글 표시
I have a class called WorkOrder that contains of several properties. My program brings in data from a SQL database as a Matlab table to be used as property values.. Once the data is imported, I check the height of the table and instatiate that exact amount of WorkOrder objects in a an array. I would now like to update the each of WorkOrder.properties by using the following type of statement:
[WorkOrder(1,:,1).wonbr] = listData.WONbr{:,1};
The above code works fine if the SQL datatype is a character string. However it fails if the SQL datatype is numeric with the error message: Brace indexing is not supported for variables of this type. But if I change the indexing to parentheses as below, I receive the error: Error using tabular/dotParenReference Too many output arguments.
[WorkOrder(1,:,1).nid] = listData.nid(:,1);
I could use a for loop as below, but it is too slow when the number of WorkOrder objects is high.
for i = 1:height(listData)
WorkOrder(i).nid = listData.nid(i,1);
end
Is there a way to make the middle statement above work for numberic data?
댓글 수: 0
채택된 답변
per isakson
2020년 5월 12일
편집: per isakson
2020년 5월 12일
The documentation doesn't tell that a statement like [WorkOrder(1,:,1).nid] = listData.nid(:,1); isn't possible. You are not the first one to try in vain. See Generate a comma-separated list from a numeric array?
I don't fully understand your code snippets. However, I made a working example.
Run
%% Example table from the documentation
load patients
T = table(Gender,Age,Height,Weight,Smoker,Systolic,Diastolic);
%% Create an array of WorkOrder objects
wo = WorkOrder( height(T) );
%% Update the properties of the WorkOrder objects
[wo.wonbr] = T.Gender{:,1};
[wo.nid] = num2csl( T.Height );
where
function varargout = num2csl( num )
% num2csl converts a numerical vector into a comma separated list
assert( isnumeric(num), 'num2csl:WrongClass', 'Input must be numeric' )
cac = num2cell( num );
varargout = cac( 1 : nargout );
end
and
classdef WorkOrder
properties
wonbr
nid
end
methods
function this = WorkOrder( N )
if nargin >= 1
this(1,N) = WorkOrder;
for jj = 1:N
this(jj).nid = nan;
end
end
end
end
end
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 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!