Replace string values in a table

60 ビュー (過去 30 日間)
James Bishop
James Bishop 2022 年 3 月 16 日
回答済み: Eric Sofen 2022 年 3 月 17 日
I have a column in a table with 3 wine types defined as character values "1", "2" and "3". I want to replace these values with "French", "Spanish" and "Italian" respectively. I am treating the column as an array of strings and using the tried and trusted combination of a for loop and if/elseif ladder to select and replace each of the string values in the table. Howver, when I run this in the command window, I get an error saying 'Unable to perform assignment because the left and right sides have a different number of elements' . My code is listed below and the array I am trying run it on is attached.
for i = 1:size(Typ)
if((Typ(i))=="1")
Typ(i)="French"
elseif((Typ(i))=="2")
Typ(i)="Spanish"
elseif((Typ(i))=="3")
Typ(i)="Italian"
else
end
end

採用された回答

Mathieu NOE
Mathieu NOE 2022 年 3 月 16 日
hello
my 2 cents suggestion
Typ = readtable('Typ.csv');
Typ = table2array(Typ);
for i = 1:numel(Typ)
if((Typ(i))== 1)
newTyp{i,1}='French';
elseif((Typ(i))==2)
newTyp{i,1}='Spanish';
elseif((Typ(i))==3)
newTyp{i,1}='Italian';
else
end
end
Typ = newTyp;

その他の回答 (2 件)

Stephen23
Stephen23 2022 年 3 月 16 日
編集済み: Stephen23 2022 年 3 月 16 日
The simple MATLAB approach would be to use indexing:
T = readtable('Typ.csv');
V = ["French";"Spanish";"Italian"];
T.Typ = V(T.V1)
T = 178×2 table
V1 Typ __ ________ 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French" 1 "French"

Eric Sofen
Eric Sofen 2022 年 3 月 17 日
This is what categorical is built for! When you create the categorical, you can specify the data, value set, and category names.
T = readtable("https://www.mathworks.com/matlabcentral/answers/uploaded_files/929319/Typ.csv");
T.Typ = categorical(T.V1, 1:3, ["French", "Spanish","Italian"])
T = 178×2 table
V1 Typ __ ______ 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French 1 French

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by