Using multiple functions on a variable in a table
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(1 个)
Dave B
2021-11-26
编辑:Dave B
2021-11-26
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 个评论
Dave B
2021-11-27
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)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!