Updating a Property in an Array of Objects
15 次查看(过去 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!