How to create a numerical variable from a string stored in a cell array ?

I have a cell array that looks as follows:
countrycode = {'ALB';'ALB';'ALB';'ARG';'ARG';'BRA';'BRA';'BRA';'BRA'}
This is a short example, the list has about 50 countries, each with a different number of entries.
1. How can I create a numerical variable that assigns the value 1 to all 'ALB' entries, 2 to all 'ARG' entries, 3 to all 'BRA' entries and so on? 2. Is there a command akin to 'foreach' that would allow me to loop over all possible country codes? for instance, to extract data in a numerical variable associated with the variable countrycode?

1 件のコメント

KSSV
KSSV 2017 年 3 月 15 日
What is the necessity to assign a number for it?

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

 採用された回答

Alexandra Harkai
Alexandra Harkai 2017 年 3 月 15 日
To get the numeric values:
country_idx = findgroups(countrycode);
For the second part, it really depends on what is it exactly you want to do. splitapply till likely be a helpful, for example, to count the number of entries within each country:
splitapply(@numel, countrycode, country_idx)

1 件のコメント

azr124
azr124 2017 年 3 月 15 日
Thanks Alexandra! Once I have the numerical values I can use these for looping.

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

その他の回答 (1 件)

Rik
Rik 2017 年 3 月 15 日
You can use unique to generate the list of codes, followed by ismember to find out the locations, so the result is a vector.
countrycode = {'ALB';'ALB';'ALB';'ARG';'ARG';'BRA';'BRA';'BRA';'BRA'};
list=unique(countrycode);
[~,Locb] = ismember(countrycode,list);
To my knowledge there is no foreach command in Matlab, but you can use a for-loop to loop over all the possible values. I suspect what you want may also be achieved without a loop, but you'dd have to tell us more about what exactly you want to do.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2017 年 3 月 15 日

コメント済み:

2017 年 3 月 15 日

Community Treasure Hunt

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

Start Hunting!

Translated by