How to delete duplicates and replace values in an array?

3 次查看(过去 30 天)
Hey, I'm a little stumped on my personal project. I'm trying to have MatLab check a list of ingredients, delete duplicates, and rewrite the remaining ingredient to show how many times its been mentioned. Here's an example:
[("White Onion"),("Potato"),("White Onion"),("Fruit")] -> [("2x White Onion"),("Potato"),("Fruit")]
I know unique() is a command I could use, but how would I rewrite that individual value?

采纳的回答

Simon Chan
Simon Chan 2021-8-20
编辑:Simon Chan 2021-8-20
Create a table and use function groupsummary
Item=["White Onion";"Potato";"White Onion";"Fruit"];
T=table(Item,'VariableNames',{'Ingredients'});
G = groupsummary(T,"Ingredients","sum")
Result:
G =
3×2 table
Ingredients GroupCount
_____________ __________
"Fruit" 1
"Potato" 1
"White Onion" 2
  3 个评论
Cris LaPierre
Cris LaPierre 2021-8-20
Yes. Look at writetable
I would remove the method 'sum', as it doesn't make sense with string data.
ingrT = table(["White Onion","Potato","White Onion","Fruit"]','VariableNames',"ingredients");
groupsummary(ingrT,"ingredients")
ans = 3×2 table
ingredients GroupCount _____________ __________ "Fruit" 1 "Potato" 1 "White Onion" 2
Simon Chan
Simon Chan 2021-8-20
Thanks Cris, forgot it is string data.
Use function writetable to put it in a text file
writetable(G,'result.txt')

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by