フィルターのクリア

How to remove spaces and special characters from elements of a char array

75 ビュー (過去 30 日間)
harshpurohit11
harshpurohit11 2018 年 8 月 17 日
コメント済み: Image Analyst 2018 年 8 月 18 日
char array names = ['time (s)', 'speed (%)',....]
I want to save the char array such that () and % characters are removed, meaning names = ['time_s', 'accel_pedal',...]
  5 件のコメント
harshpurohit11
harshpurohit11 2018 年 8 月 18 日
編集済み: harshpurohit11 2018 年 8 月 18 日
I have a 640 elements long char array with three set of characters %, (, ) and spaces which I want to replace with '_'. I am using matlab 2014a which does not have the strrep function in it.
Image Analyst
Image Analyst 2018 年 8 月 18 日
Yes you do. It was introduced before R2006a.

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

採用された回答

Walter Roberson
Walter Roberson 2018 年 8 月 18 日
str = regexp( names, '[%() ]', '_');
But more likely you want
str = regexp(names, {'[%() ]+', '_+$'}, {'_', ''});
But it is a bit confusing what you are asking, especially since you are using a version before the string() data type. The notation
['time (s)', 'speed (%)',....]
would create a single character vector that started with
'time (s)speed (%)'
and once that was constructed there would be no way of knowing where the original breaks between the elements had been -- not unless we could count on each entry ending in ')' . If we can count on that, then would the desired output be
'time_s speed'
?
I am uncertain as to your actual input is something like,
names = ['time (s) ';
'speed (%)']
so a char array with 640 rows and blank padding to make the rows all the same size? If so then preserving the char array nature would be slightly awkward, and would raise the question of whether the new char array should be the same size as the input or should instead only have as many columns as needed to represent the widest entry excluding trailing blanks.
Or perhaps what you have is a cell array of character vectors,
names = {'time (s)', 'speed (%)',....};
If so then the two regexp() I posted above will work.
  2 件のコメント
harshpurohit11
harshpurohit11 2018 年 8 月 18 日
Thanks a lot for the answers walter. And you are right names = {'time (s)'; 'speed (%)';...}. However when i tried using two regexp() i got an error saying 'The 'STRING' input must be a one-dimensional array of char or cell arrays of strings.'
Walter Roberson
Walter Roberson 2018 年 8 月 18 日
str = regexprep(names, {'[%() ]+', '_+$'}, {'_', ''});

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by