文字列を数値に変換

例えば変数A=["apple", "apple","banana", "orange"];
といった中に文字が入力されている変数があるとします。
これをapple=1,banana=2, orange=3だとしてA=[1,1,2,3]のように変換したいと考えています。
いくつか方法を試したのですが、上手くいかず困っています。
ご教授いただけると幸いです。

 Respuesta aceptada

Shunichi Kusano
Shunichi Kusano el 8 de Nov. de 2022

2 votos

カテゴリカル行列がうってつけな気がします。
A=["apple", "apple","banana", "orange"];
fruitsCat = categorical(A,["apple","banana","orange"]) % 第2引数は重複のない要素→これが順に1,2,3となる
fruitsCat = 1×4 categorical array
apple apple banana orange
uint8(fruitsCat) % カテゴリカルに対応する数値に変換
ans = 1×4
1 1 2 3

1 comentario

Atsushi Ueno
Atsushi Ueno el 8 de Nov. de 2022
そうだ categorical 配列を忘れていました。

Iniciar sesión para comentar.

Más respuestas (4)

Atsushi Ueno
Atsushi Ueno el 7 de Nov. de 2022

2 votos

本質問の対象となるリリースはR2022a、下記回答はR2022bで導入された機能ですが、一応書いておきます。
fruits = ["apple","banana","orange"];
numbers = [1,2,3];
dic = dictionary(fruits,numbers)
dic =
dictionary (stringdouble) with 3 entries: "apple" ⟼ 1 "banana" ⟼ 2 "orange" ⟼ 3
A = ["apple","apple","banana","orange"];
dic(A) % arrayfunが要らない!
ans = 1×4
1 1 2 3
交感神経優位なあかべぇ
交感神経優位なあかべぇ el 8 de Nov. de 2022

2 votos

文字列一致判定で数値を代入する例を記述します。
A=["apple", "apple", "banana", "orange"];
Anum = zeros(1, length(A));
Anum(strcmp(A, "apple")) = 1;
Anum(strcmp(A, "banana")) = 2;
Anum(strcmp(A, "orange")) = 3;
disp(Anum);
1 1 2 3
Atsushi Ueno
Atsushi Ueno el 7 de Nov. de 2022

1 voto

mapObj = containers.Map(["apple","banana","orange"], [1,2,3])
mapObj =
Map with properties: Count: 3 KeyType: char ValueType: double
A = ["apple","apple","banana","orange"];
arrayfun(@(x) mapObj(x),A)
ans = 1×4
1 1 2 3
Atsushi Ueno
Atsushi Ueno el 8 de Nov. de 2022

0 votos

type fruits.m % 添付のクラス定義ファイルを表示
classdef fruits < uint8 enumeration apple (1) banana (2) orange (3) end end
A = ["apple","apple","banana","orange"];
Aenum = arrayfun(@(x) fruits.(x), A)
Aenum =
1×4 fruits enumeration array apple apple banana orange
Anum = double(Aenum)
Anum = 1×4
1 1 2 3

Categorías

Más información sobre MATLAB 入門 en Centro de ayuda y File Exchange.

Productos

Versión

R2022a

Etiquetas

Preguntada:

el 7 de Nov. de 2022

Respondida:

el 8 de Nov. de 2022

Community Treasure Hunt

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

Start Hunting!