Using multiple functions on a variable in a table
1 view (last 30 days)
Show older comments
I have a table (T) of data 365x3. With column variables A,B,C lets say. I am trying to create a new column (D) where 2 functions would be necessary for the new variable. I run into an error that the size of the left and right do not match. I have tried 3 different approaches with no success, shown below. I am not too sure how to fix this?
%Method 1
T.D = 1000 * (2834.1 - 0.29 * T.B - 0.004 * T.B.^(2.0));
idx = T.B >= 0;
T.D(idx) = 1000 * (2501 - 2.36 * T.B);
%Method 2
idx = T.B < 0;
T.D(idx) = 1000 * (2834.1 - 0.29 * T.B - 0.004 * T.B.^(2.0));
idx2 = T.B >= 0;
T.D(idx2) = 1000 * (2501 - 2.36 * T.B);
%Method 3
idx = T{:,'B'} < 0;
T{idx,'D'} = 1000 * (2834.1 - 0.29 * T{:,'B'} - 0.004 * T{:,'B'}.^(2.0));
idx2 = T{:,'B'} >= 0;
T{idx2,'D'} = 1000 * (2501 - 2.36 * T{:,'B'});
0 Comments
Accepted Answer
More Answers (1)
Dave B
on 26 Nov 2021
Edited: Dave B
on 26 Nov 2021
How about just initializing the new table variable first (e.g. with NaN values) and then populating it using your indices?
T = table(rand(100,1));
T.Var2 = nan(height(T), 1);
T.Var2(T.Var1<.5) = -1;
T.Var2(T.Var1>=.5) = 1
2 Comments
Dave B
on 27 Nov 2021
Your snippet was just missing the index in the right hand side
T = table(rand(100,1));
T.Var2 = nan(height(T), 1);
ind = T.Var1<.5;
T.Var2(ind) = 3.2*T.Var1(ind);
T.Var2(~ind) = 4.2*T.Var1(~ind)
See Also
Categories
Find more on Tables in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!