How can I set the FormatSpec to read this numerical value?

1 view (last 30 days)
Hi all,
I have some some difficulties to read from file the following numerical value by using textscan
'-1.661-4'
The problem lies in the lack of the exponential character that makes Matlab read -1.661.
Is there a simple way to set a FormatSpec to solve the problem. I tried with 'ExpChar ','' but it didn't work.
PS: this numerical value is within a loop where just few values have this structure.

Accepted Answer

dpb
dpb on 7 Dec 2018
ML doesn't have the facility built into any of the text conversion routines to handle the omitted exponent indicator; some Fortran compilers have that as an extension to allow such a format.
One way if the file is regular in there always being the two elements is to write a little processing function...
s='-1.661-4,3.141+0'; % more general input string example
v=reshape(cell2mat(textscan(s,'%f','delimiter',',')),2,[]).'; % parse fields to mantiss/exponent
v=v(:,1).*10.^v(:,2); % convert to value
>> fprintf('%g %g\n',v) % show what we got
-0.0001661 3.141
>>
If there are missing elements in some entries, then a parsing of each element and interpretation on a field-by-field basis would be necessary or write a more intelligent regular expression substitution pattern to correctly insert the missing exponent indication letter where it is needed.

More Answers (1)

Francesco Saltari
Francesco Saltari on 11 Dec 2018
The answer was really helpful and helped me to overcome the issue.
Unfortunately if I get something like this
s='-1.661,3.141+0';
the only way is to analyze each value indipendently so increasing the computational time.
Thank you so much

Community Treasure Hunt

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

Start Hunting!