1

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!

Dylan Fox
  • 15
  • 4

2 Answers2

2

You could import each file into a table using readtable and then use outerjoin to combine the tables in the way that you would expect. This will work if all data starts at t = 0 or not.

To create a table from a file:

T1 = readtable('filename1.dat');
T2 = readtable('filename2.dat');

Then to perform the outerjoin (pseudo data created for demonstration purposes).

t1 = table((1:4)', (5:8)', 'VariableNames', {'t', 'v'});

%//     t    v
%//     _    _
%//     1    5
%//     2    6
%//     3    7
%//     4    8

% t2 is missing row 2
t2 = table([1;3;4], [1;3;4], 'VariableNames', {'t', 'v'});

%//     t    v
%//     _    _
%//     1    1
%//     3    3
%//     4    4

%// Now perform an outer join and merge the key column
t3 = outerjoin(t1, t2, 'Keys', 't', 'MergeKeys', true)

%//     t    v_t1    v_t2
%//     _    ____    ____
%//     1    5         1
%//     2    6       NaN
%//     3    7         3
%//     4    8         4
Suever
  • 64,497
  • 14
  • 82
  • 101
1

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);
Ryan Fl0w
  • 108
  • 8