how to create a new variable based off an if else statement on one variable?

I have created a table in MATLAB, one of the variables is called animals. Within that coloum are "dogs", "cats", "sheep". I want to create code that states if table.animals == "dogs" then create a new variable called numbers and assign the number 1 to the rows that have dogs stated in it. If table.animals == "cats" then in that same new variable called numbers assign the number 2. and similar with sheep expect the number 3. How would I go about create this type of code?
This is something similar to what I have tried but it does not work.
if tables.animals == "Dogs"
tables.numbers = 1
elseif tables.animals == "cats"
tables.numbers = 2
else tables.numbers = 3
end
my code ends up usually create that new coloum but places the number 3 for all the rows.

 採用された回答

Voss
Voss 2022 年 12 月 1 日
t = table(["cats";"dogs";"cats";"sheep"],'VariableNames',"animals")
t = 4×1 table
animals _______ "cats" "dogs" "cats" "sheep"
all_animals = ["dogs" "cats" "sheep"];
[~,idx] = ismember(t.animals,all_animals);
t.numbers = idx
t = 4×2 table
animals numbers _______ _______ "cats" 2 "dogs" 1 "cats" 2 "sheep" 3

4 件のコメント

Elysia
Elysia 2022 年 12 月 1 日
How were you able to assign the numbers to the animals? For example if I wanted to changes dogs to equal the number 38383 instead of 1, how would I change that?
The number was the index in "all_animals", since it was 1, 2, 3.
To be able to use arbitrary numbers instead, you can use those same indexes, but index into an array of the numbers you want (here I call it "all_numbers"):
t = table(["cats";"dogs";"cats";"sheep"],'VariableNames',"animals")
t = 4×1 table
animals _______ "cats" "dogs" "cats" "sheep"
all_animals = ["dogs"; "cats"; "sheep"];
all_numbers = [38383; 29292; 10101];
[~,idx] = ismember(t.animals,all_animals);
t.numbers = all_numbers(idx)
t = 4×2 table
animals numbers _______ _______ "cats" 29292 "dogs" 38383 "cats" 29292 "sheep" 10101
Elysia
Elysia 2022 年 12 月 1 日
That makes so much sense! Thank you so much!
Voss
Voss 2022 年 12 月 1 日
You're welcome!

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

その他の回答 (0 件)

カテゴリ

製品

リリース

R2022b

タグ

質問済み:

2022 年 12 月 1 日

コメント済み:

2022 年 12 月 1 日

Community Treasure Hunt

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

Start Hunting!

Translated by