Skip to main content

toDataTable helper function

function [dataTable] = toDataTable(T)

%TODATATABLE Converts a Matlab table to a Bayes Server DataTable.
%
% Version 0.1 (Beta)
% Copyright (C) Bayes Server. All rights reserved.

import com.bayesserver.data.*;

if ~istable(T)
error('T must be a Matlab table');
end

colCount = width(T);

if colCount == 0
error('Zero columns found');
end

dataTable = DataTable();
rows = dataTable.getRows();
cols = dataTable.getColumns();

rowCount = height(T);

names = T.Properties.VariableNames;

for c=1:colCount

V = table2array(T(:,c));

dataType = toJavaLangClass(V);
cols.add(names(c), dataType);

end

for r=1:rowCount

jxs = javaArray('java.lang.Object', colCount);

for c=1:colCount

val = T{r, c};

if iscell(val)
val = val{1};
end

if ismissing(val)
% leave as null
else

if iscategorical(val)
% c-1 as Java array access is zero based
dataTypeJ = dataTable.getColumns().get(c-1).getDataType().getName();

if strcmp(dataTypeJ, 'java.lang.String')
val = char(val);
else
error('Not yet implemented for this categorical variable data type');
end
end

if isinteger(val)
jxs(c) = java.lang.Integer(val);
elseif isfloat(val)
jxs(c) = java.lang.Double(val);
elseif ischar(val) || isstring(val)
jxs(c) = java.lang.String(val);
elseif islogical(val)
jxs(c) = java.lang.Boolean(val);
else
error('Not implemented for data type');
end
end
end

rows.add(jxs);

end
end

function [name] = toJavaLangClass(xs)

%TOJAVALANGCLASS Determines the appropriate Java class to represent values of a Matlab vector.
%
% Version 0.1 (Beta)
% Copyright (C) Bayes Server. All rights reserved.

if iscell(xs)
for i=1:length(xs)
if ischar(xs{i})
name = toJavaLangClass(xs{i});
return;
elseif ~ismissing(xs{i})
name = toJavaLangClass(xs{i});
return;
end
end

error('Cannot determine data type in cell');

else
if isinteger(xs)
name = java.lang.Class.forName(java.lang.Integer.class);
elseif iscategorical(xs)
name = toJavaLangClass(categories(xs));
elseif isfloat(xs)
name = java.lang.Class.forName(java.lang.Double.class);
elseif ischar(xs) || isstring(xs)
name = java.lang.Class.forName(java.lang.String.class);
elseif islogical(xs)
name = java.lang.Class.forName(java.lang.Boolean.class);
else
error(['Not implemented for data type ', class(xs)])
end
end

end