How do you create a floating point array in MATLAB? - matlab

I'm trying to create a 10 x 8 array in MATLAB filled with floating-point values.
Ideas?
UPDATE:
I am actually trying to create an empty 10 x 8 float-type array. How can I do that?

You might want to have a look at the zeros function. To create a 10 x 8 matrix containing all zeros, use
matrix = zeros(10, 8);
To force the elements to be of a certain type (e.g. single precision), use the additional class argument like
matrix = zeros(10, 8, 'single');
(I think, the default is double precision)

matrix = single(rand(10,8));
float is a single in Matlab
rand(10,8); returns a matrix of dimension 10x8 formatted as doubles...you can cast the return value to single(rand(10,8)) to get floating point values...if for some reason you need to have floating point precision instead of double floating point procision

UPDATE: the clarification from the OP made this answer outdated.
If you just want to create a matrix with specific values, here is a one-liner approach:
data = [0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9;0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9; ...; 0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9]
multi-liner approach (if you are about to copy-paste data):
data = [
0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9
0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9
0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9
0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9
...
0. 0.1 0.2 3. 4. 5. 6. 7. 8. 0.9
]
However, as many wrote rand(10,8) right off the bed, you can see, it is common practice not to use some kind of function to create a (10,8) matrix. Say: rand,ones, zeros, or some other tricks say reshape((1:1:80), 10, 8).

This is an old question but I'm posting my answer in case anyone stumbled across the same problem. Assuming that you're trying to get 32 digits precision, use
M=vpa(zeros(10,8)).

Related

How is Powershell rounding Doubles when multiplying with Strings? [duplicate]

