Using multiple functions on a variable in a table
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Stef1998
el 26 de Nov. de 2021
Comentada: Dave B
el 27 de Nov. de 2021
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 comentarios
Respuesta aceptada
Más respuestas (1)
Dave B
el 26 de Nov. de 2021
Editada: Dave B
el 26 de Nov. de 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 comentarios
Dave B
el 27 de Nov. de 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)
Ver también
Categorías
Más información sobre Tables en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!