How to change a cell in a table to double ?

8 views (last 30 days)
Matboy
Matboy on 21 Mar 2022
Commented: Peter Perkins on 24 Mar 2022
Hey,
I am reading in some data and I want to concatenate the read tables with 218 and 220 columns vertically in one big table. Therefore I add 2 columns with nan values to the table with 218 columns.
But I get this error: Cannot concatenate the table variable 'fill2' because it is a cell in one table and a non-cell in another. So I tried str2double in order to get oridinary double.
But then I get this error: To assign to or create a variable in a table, the number of rows must match the height of the table. I dont understand where my mistake is. Maybe someone could help me out with a correct code snippet.
Thanks a lot!
P.S. I also tried some other codes to solve the problem with cell2mat, a for loop etc. ... it didnt really work. They are commented out.
files = dir('plotdata-*');
tab_gesamt = [];
for K = 1:length(files)
thisfilename = files(K).name;
opts = detectImportOptions(thisfilename);
opts = setvartype(opts,{'Var1','Var2'},'string');
T = readtable(thisfilename, opts);
x = width(T);
y = height(T);
%for motor plotdata
if isequal(x,220)
T.Properties.VariableNames(219:220)={'fill1','fill2'};
% for i=1:y
% T.fill1(i) = cell2mat(T.fill1(i));
% T.fill2(i) = cell2mat(T.fill2(i));
% if iscell(T.fill1)
T.fill1 = str2double(T.fill1);
% elseif iscell(T.fill2)
T.fill2 = str2double(T.fill2);
% end
% end
% for i = 1:width(T), if iscell(T.(i)), T.(i) = cell2mat(T.(i)); end, end
tab_gesamt=[tab_gesamt; T];
elseif isequal(x,218)
fill1 = randi(10, [y,1]);
fill2 = randi(10, [y,1]);
fill1(1:y) = nan;
fill2(1:y) = nan;
T1 = array2table(fill1);
T2 = array2table(fill2);
T_new = [T, T1, T2];
tab_gesamt = [tab_gesamt; T_new];
end
end
clear K
  1 Comment
Peter Perkins
Peter Perkins on 24 Mar 2022
It's pretty unlikely that anyone can help with just that information. Attach a SMALL example of something like your files, show a small example of what you are starting with and what you want to end up with, and where in your code the error is coming from.
In any case, this
fill1 = randi(10, [y,1]);
fill2 = randi(10, [y,1]);
fill1(1:y) = nan;
fill2(1:y) = nan;
T1 = array2table(fill1);
T2 = array2table(fill2);
T_new = [T, T1, T2];
is much too complicated. If ytou want to add two all-NaN column vectors to T, just assign nan(y,1) to T.fill1 etc. Just like what you did in the isequal(x,22) case.

Sign in to comment.

Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!