필터 지우기
필터 지우기

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

조회 수: 75 (최근 30일)
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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by