Remove strings from an array based on string length

4 ビュー (過去 30 日間)
Aravind Vicinthangal Prathivaathi
Aravind Vicinthangal Prathivaathi 2019 年 10 月 13 日
編集済み: Stephen23 2019 年 10 月 14 日
Hello. I'm trying to remove strings from a string array based on string length. I want to remove strings with lesser than 2 alphabets. I tried the following code but I'm getting an error
clc; clear;
s = {'a';'b';'cat';'apple'};
s1 = string(s);
String_length = strlength(s1);
Min_length = 2;
Modified_string = [s1 String_length];
indices = find(Modified_string(:,2) < Min_length);
Modified_string(indices,:) = [];
Error using <
Comparison between string and double is not supported.
Error in Dummy (line 8)
indices = find(Modified_string(:,2) < Min_length);
  1 件のコメント
Stephen23
Stephen23 2019 年 10 月 14 日
編集済み: Stephen23 2019 年 10 月 14 日
This approach is very complex, with one implicit conversion from numeric to string, which then requires an explicit conversion from string to numeric. Pointless type conversions should be avoided, as they just slow code down without any benefit.
Here is a much simpler and more efficient solution using basic MATLAB indexing:
out = s1(strlength(s1)>=2))

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

採用された回答

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2019 年 10 月 13 日
For you to do the comparison you must first convert the string to a numeric. The following code should solve your problem:
clc; clear;
s = {'a';'b';'cat';'apple'};
s1 = string(s);
String_length = strlength(s1);
Min_length = 2;
Modified_string = [s1 String_length];
indices = find( str2double(Modified_string(:,2)) < Min_length);
Modified_string(indices,:) = []
Modified_string =
2×2 string array
"cat" "3"
"apple" "5"

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by