WJA
WJA

Reputation: 7004

Expand table variables in Matlab

I have a table:

Values = [2.1 2.4 2.5 2.6; ...
            4.1 4.4 4.5 4.6; ...
            6.1 6.4 6.5 6.6];

ID     = {'x1', 'x4', 'x5', 'x6'};

Ta = array2table(Values,'VariablesNames', ID);

Now I have another list of IDs:

ID     = {'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7'};

And I want to expand my table such that, on the columns where I have data in Ta I put the values of Ta, and the cells on which I dont have data I get NaN.

How can I expand the VariableNames of my table keeping the values where necessary?

Upvotes: 0

Views: 264

Answers (1)

Mikhail_Sam
Mikhail_Sam

Reputation: 11228

We can do it in this way: first, you need to create the table of the new IDs. And then you can form on tables as usual arrays. Example:

x1 = [1; 2; 3; 4;]
x2 = [1;1;1;1]
x4 = [10;10;10;10]
T = table(x1,x2,x4)

T = 

    x1    x2    x4
    __    __    __

    1     1     10
    2     1     10
    3     1     10
    4     1     10

Create new table:

x3 = [123;13;13;123]
x5 = [0;0;0;0]
T1 = table(x3,x5)

T1 = 

    x3     x5
    ___    __

    123    0 
     13    0 
     13    0 
    123    0 

To expand first Table you have to use indexing now:

T = [T(:,1:2) T1(:,1) T(:,3) T1(:,2)]

So, now all you need to do is create algorithm to choose current tables of data using your ID vector.

Upvotes: 1

Related Questions