Using multiple functions on a variable in a table

1 回表示 (過去 30 日間)
Stef1998
Stef1998 2021 年 11 月 26 日
コメント済み: Dave B 2021 年 11 月 27 日
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'});

採用された回答

Stef1998
Stef1998 2021 年 11 月 27 日
A bit tedious and Im sure there might be a faster method out there but this solves the problem
T.D1 = 1000 * (2834.1 - 0.29 * T.B - 0.004 * T.B.^(2.0));
T.D1(T.B>=0) = 0;
T.D2 = 1000 * (2501 - 2.36 * T.B);
T.D2(T.B<0) = 0;
T.D = T.D1 + T.D2;

その他の回答 (1 件)

Dave B
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
T = 100×2 table
Var1 Var2 ________ ____ 0.59525 1 0.89591 1 0.3016 -1 0.94513 1 0.38489 -1 0.3707 -1 0.20688 -1 0.066268 -1 0.07012 -1 0.97702 1 0.23667 -1 0.97863 1 0.56713 1 0.9572 1 0.93443 1 0.5219 1
  2 件のコメント
Stef1998
Stef1998 2021 年 11 月 27 日
That would be similar to what i did for method one but because I use an equation that references another variable it still does not work since the left and right sides have different elements. It would read more like
T = table(rand(100,1));
T.Var2 = nan(height(T), 1);
T.Var2(T.Var1<.5) = 3.2*T.Var1;
Unable to perform assignment because the left and right sides have a different number of elements.
T.Var2(T.Var1>=.5) = 4.2*T.Var1;
Dave B
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)
T = 100×2 table
Var1 Var2 ________ ________ 0.61477 2.582 0.022891 0.073253 0.51972 2.1828 0.40734 1.3035 0.10431 0.3338 0.50238 2.11 0.69675 2.9263 0.82957 3.4842 0.41558 1.3298 0.12382 0.39623 0.50392 2.1164 0.9992 4.1967 0.61337 2.5762 0.69751 2.9295 0.96018 4.0328 0.82302 3.4567

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeTables についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by