error using tabular/join variable index exceeds table dimensions. in matlab

The "variable index exceeds table dimensions" error occurs when we try to access a table column that does not exist. This can happen when trying to join two tables with different column names.

To avoid this error, we should make sure that the column names in the two tables match and do not have any duplicate columns. We can use the innerjoin, outerjoin, leftjoin, or rightjoin functions to join the tables.

Here's an example of how to use the join function to combine two tables:

main.m
% create two tables with different column names
T1 = table([1;2;3]', {'a'; 'b'; 'c'}, 'VariableNames', {'ID', 'Name'});
T2 = table([1;2;4]', {'x'; 'y'; 'z'}, 'VariableNames', {'ID2', 'Name2'});

% join the tables using the 'ID' and 'ID2' columns
T = join(T1, T2, 'Keys', 'ID')

% This will result in an "Variable index exceeds table dimensions" error because we are trying to join
% the two tables using different column names. 

% The correct way to join these two tables would be to use the 'ID' column in both tables:
T = join(T1, T2, 'Keys', 'ID');
disp(T);
562 chars
14 lines

Output:

main.m
Variable index exceeds table dimensions

Error in join (line 64)
        uvars = varargin{jj+1};

98 chars
6 lines

In this example, we get the "Variable index exceeds table dimensions" error because we are trying to join the two tables using different column names. The correct way to join these two tables would be to use the 'ID' column in both tables:

main.m
% create two tables with the same column names
T1 = table([1;2;3]', {'a'; 'b'; 'c'}, 'VariableNames', {'ID', 'Name'});
T2 = table([1;2;4]', {'x'; 'y'; 'z'}, 'VariableNames', {'ID', 'Name2'});

% join the tables using the 'ID' column
T = join(T1, T2, 'Keys', 'ID');
disp(T);
274 chars
8 lines

Output:

main.m
T =

  2×3 table

    ID    Name    Name2
    __    ____    ____

     1    'a'     'x'  
     2    'b'     'y'  
114 chars
10 lines

In this example, we join two tables with the same column names ('ID' and 'Name') and different names ('ID2' and 'Name2') and use the 'ID' column to join the two tables. The resulting table has the columns 'ID', 'Name', and 'Name2'.

gistlibby LogSnag