文字列を数値に変換

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

 Accepted Answer

Shunichi Kusano
Shunichi Kusano on 8 Nov 2022

2 votes

カテゴリカル行列がうってつけな気がします。
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 Comment

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

Sign in to comment.

More Answers (4)

Atsushi Ueno
Atsushi Ueno on 7 Nov 2022

2 votes

本質問の対象となるリリースは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
文字列一致判定で数値を代入する例を記述します。
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 on 7 Nov 2022

1 vote

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

0 votes

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 MATLAB 入門 in Help Center and File Exchange

Products

Release

R2022a

Tags

Community Treasure Hunt

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

Start Hunting!