Updating a Property in an Array of Objects

16 ビュー (過去 30 日間)
Clarke
Clarke 2020 年 5 月 12 日
編集済み: Clarke 2020 年 5 月 13 日
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?

採用された回答

per isakson
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
  2 件のコメント
Clarke
Clarke 2020 年 5 月 13 日
Thanks PI, that did the trick. Any idea why we need the function workaround for an int64 datatype, but not a string? Just curious. I am already using the function.
Clarke
Clarke 2020 年 5 月 13 日
編集済み: Clarke 2020 年 5 月 13 日
PS. The page is not letting me accept the answer. I reload, but no joy. Will try again later today or tommorow.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by