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

조회 수: 44 (최근 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,
Ronald
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 )
warning('off')
% 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);
%%%%%%%%%
end
% do the merge into a new output table T
T = T1;
T( kdo, commonnames ) = T2( :, commonnames);
else
fprintf( 2, 'Warning in %s table 1 returned unchanged. Table 2 has no common variables\n', mfilename);
T = T1;
end
  댓글 수: 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 :)

댓글을 달려면 로그인하십시오.

답변 (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

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by