# 文字列を数値に変換

14 views (last 30 days)
Ochi Kai on 7 Nov 2022
Answered: Atsushi Ueno on 8 Nov 2022

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

Shunichi Kusano on 8 Nov 2022
カテゴリカル行列がうってつけな気がします。
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
Atsushi Ueno on 8 Nov 2022
そうだ categorical 配列を忘れていました。

Atsushi Ueno on 7 Nov 2022

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

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 on 7 Nov 2022
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 on 8 Nov 2022
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

### Categories

Find more on コード生成 in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!