Reputation: 1052
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 C
with 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
Reputation: 112669
You can use the following:
[t{t.A==1, 'C'}] = 4;
[t{t.A==3, 'C'}] = 5;
This uses the facts that
{}
, as in cell arrays;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