Number to string within numeric matrix

1 回表示 (過去 30 日間)
Tyler Smith
Tyler Smith 2016 年 10 月 6 日
編集済み: lenny006 2016 年 10 月 7 日
I have numbers (1-20) which correspond to a city. I want to convert each number to a string to more easily read the city. For example: 1 = 'Atlanta', 2='Boston', etc. I have the data grouped in cell arrays based on a specific column, but also have the data in a 425x15 matrix (before grouping). Is it possible to replace the city numbers with city names? Thanks.
  1 件のコメント
Tyler Smith
Tyler Smith 2016 年 10 月 6 日
Thanks for all the help! I ended up using a combination of your answers. I used a categorical and turned it into a table, then turned my double into a table so I could horzcat and visualize the cities next to their respective data.

サインインしてコメントする。

採用された回答

dbmn
dbmn 2016 年 10 月 6 日

have you tried using a categorical?

categorical([1 2 1 1 2 2], [1,2], {'Atlanta'; 'Boston'})
ans = 
     Atlanta      Boston      Atlanta      Atlanta      Boston      Boston 

その他の回答 (3 件)

Matthias Walle
Matthias Walle 2016 年 10 月 6 日
Hi,
create a new class file
classdef city < uint32
enumeration
Atlanta (1)
Boston (2)
Whatever (3)
andsoon (4)
end
end
then you can use
city(1)
for example to get Atlanta
I hope this works for you
  2 件のコメント
Tyler Smith
Tyler Smith 2016 年 10 月 6 日
When I use this, it simply returns a 1 for Atlanta, 2 for Boston, and so on (which I already have). I need it to return the names instead of the numbers. Perhaps I am using it incorrectly.
lenny006
lenny006 2016 年 10 月 7 日
編集済み: lenny006 2016 年 10 月 7 日
Thank you very much. This has helped me indeed, Matthias Walle

サインインしてコメントする。


Steven Lord
Steven Lord 2016 年 10 月 6 日
You can't store both numbers and characters in a numeric array or a char array without conversion.
A = ones(2) % A is a double array
A(4) = 'A' % double('A') is 65, so A will be [1 1; 1 65]
B = 'ABCDE' % B is a char array
B(5) = 90 % char(90) is 'Z' so B will be 'ABCDZ'
You could use a cell array or a table to store data of both types.
C = {ones(5), 'abracadabra'}
x = [1; 3; 6; 10];
y = {'Amherst'; 'Boston'; 'Cambridge'; 'Easthampton'};
ind = [1 1 2 2 2 2 3 3 3 4]
D = y(ind)
E = table(x, y)

Jan
Jan 2016 年 10 月 6 日
You can use the city numbers as indices:
Names = {'Atlanta', 'Boston', 'Chicago'};
Data = [1, 3.14; 3, 7.07; 2, 2.71];
fprintf(%s\n', Names{Data(:, 1)})

カテゴリ

Help Center および File ExchangeLarge Files and Big Data についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by