Sunday, September 30, 2018

MATLAB: Initialize and empty table with headers and concatenate it to another table

Leave a Comment

I'm getting this error:

Cannot concatenate the table variable 'epoch' because it is a cell in one table and a non-cell in another.

To reproduce the error:

A.epoch = [1,2,3]'; A.value = [10,20,30]'; 

Initialized empty table with headers:

Aclean = cell2table(cell(1,2), 'VariableNames', {'epoch', 'value'}); 

Vertically concatenate the 2 tables:

Aclean = vertcat(Aclean, struct2table(A)); 

What is the best way of concatenating tables with a for loop in Matlab?

1 Answers

Answers 1

If I understand right, you want to initialize Aclean before a loop, then concatenate data to it in every loop iteration. If so, you can simply initialize Aclean to the empty array:

Aclean = [];  A.epoch = [1,2,3].'; A.value = [10,20,30].'; Aclean = vertcat(Aclean, struct2table(A)); 

However, if you know in advance how many rows you will add to the table, it is better to preallocate the full table:

% N = number of rows A = array2table(zeros(N,2), 'VariableNames', {'epoch', 'value'}); A.epoch(1:3) = [1,2,3]; A.value(1:3) = [10,20,30]; 

It is cheaper to cut off unused rows from the bottom than to append in every iteration.

Yet another alternative is to work with a struct and convert it to a table after your loop. A struct is a built-in type, whereas a table is implemented as a custom class. The struct will therefore be more efficient to update.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment