stacking or appending tables with NaN and 'ABC' -- cell vs non-cell

8 views (last 30 days)
Hello, with a loop and using readtable I am stacking a table on top of an existing table where var2 is sometimes NaN or sometimes 'ABC'
The var type of var2 in both cases reads char
When I try to stack one table over the other it prompts:
Cannot concatenate the table variable 'var2' because it is a cell in one table and a non-cell in another.
Is there a way to fix this?

Accepted Answer

Walter Roberson
Walter Roberson on 13 Oct 2021
If I understand correctly, you are looping reading multiple files, and want to put the results all into one large table. And that you have a column which will at least sometimes contain text.
The times that it complains about nan: is it possible those are times that the entire column for that variable is empty? The automatic detection will call empty columns as double, not char.
If this is the problem, then there are two potential ways to proceed:
  1. detectImportOptions each time and setvartype() to force it to text; or
  2. detectImportOptions only once at the beginning (forcing to text would not hurt), and then use those import options for all remaining files
  3 Comments
Dave
Dave on 13 Oct 2021
Update, I set it to char outside the loop, it works.
Danke
Walter Roberson
Walter Roberson on 13 Oct 2021
opts = detectImportOptions(csvfilename{1});
opts = setvartype(opts, 'var2', 'char');
Then inside the loop,
out1 = readtable(csvfilename{ii}, opts);
This should be faster than what you already had: when you were using readtable() without passing in options, MATLAB would automatically invoke detectImportOptions on your behalf (for the last several years, not before that.)

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!