get 0 in the end of a regexp function

조회 수: 1 (최근 30일)
Adrian Brown
Adrian Brown 2021년 6월 11일
편집: Stephen23 2021년 6월 11일
Hello,
I have a number x= 1.25690e-15 in the first step I extract only the the first part of the x which mean firstPart = 1.25690 using the program bellow, then I used the fuction regexp to split the firstPart varibale to elements. in the result of the program I expect to get : [1 2 5 6 9 0] but Unfortunatly I got only [1 2 5 6 9].
x = 1.25690e-15;
string = sprintf('%.8e', x); % Convert number to a scientific notation string with 8 decimal places of precision
stringParts = strsplit(string,'e'); % Split the string where 'e' is
firstPart = str2double(stringParts(1)); % Get the 1st part of stringParts which is the first part of standard form.
k=str2double(regexp(num2str(firstPart),'\d','match')); % slpit the firstPart variable to elements
I really appreciate any help and suggestion.
  댓글 수: 2
Sebastiano Marinelli
Sebastiano Marinelli 2021년 6월 11일
I think you should try to work with string untill the end since when you convert the string to a number:
firstPart = str2double(stringParts(1));
Matlab does automatically remove the not usefull 0 since 1.25690 = 1.2569
something like this should work (yep it is not very elegant, but you can base on this code to solve your problem)
x = 1.25690e-15;
%Note that I had to change .8 to .5!!!
string = sprintf('%.5e', x); % Convert number to a scientific notation string with 8 decimal places of precision
stringParts = strsplit(string,'e'); % Split the string where 'e' is
firstPart = stringParts(1); % Get the 1st part of stringParts which is the first part of standard form.
%split the number into two parts: 1.25690 -> 1 and 25690
strSplit = split((firstPart{1}),'.');
%extract the decimal
decimals = strSplit(2);
%Reshape the decimal
for i = 1:length(decimals{1})
k(i) = str2double(decimals{1}(i));
end
Sebastiano Marinelli
Sebastiano Marinelli 2021년 6월 11일
of course you can still mantain the 8 decimal, you only have to change a bit the code

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

답변 (1개)

Stephen23
Stephen23 2021년 6월 11일
편집: Stephen23 2021년 6월 11일
x = 1.2569e-15;
v = regexprep(sprintf('%#.6g',x),{'\.','e.+'},'')-'0'
v = 1×6
1 2 5 6 9 0

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by