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 件のコメント

Andrew McCauley
Andrew McCauley 2022 年 7 月 20 日
編集済み: Andrew McCauley 2022 年 7 月 20 日
This works for me:
str = {'SRm40_' 'SRp5_'};
number1 = str2num(str{1}(4:end-1));
if strcmp(str{1}(3), 'm')
number1=-number1;
end
number2 = str2num(str{2}(4:end-1));
if strcmp(str{2}(3), 'm')
number2=-number2;
end
numbers=[number1 number2];
Andrew McCauley
Andrew McCauley 2022 年 7 月 20 日
(and if it's much more than two numbers, it won't be hard to turn into a loop)
Andrew McCauley
Andrew McCauley 2022 年 7 月 20 日
編集済み: Andrew McCauley 2022 年 7 月 20 日
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
Lukas Ehrler
Lukas Ehrler 2022 年 7 月 20 日
thanks a lot for the quick answer!!

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

 採用された回答

Stephen23
Stephen23 2022 年 7 月 20 日

0 投票

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 日

0 投票

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

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2021b

タグ

質問済み:

2022 年 7 月 20 日

回答済み:

2022 年 7 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by