syntax of readmtx(fname,nrows,ncols,precision) in matlab - matlab

I want to read a matrix from file using the following syntax in MATLAB . This matrix is of double numbers .
readmtx(fname,nrows,ncols,precision)
Here all the inputs are quite familiar to me . But I want to know about precision . The precision of int is 'int16'. What is the precision of double number?

In this case, the documentation states:
Both binary and formatted data files can be read. If the file is binary, the precision argument is a format string recognized by fread. Repetition modifiers such as '40*char' are not supported. If the file is formatted, precision is a fscanf and sscanf-style format string of the form '%nX', where n is the number of characters within which the formatted data is found, and X is the conversion character such as 'g' or 'd'. Fortran-style double-precision output such as '0.0D00' can be read using a precision string such as '%nD', where n is the number of characters per element. This is an extension to the C-style format strings accepted by sscanf. Users unfamiliar with C should note that '%d' is preferred over '%i' for formatted integers. MATLAB syntax follows C in interpreting '%i' integers with leading zeros as octal. Formatted files with line endings need to provide the number of trailing bytes per row, which can be 1 for platforms with carriage returns or linefeed (Macintosh, UNIX®), or 2 for platforms with carriage returns and linefeeds (DOS).
In addition it is helpful to look at the table summary in the fread documentation:

Related

Format Matlab data to only have digits after the decimal place

I used dlmwrite to output some data in the following form:
-1.7693255974E+00,-9.7742420654E-04, 2.1528647648E-04,-1.4866241234E+00
What I really want is the following format:
-.1769325597E+00, -.9774242065E-04, .2152864764E-04, -.1486624123E+00
A space is required before each number, followed by a sign, if the number is negative, and the number format is comma delimited, in exponential form to 10 significant digits.
Just in case Matlab is not able to write to this format (-.1769325597E+00), what is it called specifically so that I can research other means of solving my problem?
Although this feels morally wrong, one can use regular expressions to move the decimal point. This is what the function
myFormat = #(x) regexprep(sprintf('%.9e', 10*x), '(\d)\.', '\.$1');
does. The input value is multiplied by 10 prior to formatting, to account for the point being moved. Example: myFormat(-pi^7) returns -.3020293228e+04.
The above works for individual numbers. The following version is also able to format arrays, providing comma separators. The second regexprep removes the trailing comma.
myArrayFormat = #(x) regexprep(regexprep(sprintf('%.9e, ', 10*x), '(\d)\.', '\.$1'), ', $', '');
Example: myArrayFormat(1000*rand(1,5)-500) returned
-.2239749230e+03, .1797026769e+03, .1550980040e+03, -.3373882648e+03, -.3810023184e+03
For individual numbers, myArrayFormat works identically to myFormat.

How to give ascii characters as input in simulink

I have to give ascii characters as input from simulink to stateflow and need to check whether the input matches with the existing ascii character. Can anyone help me to solve this? will be of a great help?
Example:
If I give ascii characters 'AF' as input from simulink to stateflow. It has to produce 1 as output if it matches with the existing ascii character in condition.
Simulink/Stateflow prefer numeric data. You should use an integer representation of the ASCII value (using a uint8 or uint16 data type), which will make comparison almost trivial.
Matlab does not make a clear distinction between a string with just one char and a char, and as far as I know, it is not possible to use a string type in stateflow.
Convert the input to integers then use only comparisons of integers inside the state chart.
You can use this function to convert chars to integers in Matlab:
function [ integer ] = atoi( char )
%ATOI Ascii To Integer converts char to int
%
integer = char - '0' + '0' ; %matlab seems a bit lunatic when it comes to chars
end

What are the valid formats for numbers in MATLAB?

