Reading numbers from String
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Lukas Ehrler
am 20 Jul. 2022
Beantwortet: Steven Lord
am 20 Jul. 2022
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 Kommentare
Andrew McCauley
am 20 Jul. 2022
Bearbeitet: Andrew McCauley
am 20 Jul. 2022
In loop form in case needed:
str = {'SRm40_' 'SRp5_'};
numbers = zeros(1, length(str));
for countString = 1:length(str)
numbers(countString) = str2num(str{countString}(4:end-1));
if strcmp(str{countString}(3), 'm')
numbers(countString)=-numbers(countString);
end
end
Akzeptierte Antwort
Stephen23
am 20 Jul. 2022
Another approach:
str = {'SRm40_','SRp5_'};
vec = str2double(regexprep(str,{'[A-Z_]+','m','p'},{'','-','+'}))
0 Kommentare
Weitere Antworten (1)
Steven Lord
am 20 Jul. 2022
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
0 Kommentare
Siehe auch
Kategorien
Mehr zu String finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!