There is a string containing a number in an arbitrary format (e.g., 12, -34.5, and 6.78e-9). The goal is to convert this string into the corresponding number and then convert this number back to a string such that (a) the precision given in the original string is preserved, and (b) the resulting string has an adequate format (probably, the most adequate format is the format of the original string). I thought the problem could be easily solved using str2num and num2str; however, in some cases, MATLAB seems to be mangling the final result as shown below:
>> a = '1e23'
a =
1e23
>> b = str2num(a)
b =
1.0000e+23
>> c = num2str(b)
c =
9.999999999999999e+22
One solution is to use a general format string:
>> c = num2str(b, '%e')
c =
1.000000e+23
However, in this case, the output looks rather cumbersome for numbers of small orders:
>> d = num2str(1, '%e')
d =
1.000000e+00
In most cases, num2str without additional parameters does a pretty good job resulting in a nicely formatted string. The question is: Is there a way to eliminate the 9.999999999999999e+22 problem?
Thank you!
Regards,
Ivan
In general the representation of one input string does not contain enough information to determine the format. Hence (assuming you want to output slightly different numbers and cannot simply store the number in string format), the simplest way would be to try and find a format that you like.
Judging from your comments, I think you will be happy with:
format short g
For large numbers it will give:
x = num2str(1.0000e+23);str2num(x)
ans =
1e+23
And for small numbers:
x = num2str(1);str2num(x)
ans =
1
Related
I want to read a string in Matlab (not an external text file) which has numerical values separated by commas, such as
a = {'1,2,3'}
and I'd like to store it in a vector as numbers. Is there any function which does that? I only find processes and functions used to do that with text files.
I think you're looking for sscanf
A = sscanf(str,formatSpec) reads data from str, converts it according
to the format specified by formatSpec, and returns the results in an
array. str is either a character array or a string scalar.
You can try the str2num function:
vec = str2num('1,2,3')
If you have to use the cell a, per your example, it would be: vec=str2num(a{1})
There are some security warnings in the documentation to consider so be cognizant of how your code is being employed.
Another, more flexible, option is textscan. It can handle strings as well as file handles.
Here's an example:
cellResult = textscan('1,2,3', '%f','delimiter',',');
vec = cellResult{1};
I will use the eval function to "evaluate" the vector. If that is the structure, I will also use the cell2mat to get the '1,2,3' text (this can be approached by other methods too.
% Generate the variable "a" that contains the "vector"
a = {'1,2,3'};
% Generate the vector using the eval function
myVector = eval(['[' cell2mat(a) ']']);
Let me know if this solution works for you
Ideally, there should be 6 digits in a variable called 'subject'
"how to fill the 0 if not 6digit in the subject variable?"
example *subject = 387592(continue the process)
*subject = 35885(add zero to make 6digit = 035885)
*subject = 7161( add zeros 007161)
python zfill(6) helps to solve this kind of issues
An old school string parsing approach should do the trick:
substring(concat('000000',variables('IntString4')),sub(length(concat('000000',variables('IntString4'))),6),6)
Here's the breakdown:
Concat the existing string with leading zeros
concat('000000',variables('IntString4')
Measure the length of the string and subtract the desired length to calculate the starting index of the eventual substring:
sub(length(concat('000000',variables('IntString4'))),6)
Use substring to capture the last 6 characters:
substring(#1,#2,6)
You could make this a bit more readable and dynamic with variables, but same logic applies.
Have you tried using the "formatNumber" function?
For example, in your case
formatNumber('35885', '000000') -> Result "035885"
formatNumber('7161', '000000') -> Result "007161"
https://learn.microsoft.com/es-es/azure/logic-apps/workflow-definition-language-functions-reference#formatNumber
I have a question in Python 3.7. I am opening a text file (input.txt) and creating variables from various lines of the text file. For example my text file looks as follows:
Case1
P
1.00E+02
5.
I need to create variables so that:
title = "Case1"
area = "P"
distance = 100
factor = 5
So far this is what I have:
f = open('C:\\input.txt',"r")
title = f.readline().strip()
area = f.readline().strip()
distance = f.readline().strip()
factor = f.readline().strip().strip(".")
f.close
print(title)
print(area)
print(distance)
print(factor)
which results in:
Case1
P
1.00E+02
5
How do I get the distance variable to show up as 100 instead of 1.00E+02?
I found the link below thinking it would help, but wasn't able to solve my problem from there. This is a very small segment of my larger program that was simplified, but if it works here it will work for my needs. My program needs to open a generated text file and produce another text file, so the scientific notation number will change between 1.00E-06 and 1.00E+03. The generated text file needs to have these numbers as integers (i.e. between 0.000001 and 1000). Thanks for any help!
Converting number in scientific notation to int
The link you posted actually gives the answer, albeit in a roundabout way.
int() cannot parse strings that don't already represent integers.
But a scientific number is a float.
So, you need to cast it to float first to parse the string.
Try:
print(float(distance))
For numbers with more decimals (e.g your example of 1.00E-06), you can force float notation all the time. Try:
print(format(float(distance), 'f'))
If you only want a certain number of decimals, try:
print(format(float(distance), '.2f'))
(for example)
I know the string methods str.isdigit, str.isdecimal and str.isnumeric.
I'm looking for a built-in method that checks if a character is algebraic, meaning that it can be found in a declaration of a decimal number.
The above mentioned methods return False for '-1' and '1.0'.
I can use isdigit to retrieve a positive integer from a string:
string = 'number=123'
number = ''.join([d for d in string if d.isdigit()]) # returns '123'
But that doesn't work for negative integers or floats.
Imagine a method called isnumber that works like this:
def isnumber(s):
for c in s:
if c not in list('.+-0123456789'):
return False
return True
string1 = 'number=-1'
string2 = 'number=0.1'
number1 = ''.join([d for d in string1 if d.isnumber()]) # returns '-1'
number2 = ''.join([d for d in string2 if d.isnumber()]) # returns '0.1'
The idea is to test against a set of "basic" algebraic characters. The string does not have to contain a valid Python number. It could also be an IP address like 255.255.0.1.
.
Does a handy built-in that works approximately like that exist?
If not, why not? It would be much more efficient than a python function and very useful. I've seen alot of examples on stackoverflow that use str.isdigit() to retrieve a positive integer from a string. Is there a reason why there isn't a built-in like that, although there are three different methods that do almost the same thing?
No such function exists. There are a bunch of odd characters that can be part of number literals in Python, such as o, x and b in the prefix of integers of non-decimal bases, and e to introduce the exponential part of a float. I think those plus the hex digits (0-9 and A-F) and sign characters and the decimal point are all you need.
You can put together a string with the right character yourself and test against it:
from string import hex_digits
num_literal_chars = hex_digits + "oxOX.+-"
That will get a bunch of garbage though if you use it to test against mixed text and numbers:
string1 = "foo. bar. 0xDEADBEEF 10.0.0.1"
print("".join(c for c in string1 if c in num_literal_chars))
# prints "foo.ba.0xDEADBEEF10.0.0.1"
The fact that it gives you a bunch of junk is probably why no builtin function exists to do this. If you want to match a certain kind of number out of a string, write an appropriate regular expression to match that specific kind of number. Don't try to do it character-by-character, or try to match all the different kinds of Python numbers.
Hi can any one help me in dealing with strings in MATLAB. For example, the string
A = 'A good looking boy'
how can we store these individual words in arrays and later retrieve any of the words?
As found here, you could use
>> A = 'A good looking boy';
>> C = regexp(A,'[A-z]*', 'match')
C =
'A' 'good' 'looking' 'boy'
so that
>> C{1}
ans =
A
>> C{4}
ans =
boy
>> [C{:}]
ans =
Agoodlookingboy
The most intuitive way would be using strsplit
C = strsplit(A,' ')
However as it is not available in my version I suppose this is only a builtin function in matlab 2013a and above. You can find the documentation here.
If you are using an older version of matlab, you can also choose to get this File Exchange solution, which basically does the same.
You can use the simple function textscan for that:
C = textscan(A,'%s');
C will be a cell array. This function is in Matlab at least since R14.