Add new variable to table based on condition
古いコメントを表示
Hi,
I apologize for the newbie question but how does one add a variable to a table in Matlab based on conditions applied to other variables ?
For example, in the code below if t.y < 4 & t.y > 2 then 'A' should be stored in a new collumn t.z. Which doesnt work. Any ideas ?
y = [1 2 3 4];
x = [5 6 7 8];
t = table(x', y', 'VariableNames', {'x', 'y'})
if t.y < 4 & t.y > 2
t.z = 'A'
end
5 件のコメント
Bob Thompson
2019 年 6 月 26 日
You won't have success doing this for one thing because you're looking to add a single element to a table which has four rows. Matlab doesn't like introducing a new column with one element when there are more than one rows in an array of any kind. Try adding the t.z column first and then setting the value to 'A.'
Adam Danz
2019 年 6 月 26 日
Also, the logical tests below will be true only if all rows of t.y and t.x satisfy the conditions. If that's really what you're testing, you should use all().
if t.y < 4 & t.y > 2
if all(t.y < 4) & all(t.y > 2)
Walter Roberson
2019 年 6 月 26 日
More likely,
mask = t.y > 2 & t.y < 4;
t.z(mask) = 'A';
Bob Thompson
2019 年 6 月 27 日
Would using a logic index range for an undefined variable work though? I would think that if t.z didn't exist already then you would still run into the same issue Blue has. I get that the range covers a set of elements the same size as the other variables, but what values are entered for mask == 0? Do they just get created as empty? Is that allowed in a table?
Adam Danz
2019 年 6 月 27 日
Yes, mask=0 elements are merely empty strings ('')
y = [1 2 3 4];
x = [5 6 7 8];
t = table(x', y', 'VariableNames', {'x', 'y'})
mask = t.y > 2 & t.y < 4;
t.z(mask) = 'A';
t =
4×3 table
x y z
_ _ _
5 1
6 2
7 3 A
8 4
回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Tables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!