Extract integer number from a cell array.

22 ビュー (過去 30 日間)
Biswajit Dipan Biswas
Biswajit Dipan Biswas 2019 年 10 月 1 日
編集済み: Akira Agata 2019 年 10 月 2 日
Hi,
I need to extract only number from a cell array. For example, from the cell array given below I only need to take 17 out,
{'REMOVE UNIT 1 FROM BUS 17←'}
or from the following cell I need 459 and 496
{'OPEN BRANCH FROM BUS 459 TO BUS 496 CIRCUIT 1←'}. How can I do that?
Till now what I've done, I've split the cell into multiple cells on the basis of delimiter, like the following
16×1 cell array
{'OPEN' }
{'BRANCH' }
{'FROM' }
{'BUS' }
{0×0 char }
{0×0 char }
{0×0 char }
{'459' }
{'TO' }
{'BUS' }
{0×0 char }
{0×0 char }
{0×0 char }
{'496' }
{'CIRCUIT'}
{'1←' }
what happens, depending on the number of spaces in between the index of the numbers vary in different cases. How can I solve this issue in a better approach? Please let me know.
Thank you.

採用された回答

Akira Agata
Akira Agata 2019 年 10 月 2 日
編集済み: Akira Agata 2019 年 10 月 2 日
If my understanding is correct, you are trying to extract numbers just after 'BUS'.
If so, how about the following?
% Original text
str =...
{'OPEN BRANCH FROM BUS 459 TO BUS 496 CIRCUIT 1←';...
'REMOVE UNIT 1 FROM BUS 17←'};
% Extract 'BUS + number'
data = regexp(str,'BUS\s+\d+','match');
% Extract number(s)
for kk = 1:numel(data)
data{kk} = regexprep(data{kk},'BUS\s+','');
end
The result is:
>> data{1}
ans =
1×2 cell array
{'459'} {'496'}
>> data{2}
ans =
1×1 cell array
{'17'}
  1 件のコメント
Biswajit Dipan Biswas
Biswajit Dipan Biswas 2019 年 10 月 2 日
This worked perfectly. Thank you sir.

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

その他の回答 (1 件)

James Tursa
James Tursa 2019 年 10 月 2 日
You could do this:
C = your cell array of strings, some containing numbers
d = str2double(C);
d = d(~isnan(d));
  1 件のコメント
Biswajit Dipan Biswas
Biswajit Dipan Biswas 2019 年 10 月 2 日
Thank you sir.

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by