PythonNoob
PythonNoob

Reputation: 1052

How to add new values into matlab's table based on a condition?

Considering having this table in matlab:

t = table([1; 0; 3; 1], [0; 1; 0; 4], 'VariableNames', {'A', 'B'});

A    B
_    _

1    0
0    1
3    0
1    4

I want to append a new column Cwith specific value that is based on a condition. Currently I use this loop:

for i=1:height(t)

    if t(i, 'A').Variables == 1
        t.C(i, 1) = 4;

    elseif t(i, 'A').Variables == 3
        t.C(i, 1) = 5;

    end

end

However, this is a time comsuming operation is case of a table size greater then 100k rows.

What would be the best solution for this?

Upvotes: 2

Views: 579

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112669

You can use the following:

[t{t.A==1, 'C'}] = 4;
[t{t.A==3, 'C'}] = 5;

This uses the facts that

  • Table contents can be indexed via {}, as in cell arrays;
  • Table columns can be indexed by their name.

Or, as noted by @SardarUsama, you can use the simpler

t.C(t.A==1)=4;
t.C(t.A==3)=5;

This uses dot notation to index the column. The result is a numerical column vector, to which a scalar can be directly assigned.

Upvotes: 2

Related Questions