MATLAB Answers

Find only numeric strings on cellstr array.

2 ビュー (過去 30 日間)
Ajpaezm
Ajpaezm 2021 年 6 月 15 日
コメント済み: Ajpaezm 2021 年 6 月 15 日
I'd like to know the index of the "numerical strings" within a cellstr array.
arr = {'123', 'Hola', 'my', 'String', '', '1453', 'stay'};
A correct output will give me index 1 and 6.
isnumeric contained within cellfun doesn't work well here, I'd have to use it in combination with something else but I don't know exactly what that might be.
Any help is appreciated.

採用された回答

Krishna Sutar
Krishna Sutar 2021 年 6 月 15 日
From my understanding you want to find the indexes of the strings in the cell string array that are numerical. Here is the code which might help you:
arr = {'123', 'Hola', 'my', 'String', '', '1453', 'stay'};
idx = find(~isnan(str2double(arr)))
isnumeric checks whether the datatype of the object is numeric, which in this case is string which would return false. Please refer to isnumeric and find for more information.
  3 件のコメント
Ajpaezm
Ajpaezm 2021 年 6 月 15 日
@Stephen Cobeldickthank you, I understand. Luckily, the array won't have any presence of them, but in case some weird stuff happens and indeed gets populated with it, I'll be sure to use your proposal.

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2021 年 6 月 15 日
arr = {'123', 'Hola', 'my', 'String', '', '1453', 'stay'};
find(~cellfun(@isempty, regexp(arr, '^\d+$', 'once')))
ans = 1×2
1 6
find(matches(arr, lineBoundary + digitsPattern + lineBoundary))
ans = 1×2
1 6

Stephen
Stephen 2021 年 6 月 15 日
編集済み: Stephen 2021 年 6 月 15 日
Writing regular expressions or pattern matching that robustly detects all valid number formats is not such a trivial task... it is more reliable to let MATLAB do the heavy lifting:
arr = {'123', 'Hola', 'my', 'String', '', '1453', 'stay', '-1.234', 'NaN', '9e-87'};
idx = strcmpi(arr,'NaN')|~isnan(str2double(arr))
idx = 1×10 logical array
1 0 0 0 0 1 0 1 1 1
find(idx)
ans = 1×5
1 6 8 9 10

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by