In C#, the result of Math.Round(2.5) is 2.
It is supposed to be 3, isn't it? Why is it 2 instead in C#?
Firstly, this wouldn't be a C# bug anyway - it would be a .NET bug. C# is the language - it doesn't decide how Math.Round is implemented.
And secondly, no - if you read the docs, you'll see that the default rounding is "round to even" (banker's rounding):
Return ValueType: System.DoubleThe integer nearest a. If the
fractional component of a is halfway
between two integers, one of which is
even and the other odd, then the even
number is returned. Note that this
method returns a Double instead of an
integral type.
RemarksThe behavior of this method follows IEEE Standard 754,
section 4. This kind of rounding is
sometimes called rounding to nearest,
or banker's rounding. It minimizes
rounding errors that result from
consistently rounding a midpoint value
in a single direction.
You can specify how Math.Round should round mid-points using an overload which takes a MidpointRounding value. There's one overload with a MidpointRounding corresponding to each of the overloads which doesn't have one:
Round(Decimal) / Round(Decimal, MidpointRounding)
Round(Double) / Round(Double, MidpointRounding)
Round(Decimal, Int32) / Round(Decimal, Int32, MidpointRounding)
Round(Double, Int32) / Round(Double, Int32, MidpointRounding)
Whether this default was well chosen or not is a different matter. (MidpointRounding was only introduced in .NET 2.0. Before then I'm not sure there was any easy way of implementing the desired behaviour without doing it yourself.) In particular, history has shown that it's not the expected behaviour - and in most cases that's a cardinal sin in API design. I can see why Banker's Rounding is useful... but it's still a surprise to many.
You may be interested to take a look at the nearest Java equivalent enum (RoundingMode) which offers even more options. (It doesn't just deal with midpoints.)
That's called rounding to even (or banker's rounding), which is a valid rounding strategy for minimizing accrued errors in sums (MidpointRounding.ToEven). The theory is that, if you always round a 0.5 number in the same direction, the errors will accrue faster (round-to-even is supposed to minimize that) (a).
Follow these links for the MSDN descriptions of:
Math.Floor, which rounds down towards negative infinity.
Math.Ceiling, which rounds up towards positive infinity.
Math.Truncate, which rounds up or down towards zero.
Math.Round, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)" becoming 3).
The following diagram and table may help:
-3 -2 -1 0 1 2 3
+--|------+---------+----|----+--|------+----|----+-------|-+
a b c d e
a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8
====== ====== ===== ===== =====
Floor -3 -1 0 1 2
Ceiling -2 0 1 2 3
Truncate -2 0 0 1 2
Round(ToEven) -3 0 0 2 3
Round(AwayFromZero) -3 -1 0 2 3
Note that Round is a lot more powerful than it seems, simply because it can round to a specific number of decimal places. All the others round to zero decimals always. For example:
n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15
With the other functions, you have to use multiply/divide trickery to achieve the same effect:
c = System.Math.Truncate (n * 100) / 100; // 3.14
d = System.Math.Ceiling (n * 100) / 100; // 3.15
(a) Of course, that theory depends on the fact that your data has an fairly even spread of values across the even halves (0.5, 2.5, 4.5, ...) and odd halves (1.5, 3.5, ...).
If all the "half-values" are evens (for example), the errors will accumulate just as fast as if you always rounded up.
You should check MSDN for Math.Round:
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding.
You can specify the behavior of Math.Round using an overload:
Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3
Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2
From MSDN, Math.Round(double a) returns:
The integer nearest a. If the
fractional component of a is halfway
between two integers, one of which is
even and the other odd, then the even
number is returned.
... and so 2.5, being halfway between 2 and 3, is rounded down to the even number (2). this is called Banker's Rounding (or round-to-even), and is a commonly-used rounding standard.
Same MSDN article:
The behavior of this method follows
IEEE Standard 754, section 4. This
kind of rounding is sometimes called
rounding to nearest, or banker's
rounding. It minimizes rounding errors
that result from consistently rounding
a midpoint value in a single
direction.
You can specify a different rounding behavior by calling the overloads of Math.Round that take a MidpointRounding mode.
The nature of rounding
Consider the task of rounding a number that contains a fraction to, say, a whole number. The process of rounding in this circumstance is to determine which whole number best represents the number you are rounding.
In common, or 'arithmetic' rounding, it is clear that 2.1, 2.2, 2.3 and 2.4 round to 2.0; and 2.6, 2.7, 2.8 and 2.9 to 3.0.
That leaves 2.5, which is no nearer to 2.0 than it is to 3.0. It is up to you to choose between 2.0 and 3.0, either would be equally valid.
For minus numbers, -2.1, -2.2, -2.3 and -2.4, would become -2.0; and -2.6, 2.7, 2.8 and 2.9 would become -3.0 under arithmetic rounding.
For -2.5 a choice is needed between -2.0 and -3.0.
Other forms of rounding
'Rounding up' takes any number with decimal places and makes it the next 'whole' number. Thus not only do 2.5 and 2.6 round to 3.0, but so do 2.1 and 2.2.
Rounding up moves both positive and negative numbers away from zero. Eg. 2.5 to 3.0 and -2.5 to -3.0.
'Rounding down' truncates numbers by chopping off unwanted digits. This has the effect of moving numbers towards zero. Eg. 2.5 to 2.0 and -2.5 to -2.0
In "banker's rounding" - in its most common form - the .5 to be rounded is rounded either up or down so that the result of the rounding is always an even number. Thus 2.5 rounds to 2.0, 3.5 to 4.0, 4.5 to 4.0, 5.5 to 6.0, and so on.
'Alternate rounding' alternates the process for any .5 between rounding down and rounding up.
'Random rounding' rounds a .5 up or down on an entirely random basis.
Symmetry and asymmetry
A rounding function is said to be 'symmetric' if it either rounds all numbers away from zero or rounds all numbers towards zero.
A function is 'asymmetric' if rounds positive numbers towards zero and negative numbers away from zero.. Eg. 2.5 to 2.0; and -2.5 to -3.0.
Also asymmetric is a function that rounds positive numbers away from zero and negative numbers towards zero. Eg. 2.5 to 3.0; and -2.5 to -2.0.
Most of time people think of symmetric rounding, where -2.5 will be rounded towards -3.0 and 3.5 will be rounded towards 4.0. (in C# Round(AwayFromZero))
The default MidpointRounding.ToEven, or Bankers' rounding (2.5 become 2, 4.5 becomes 4 and so on) has stung me before with writing reports for accounting, so I'll write a few words of what I found out, previously and from looking into it for this post.
Who are these bankers that are rounding down on even numbers (British bankers perhaps!)?
From wikipedia
The origin of the term bankers'
rounding remains more obscure. If this
rounding method was ever a standard in
banking, the evidence has proved
extremely difficult to find. To the
contrary, section 2 of the European
Commission report The Introduction of
the Euro and the Rounding of Currency
Amounts suggests that there had
previously been no standard approach
to rounding in banking; and it
specifies that "half-way" amounts
should be rounded up.
It seems a very strange way of rounding particularly for banking, unless of course banks use to receive lots of deposits of even amounts. Deposit £2.4m, but we'll call it £2m sir.
The IEEE Standard 754 dates back to 1985 and gives both ways of rounding, but with banker's as the recommended by the standard. This wikipedia article has a long list of how languages implement rounding (correct me if any of the below are wrong) and most don't use Bankers' but the rounding you're taught at school:
C/C++ round() from math.h rounds away from zero (not banker's rounding)
Java Math.Round rounds away from zero (it floors the result, adds 0.5, casts to an integer). There's an alternative in BigDecimal
Perl uses a similar way to C
Javascript is the same as Java's Math.Round.
From MSDN:
By default, Math.Round uses
MidpointRounding.ToEven. Most people
are not familiar with "rounding to
even" as the alternative, "rounding
away from zero" is more commonly
taught in school. .NET defaults to
"Rounding to even" as it is
statistically superior because it
doesn't share the tendency of
"rounding away from zero" to round up
slightly more often than it rounds
down (assuming the numbers being
rounded tend to be positive.)
http://msdn.microsoft.com/en-us/library/system.math.round.aspx
Since Silverlight doesn't support the MidpointRounding option you have to write your own. Something like:
public double RoundCorrect(double d, int decimals)
{
double multiplier = Math.Pow(10, decimals);
if (d < 0)
multiplier *= -1;
return Math.Floor((d * multiplier) + 0.5) / multiplier;
}
For the examples including how to use this as an extension see the post: .NET and Silverlight Rounding
I had this problem where my SQL server rounds up 0.5 to 1 while my C# application didn't. So you would see two different results.
Here's an implementation with int/long. This is how Java rounds.
int roundedNumber = (int)Math.Floor(d + 0.5);
It's probably the most efficient method you could think of as well.
If you want to keep it a double and use decimal precision , then it's really just a matter of using exponents of 10 based on how many decimal places.
public double getRounding(double number, int decimalPoints)
{
double decimalPowerOfTen = Math.Pow(10, decimalPoints);
return Math.Floor(number * decimalPowerOfTen + 0.5)/ decimalPowerOfTen;
}
You can input a negative decimal for decimal points and it's word fine as well.
getRounding(239, -2) = 200
Silverlight doesn't support the MidpointRounding option.
Here's an extension method for Silverlight that adds the MidpointRounding enum:
public enum MidpointRounding
{
ToEven,
AwayFromZero
}
public static class DecimalExtensions
{
public static decimal Round(this decimal d, MidpointRounding mode)
{
return d.Round(0, mode);
}
/// <summary>
/// Rounds using arithmetic (5 rounds up) symmetrical (up is away from zero) rounding
/// </summary>
/// <param name="d">A Decimal number to be rounded.</param>
/// <param name="decimals">The number of significant fractional digits (precision) in the return value.</param>
/// <returns>The number nearest d with precision equal to decimals. If d is halfway between two numbers, then the nearest whole number away from zero is returned.</returns>
public static decimal Round(this decimal d, int decimals, MidpointRounding mode)
{
if ( mode == MidpointRounding.ToEven )
{
return decimal.Round(d, decimals);
}
else
{
decimal factor = Convert.ToDecimal(Math.Pow(10, decimals));
int sign = Math.Sign(d);
return Decimal.Truncate(d * factor + 0.5m * sign) / factor;
}
}
}
Source: http://anderly.com/2009/08/08/silverlight-midpoint-rounding-solution/
Simple way is:
Math.Ceiling(decimal.Parse(yourNumber + ""));
Rounding numbers with .NET has the answer you are looking for.
Basically this is what it says:
Return Value
The number nearest value with precision equal to digits. If value is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of value is less than digits, then value is returned unchanged.
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. If digits is zero, this kind of rounding is sometimes called rounding toward zero.
using a custom rounding
public int Round(double value)
{
double decimalpoints = Math.Abs(value - Math.Floor(value));
if (decimalpoints > 0.5)
return (int)Math.Round(value);
else
return (int)Math.Floor(value);
}
Here's the way i had to work it around :
Public Function Round(number As Double, dec As Integer) As Double
Dim decimalPowerOfTen = Math.Pow(10, dec)
If CInt(number * decimalPowerOfTen) = Math.Round(number * decimalPowerOfTen, 2) Then
Return Math.Round(number, 2, MidpointRounding.AwayFromZero)
Else
Return CInt(number * decimalPowerOfTen + 0.5) / 100
End If
End Function
Trying with 1.905 with 2 decimals will give 1.91 as expected but Math.Round(1.905,2,MidpointRounding.AwayFromZero) gives 1.90! Math.Round method is absolutely inconsistent and unusable for most of the basics problems programmers may encounter. I have to check if (int) 1.905 * decimalPowerOfTen = Math.Round(number * decimalPowerOfTen, 2) cause i don not want to round up what should be round down.
This is ugly as all hell, but always produces correct arithmetic rounding.
public double ArithRound(double number,int places){
string numberFormat = "###.";
numberFormat = numberFormat.PadRight(numberFormat.Length + places, '#');
return double.Parse(number.ToString(numberFormat));
}

MATLAB showing 0.82-0.80 not equal to 0.02 and similar error in inverting a matrix [duplicate]

This question already has answers here:
Why is 24.0000 not equal to 24.0000 in MATLAB?
(6 answers)
Closed 7 years ago.
I've written the following code*:
function val = newton_backward_difference_interpolation(x,y,z)
% sample input : newton_backward_difference_interpolation([0.70 0.72 0.74 0.76 0.78 0.80 0.82 0.84 086 0.88],[0.8423 0.8771 0.9131 0.9505 0.9893 1.0296 1.0717 1.1156 1.1616 1.2097],0.71)
% sample output:
% X-Input must be equidistant
% -1.1102e-16
n=numel(x);% number of elements in x (which is also equal to number of elements in y)
h=x(2)-x(1);% the constant difference
%error=1e-5;% the computer error in calculating the differences [It was workaround where I took abs(h-h1)>=error]
if n>=3% if total elements are more than 3, then we check if they are equidistant
for i=3:n
h1=x(i)-x(i-1);
if (h1~=h)
disp('X-Input must be equidistant');
disp(h1-h);
return;
end
end
end
...
I also wrote a function for calculating inverse of a matrix** where this:
a=[3 2 -5;1 -3 2;5 -1 4];disp(a^(-1)-inverse(a));
displays this:
1.0e-16 *
0 -0.2082 0.2776
0 0.5551 0
0 0.2776 0
Why is there a small difference of 1e-16 occuring? Am I right in saying that this is because computer calculations (especially divisions are not exact)? Even if they are inexact, why does a^(-1) provide more accurate/exact solution (Sorry If this question is not programming related in your view.)
Can this be avoided/removed? How?
*for newton backward difference interpolation: (whole code at this place), the expected output is 0.85953 or something near that.
**using Gauss-Jordan Elimination: (whole code at this place)
That's in the nature of floating point calculations. There habe been many questions about this topic here already.
E.g.
Floating point inaccuracy examples
What range of numbers can be represented in a 16-, 32- and 64-bit IEEE-754 systems?
https://www.quora.com/Why-is-0-1+0-2-not-equal-to-0-3-in-most-programming-languages
The problem is that non-integer numbers in most cases have no exact representation by a 64bit double or 32bit float, not even in a 10000bit floating point value if that existed.
0.5, 0.25 and all powers of 2 (also those with negative exponents, 0.5 is 2^-1) can be stored exactly, and many others as well. Floating point numbers are saved as 3 separate parts: sign (1bit), mantissa (the 'number') and exponent for the base 2. Every possible combination of mantissa and exponent will result in a precise value, e.g. 0.5 has mantissa 'value' of 1 and exponent -1. the exact formula is
number = (sign ? -1:1) * 2^(exponent) * 1.(mantissa bits)
from
http://www.cprogramming.com/tutorial/floating_point/understanding_floating_point_representation.html
Try this formula and you'll see for example that you can't create a precise 0.1

replace zero values with previous non-zero values

I need a fast way in Matlab to do something like this (I am dealing with huge vectors, so a normal loop takes forever!):
from a vector like
[0 0 2 3 0 0 0 5 0 0 7 0]
I need to get this:
[NaN NaN 2 3 3 3 3 5 5 5 7 7]
Basically, each zero value is replaced with the value of the previous non-zero one. The first are NaN because there is no previous non-zero element
in the vector.
Try this, not sure about speed though. Got to run so explanation will have to come later if you need it:
interp1(1:nnz(A), A(A ~= 0), cumsum(A ~= 0), 'NearestNeighbor')
Try this (it uses the cummax function, introduced in R2014b):
i1 = x==0;
i2 = cummax((1:numel(x)).*~i1);
x(i1&i2) = x(i2(i3));
x(~i2) = NaN;
Just for reference, here are some similar/identical functions from exchange central and/or SO columns.
nearestpoint ,
try knnimpute function.
Or best of all, a function designed to do exactly your task:
repnan (obviously, first replace your zero values with NaN)
I had a similar problem once, and decided that the most effective way to deal with it is to write a mex file. The c++ loop is extremely trivial. After you'l figure out how to work with mex interface, it will be very easy.

The strange thing in Matlab code [duplicate]

This question already has answers here:
Is this a Matlab bug? Do you have the same issue? [duplicate]
(3 answers)
Closed 9 years ago.
I tried to compile the following code.
x = 0
while x <= 1
x = x+0.02
end
The last value of x that I should get is equal to 1.02 (which make a false condition in while loop)
However, I am very wondered that I always got the last value of x equal to 1 and the while loop is stopped. I don't know what's wrong with my code.
Could anyone please help me find out?
0.02 cannot be represented exactly in a floating point binary number (double), so you'll get some rounding errors. The result is that you don't reach one, but a number which is slighly larget than one.
Try to append disp(x-1) after your code, to see that x is not exactly 1.
This site shows how 0.02 is represented in IEEE754 double precision floating point: http://www.binaryconvert.com/result_double.html?decimal=048046048050
The essential thing here is that it is a little bit larger than 0.02
One way to solve this would be to use an integer loop variable. It's still of type double, but it only has integer values, which don't have rounding issues unless you use very large numbers (>=2^56?)
for n=0:100
x = n/100;
end
Try format long before running you will get this:
x = 0.920000000000000
x = 0.940000000000001
x = 0.960000000000001
x = 0.980000000000001
x = 1.000000000000000
Note the 1 at the very end. 0.02 cannot be represented exactly with floating point arithmetic. So although it looks like 1 when you compare it, it is actually larger so it comes up as false and exists the loop.

Questions about matlab median filter commands

This is a question about Matlab/Octave.
I am seeing some results of the medfilt1(1D Median filter command in matlab) computation by which I am confused.
EDIT:Sorry forgot to mention:I am using Octave for Windows 3.2.4. This is where i see this behavior.
Please see the questions below, and point if I am missing something.
1] I have a 1D data array b=[ 3 5 -8 6 0];
out=medfilt1(b,3);
I expected the output to be [3 3 5 0 0] but it is showing the output as [4 3 5 0 3]
How come? What is wrong here?
FYI-Help says it pads the data at boundaries by 0(zero).
2] How does medfilt2(2D median filter command in matlab) work.
Help says "Each output pixel contains the median value in the m-by-n neighborhood around the corresponding pixel in the input image".
For m=3,n=3, So does it calculate a 3x3 matrix MAT for each of input pixels placed at its center and do median(median(MAT)) to compute its median value in the m-by-n neighbourhood?
Any pointers will help.
thank you. -AD
I was not able to replicate your error with Matlab 7.11.0, but from the information in your question it seems like your version of medfilt1 does not differentiate between an odd or even n.
When finding the median in a vector of even length, one usually take the mean of the two median values,
median([1 3 4 5]) = (3+4)/2 = 3.5
This seems to be what happens in your case. Instead of treating n as odd, and setting the value to be 3, n is treated as even and your first out value is calculated to be
median([0 3 5]) = (3+5)/2 = 4
and so on.. EDIT: This only seems to happen in the endpoints, which suggest that the padding with zeros is not properly working in your Octave code.
For your second question, you are almost right, it calculates a 3x3 matrix in each center, but it does not do median(median(MAT)), but median(MAT(:)). There is a difference!
A = [1 2 3
14 5 33
11 7 13];
median(median(A)) = 11
median(A(:)) = 7