What are the valid formats are for numbers in MATLAB? The following seem to be valid:
x=0;
x=0.;
x=0.0;
x=0e0;
x=0E0;
x=0000.00; % Trailing and leading zeros seem to be irrelevant
Are there other valid general number specifications? I can't find this in the documentation.
I believe this is the regex of floating-point number formats, valid in MATLAB:
^[-+]*([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.[0-9]*)([eEdD][+-]?[0-9]+)?$
Compiled from here, and slightly modified for MATLAB:
added 'd' exponent character (as is common in FORTRAN, MATLAB's ancestor)
added uppercase exponent characters
added extra case in the required order before and after the decimal symbol
I'm pretty sure the locale can mess this up, e.g., the decimal separator . might be set to , as is common here in Europe. Oh well.
The regex in words:
string start, followed by
zero or more consecutive sign symbols, followed by
non-zero length string of consecutive integers, OR
possibly zero-length string of consecutive integers, followed by a dot, followed by non-zero length string of consecutive integers, OR
non-zero length string of consecutive integers, followed by a dot, followed by a possibly zero-length string of consecutive integers
optionally followed by the exponent part:
one of e, E, d or D.
zero or one sign symbols, followed by
non-zero length string of consecutive integers
followed by string terminator
Note that this is for non-complex floating point values. For complex values, you'd have to
use the regex once for the real, once for the imaginary part
append [ij]{1} to the imaginary part (only lower case)
take care of spacing (\s*) and a [+-]{1} in between the two parts
take care of the fact that the imaginary part may appear alone, but the real part may not appear with a trailing [+-]{1}, but no imaginary part.

How to fscanf a combination of float and string?

The data is like this
5.1,3.5,1.4,0.2,Iris-setosa
while I read it using this
data = fscanf(file, '%f,%f,%f,%f,%s');
and it turned out that data is an array of float rather than a combination of float and string. So how do I read this data from txt?
From the Matlab docs for fscanf:
Output Arguments A: An array. If the format includes:
Only numeric specifiers, A is numeric. ... Only character or
string specifiers (%c or %s), A is a character array. ... A
combination of numeric and character specifiers, A is numeric, of
class double. MATLAB converts each character to its numeric
equivalent. This conversion occurs even when the format explicitly
skips all numeric values (for example, a format of '%*d %s').
So your best bet is to read everything in as strings, and then convert the numeric strings to numeric values, using str2num or str2double or similar.
Alternatively, since you know there are 4 floating point values that really store a floating point value, and then the rest store the numeric ASCII values for the string, you can always split up your data and cast the part you know should be a string to char. Something like:
flt = data(1:4);
str = char(data(5:end));

Float to text behavior of MATLAB's fprintf()

When using fprintf to convert floats to text in a decimal representation, the output is a series of decimal digits (potentially beginning with 0).
How does this representation work?
>>fprintf('%tu\n',pi)
>>1078530011
>>fprintf('%bu\n',pi)
>>04614256656552045848
Apologies if this is very trivial; I can't find an answer elsewhere, in part because searches are swamped by the various decimal data types available.
Note that the %t and %b flags are two of the differences from C's fprintf(). According to the documentation, it prints a float or double respectively "rather than an unsigned integer." o, x and u switches between octal, hex and decimal.
This representation is the binary IEEE 754 floating point representation of the number, printed as an unsigned integer.
The IEEE 754 Converter website tells us that the IEEE 754 single-precision representation of Pi (approximately 3.1415927) is 40490FDB hexadecimal, which is 1078530011 decimal (the number that you saw printed). The '%bu' format specifier works similarly but outputs the double-precision representation.
The purpose of these format specifiers is to allow you to store a bit-exact representation of a floating-point value to a text file. The alternative approach of printing the floating-point value in human-readable form requires a lot of care if you want to guarantee bit-exact storage, and there might be some edge cases (denormalized values...?) that you won't be able to store precisely at all.
If you were to print the number as hexadecimals:
>> fprintf('%bx\n', pi)
400921fb54442d18
>> fprintf('%tx\n', single(pi))
40490fdb
then the formatters '%bx' and '%tx' are simply equivalent to using NUM2HEX:
>> num2hex( pi )
400921fb54442d18
>> num2hex( single(pi) )
40490fdb
Another way is to simply set the default output format to hexadecimals using:
>> format hex
>> pi
400921fb54442d18
>> single(pi)
40490fdb
On a related note, there was a recent article by #Loren:
"How Many Digits to Write?"
where they try to find how many decimal digits you need to write in order to retain the number's full precision when re-read in MATLAB.