Search code examples
matlabmatlab-table

Merge different sized arrays into a table


Overview

I am currently working with a series of .txt files I am importing into MATLAB. For simplicity, I'll show my problem conceptually. Obligatory, I'm new to MATLAB (or programming in general).

These .txt files contain data from tracking a ROI in a video (frame-by-frame) with time ('t') in the first column and velocity ('v') in the second as shown below;

T1 =           T2 =            etc.

t     v       t     v

0    NaN      0     NaN
0.1  100      0.1   200 
0.2  200      0.2   500
0.3  400      0.3   NaN
0.4  150       
0.5  NaN      

Problem

  • Files differ in their size, the columns remain fixed but the rows vary from trial to trial as shown in T1 and T2.
  • The time column is the same for each of these files so I wanted to organise data in a table as follows;

    time   v1    v2    etc.
    
    0      NaN   NaN
    0.1    100   200
    0.2    200   500
    0.3    400   NaN
    0.4    150   0
    0.5    NaN   0
    

Note that I want to add 0s (or NaN) to end of shorter trials to fix the issue of size differences.

Edit

Both solutions worked well for my dataset. I appreciate all the help!


Solution

  • I would suggest the use of the padarray and horzcat functions. They respectively :

    1. Pad a matrix or vector with extra data, effectively adding extra 0's or any specified value (NaNs work too).
    2. Concatenate matrices or vectors horizontally.

    First, try to obtain the length of the longest vector you have to concatenate. Let's call this value max_len. Once you have that, you can then pad each vector by doing :

    v1 = padarray(v1, max_len - length(v1), 0, 'post');
    % You can replace the '0' by any value you want !
    

    Finally, once you have vectors of the same size, you can concatenate them using horzcat :

    big_table = horzcat(v1, v2, ... , vn);