MATLAB Answers

I want to change the data type of a table column from double to cells

35 ビュー (過去 30 日間)
Ronald Ouwerkerk
Ronald Ouwerkerk 2019 年 11 月 22 日
回答済み: Jyotsna Talluri 2019 年 12 月 4 日
I want to concatenate two tables with a function (see below) that recognizes common variables appends the values of the second table to the values of the first for all common variables and fills the rest with defaults (typically zeros and empty strings)
The fuction checks for incompatible data types ( sopecifically cells or strings copied to doubles). I can identify the problem variables, but I cannot do anything about it. Is there a way to alter thet data type as in Table.Properties.Datatypes(index) = 'cells'?
Any help is much appreciated,
Here is the function
function [T, commonnames] = growtable( T1, T2 )
%function T = growtable( T1, T2 )
% adds all values of table T2 to table T1 for all variablenames these tables have in
% get varibale names from both tables
names1 = T1.Properties.VariableNames;
names2 = T2.Properties.VariableNames;
% find the common names
[commonnames,cidx1,cidx2] = intersect(names1,names2, 'stable');
if ~isempty( commonnames )
% Determine how many rows to add
[addrows, ~] = size(T2);
% Determine the row range in T1 needed to append these rows
[nrows, ~ ] = size(T1);
kdo = (1:addrows)+nrows;
% Check for cell copied to double type conflicts
classT1 = varfun(@class,T1(:,cidx1) ,'OutputFormat','cell');
doubles1 = ismember( classT1, {'double'} );
classT2 = varfun(@class,T2(:,cidx2),'OutputFormat','cell');
cells2 = ismember( classT2, {'cell'} );
% Errors ensue when copying cells into a doubles space
problemidx = find( doubles1 & cells2 );
% If is is one we copy we have a problem
if ~isempty( problemidx )
varname = names1( problemidx );
temp = T1{ :, varname };
%%%%% HERE is the problem!!!!!!!!
% How can I force the column of doubles to become a column of
% cells?
T1{ :, varname } = num2cell(temp);
% do the merge into a new output table T
T = T1;
T( kdo, commonnames ) = T2( :, commonnames);
fprintf( 2, 'Warning in %s table 1 returned unchanged. Table 2 has no common variables\n', mfilename);
T = T1;

  1 件のコメント

madhan ravi
madhan ravi 2019 年 11 月 22 日
Next time use proper formatting tools to edit your question, this time I did it for you :)

サインイン to comment.

回答 (1 件)

Jyotsna Talluri
Jyotsna Talluri 2019 年 12 月 4 日
While importing the table itself you can set the import to a specific type using 'setvaropts'. or you can convert the cell to string using cellstr and then concatenate the two tables.
Refer to the below link

  0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。


Translated by