gabboshow
gabboshow

Reputation: 5579

Add NaN rows in matlab table

I have a Table which is 100 x 19.

The first 16 columns of Table contains chars, the last 3 columns contain double variables.

How can I insert after the 50th row 3 new rows composed by NaNs so that my table becomes 103 x 19?

Table is in the form

Subject Sex Age .... .... ... .. Var1 Var2 Var3
1       M   38                     88 89   99 
2       F   34  ..... .... .. ...  34 34   34

and I would like something like (in this example I add only 1 row between the 1st and the 2nd)

Subject Sex Age .... .... ... .. Var1 Var2 Var3
1       M   38                     88 89   99 
1       M   38 ..... .... .. . .   NaN NaN NaN
2       F   34  ..... .... .. ...  34 34   34

Upvotes: 1

Views: 5664

Answers (2)

Ander Biguri
Ander Biguri

Reputation: 35525

You can create NaN values using the nan() function, then append them to your table as new data. You'd need the new data to be a table with the same variable names. I am assuming here that all of them are numeric.

In your case

T=[T; array2table(nan(3,8),'variablenames',T.Properties.VariableNames)];

Additionally, as per @Dan's comments, it seems you can also do

T{51:53,:} = NaN

Again, if all values are numeric type.

Upvotes: 4

Phil Goddard
Phil Goddard

Reputation: 10772

Assuming all the data is numeric, then

% Create an example table
>> tbl = table((1:100)',(101:200)');
% Append rows
>> tbl{end+1:end+3,:} = nan;
% Move rows
>> tbl{53:end,:} = tbl{50:100,:};
% Insert nans
>> tbl{50:52,:} = nan;

If all the data is not numeric then it's a little harder, but the general idea still holds.

Upvotes: 2

Related Questions