Reading numbers from String

조회 수: 3(최근 30일)
Lukas Ehrler
Lukas Ehrler 2022년 7월 20일
답변: Steven Lord 2022년 7월 20일
Hello,
I have the following string
str = {'SRm40_' 'SRp5_'}
I want to read the numbers from str and include the m for a minus.
my desired Output would look like this
numbers = [-40 5]
I have tried the sscanf and regexp function but i dont seem to get it working
sscanf returns this
[numbers,~,err] = sscanf(string(str(1)),'%*5d')
err = 'Matching failure in format.'
So it cant read the the string because the first location has the 'E'.
If someone has a idea how to solve this, dont hesitate to answer :)
Have a great day
  댓글 수: 4
Lukas Ehrler
Lukas Ehrler 2022년 7월 20일
thanks a lot for the quick answer!!

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2022년 7월 20일
Another approach:
str = {'SRm40_','SRp5_'};
vec = str2double(regexprep(str,{'[A-Z_]+','m','p'},{'','-','+'}))
vec = 1×2
-40 5

추가 답변(1개)

Steven Lord
Steven Lord 2022년 7월 20일
Yet another approach:
str = {'SRm40_','SRp5_'};
str = replace(str, 'm', '-'); % Handle negative numbers
str = replace(str, 'p', '+'); % Handle positive numbers
d = cellfun(@(x) sscanf(x, 'SR%d_'), str) % sscanf requires its first input to be scalar
d = 1×2
-40 5

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by