I'm using Matlab R2020b (Mac OS 12.0.1).
When I enter (-8)^(-2/3), it returns:
ans =
-0.1250 - 0.2165i
Shouldn't it be 0.2500, instead?
Raising negative numbers to fractional powers is a complex multi-valued operation. MATLAB is simply picking one of the solutions for you. E.g., for the solutions to (-8)^(1/3). start with the roots to the following polynomial equation:
x^3+8=0
Using MATLAB for this:
>> roots([1 0 0 8])
ans =
-2.0000 + 0.0000i
1.0000 + 1.7321i
1.0000 - 1.7321i
Then raising this result to the -2 power yields:
>> ans.^-2
ans =
0.2500 + 0.0000i
-0.1250 - 0.2165i
-0.1250 + 0.2165i
MATLAB happened to give you the second solution above for the (-8)^(-2/3) calculation.
BOTTOM LINE: Whenever you are dealing with complex multi-valued operations, if you want specific results you will need to account for that in your code, because MATLAB might pick something else.
Depends on the order of calculation.
(-8)^(-2/3) means divide -2 by 3 and then raise -8 to that power.
But if you do ((-8)^(-2))^(1/3) or nthroot((-8)^(-2),3) instead, you'll get 0.25.
I am using Matlab's backslash operator to solve a system of equations written as two matrices M1 and M2. These two matrices are square and tridiagonal, and so I have defined them as sparse. For example, with the dimensions of each being 5x5, they are defined as follows, with the values in each entry being dependent on some constant a:
N = 5;
a = 1e10;
M1 = spdiags([-a*ones(N,1)... % Sub diagonal
(1 + 2*a)*ones(N,1)... % Main Diagonal
-a*ones(N,1)],... % Super diagonal
-1:1,N,N);
M2 = spdiags([+a*ones(N,1)...
(1 - 2*a)*ones(N,1)...
+a*ones(N,1)],...
-1:1,N,N);
M_out = M1\M2;
So for example, M1 looks like the following in full form:
>> full(M1)
ans =
1.0e+10 *
2.0000 -1.0000 0 0 0
-1.0000 2.0000 -1.0000 0 0
0 -1.0000 2.0000 -1.0000 0
0 0 -1.0000 2.0000 -1.0000
0 0 0 -1.0000 2.0000
Now, if I examine the number of non-zero entries in the result M_out, then I can see they are all non-zero, which is fine:
>> nnz(M_out)
ans =
25
The problem is that I also need to do this for larger values of the constant a. However, if, for example, a=1e16 instead, then the off-diagonal entries of M_out are automatically set to zero, presumably because they have become too small:
>> nnz(M_out)
ans =
5
Is there a better way in Matlab of going about this problem of inverting sparse matrices? Or am I using the backslash operator in the wrong way?
If the size of your matrices doesn't grow too much, I recommend doing a full symbolic computation:
N = 5;
syms a
M1 = diag(-a*ones(N-1,1),-1) + diag((1 + 2*a)*ones(N,1),0) + diag(-a*ones(N-1,1),+1);
M2 = diag(+a*ones(N-1,1),-1) + diag((1 - 2*a)*ones(N,1),0) + diag(+a*ones(N-1,1),+1);
M_out = M1\M2;
M_num_1e10 = subs(M_out,a,1e10);
M_num_1e16 = subs(M_out,a,1e16);
vpa(M_num_1e10)
vpa(M_num_1e16)
In that case, you will need the Symbolic Math Toolbox. If you don't have it, I think you should considerer migrating to Python and work with SymPy.
EDIT:
Considering the way you defined your problem, you need extended precision for your computations. The double precision isn't enough. For example, in double precision (1e16+1) has to be rounded to (1e16), in other words (1e16+1)-(1e16) is equal to zero. So your problem starts in the main diagonal of your matrices. MATLAB only provides extended precision through its symbolic toolbox.
If you want to stick with double precision, you may extend the double precision yourself relying on the so called double-double arithmetic. I say that you will have to do it by yourself because I don't think there is a open source double-double library for MATLAB.
I need to exclude some error data from matrix. I know what data is correct and i am trying to interpolate values between so I can get decent diagrams with not so big errors. I must use that form of matrix and I must preserve its shape. I must only substitute some data that is marked as errors. I will show you my work so far:
M=[0.1000
0.6000
0.7000
0.8000
0.9000
0.9500
1.0000
1.0500
1.1000
1.1500
1.2000
1.2500
1.3000
1.5000
1.7500
2.0000
2.2500
2.5000
3.0000];
CZ1=[ 9.4290
9.5000
9.3250
9.2700
9.2950
9.4350
9.6840
10.0690
10.1840
10.2220
10.2160
9.6160
9.6890
9.4880
9.5000
9.5340
9.3370
9.0990
8.5950];
N1=11;
Nn=13;
Mx1=M(N1);
Mx2=M(Nn);
Mx=[Mx1 Mx2]';
CN1=CZ1(N1);
CN2=CZ1(Nn);
CNy=[C1 C2]';
y1=interp1q(Mx,CNy,M(N1:Nn));
CNf=CZ1;
NEWRangeC=y1;
Cfa=changem(CZ1,[NEWRangeC], [CNf(N1:Nn)]);
figure
plot(M,Cf,'-*b',M,Cfa,'r')
So far as you can see I used points 11 and 13 and i excluded point 12 interpolating that point from 11 to 13. This is working but i want to make a modification.
My question is: How can I select values that are errors and remove them but interpolate space between their neighbors. I want to use a M matrix values as my reference (not points as my example).
Assuming you know which elements are incorrect, you can use Matlab's interp1 function to interpolate them (this will only work if the M matrix is actually a vector`:
error_indices = [11 13];
all_indices = 1:length(M)
% Get the indices where we have valid data
all_correct_indices = setdiff(all_indices, error_indices)
% the first two arguments are the available data.
% the third arguments is what indices you are looking for
M_new = interp1(all_correct_indices, M(all_correct_indices), all_indices)
The above interpolates values at all_indices -- including the missing elements. Where you already have valid data (all_correct_indices), Matlab will return that data. In other places, it will interpolate using the two nearest neighbors.
Try help interp1 for more information on how this function works.
Update - an example
x = 1:10; % all indices
y = x*10;
e = 3:7; % the unknown indices
s = setdiff(x, e); % the known indices
y_est = interp1(s, y(s), x)
ans =
10 20 30 40 50 60 70 80 90 100
And we see that interp1 had interpolated all values from 30 to 70 linearly using the available data (specifically the adjacent points 20 and 80).
Well, you can start out by finding the elements that are errors, with the find command (this will return the indices). This should also work for matrices.
You can then grab the elements around each of the indices, and interpolate between, as you did.
I am developing an image processing application for object detection.
At some point I am using log of the generalized eigenvalues vector of two square covariance matrices.
Assume that I have a 9x9 covariance matrix a.
a = rand(9, 9)%just generating random matrix for testing problem easily
b = eig(a, a)%generalized eigenvalues vector containing nine values equal to 1
%so we have b = [1.000, 1.000, 1.000 ... (9 times)]
c = log(b(:)) %we know b contains values of 1. and log(1) is 0.
Even though we know and can debug to see that b contains elements with value 1 and log(1) is 0, content of c is:
1.0e-014 *
0.0222
0.1110
0.0222
0.0222
-0.0777
0
0.0222
0.0888
0
This in my case.
Anyone knows why doesn't c have values of 0?
Thanks.
As #OliCharlesworth commented the values of b aren't really 1. I did the exact same as you did and got the following for b:
b =
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
1.0000
But when I opened b up in the variable explorer I got the following:
You'll see that there's only really one value of 1 and not 1.000 meaning that there are some trailing values that aren't shown in MatLab. Hence you would get the following for c:
c =
1.0e-15 *
0.2220
-0.4441
0.2220
-0.2220
0.2220
0
0.2220
-0.1110
-0.1110
Notice the 1.0e-15 that's where trailing values are being found.
Trailing zeros after a number, like
1.0000
indicates, that it is not exactly this value.
Try
format long
to see trailing digits up to 15.
If this isn't exactly enough, try out the print command
sprintf('%.50f',b(1))
to see 50 trailing digits of the value b(1).
Thus, the numbers are not exactly 1, neither log becomes exactly 0.
In Matlab, there is this unique command that returns thew unique rows in an array. This is a very handy command.
But the problem is that I can't assign tolerance to it-- in double precision, we always have to compare two elements within a precision. Is there a built-in command that returns unique elements, within a certain tolerance?
With R2015a, this question finally has a simple answer (see my other answer to this question for details). For releases prior to R2015a, there is such a built-in (undocumented) function: _mergesimpts. A safe guess at the composition of the name is "merge similar points".
The function is called with the following syntax:
xMerged = builtin('_mergesimpts',x,tol,[type])
The data array x is N-by-D, where N is the number of points, and D is the number of dimensions. The tolerances for each dimension are specified by a D-element row vector, tol. The optional input argument type is a string ('first' (default) or 'average') indicating how to merge similar elements.
The output xMerged will be M-by-D, where M<=N. It is sorted.
Examples, 1D data:
>> x = [1; 1.1; 1.05]; % elements need not be sorted
>> builtin('_mergesimpts',x,eps) % but the output is sorted
ans =
1.0000
1.0500
1.1000
Merge types:
>> builtin('_mergesimpts',x,0.1,'first')
ans =
1.0000 % first of [1, 1.05] since abs(1 - 1.05) < 0.1
1.1000
>> builtin('_mergesimpts',x,0.1,'average')
ans =
1.0250 % average of [1, 1.05]
1.1000
>> builtin('_mergesimpts',x,0.2,'average')
ans =
1.0500 % average of [1, 1.1, 1.05]
Examples, 2D data:
>> x = [1 2; 1.06 2; 1.1 2; 1.1 2.03]
x =
1.0000 2.0000
1.0600 2.0000
1.1000 2.0000
1.1000 2.0300
All 2D points unique to machine precision:
>> xMerged = builtin('_mergesimpts',x,[eps eps],'first')
xMerged =
1.0000 2.0000
1.0600 2.0000
1.1000 2.0000
1.1000 2.0300
Merge based on second dimension tolerance:
>> xMerged = builtin('_mergesimpts',x,[eps 0.1],'first')
xMerged =
1.0000 2.0000
1.0600 2.0000
1.1000 2.0000 % first of rows 3 and 4
>> xMerged = builtin('_mergesimpts',x,[eps 0.1],'average')
xMerged =
1.0000 2.0000
1.0600 2.0000
1.1000 2.0150 % average of rows 3 and 4
Merge based on first dimension tolerance:
>> xMerged = builtin('_mergesimpts',x,[0.2 eps],'average')
xMerged =
1.0533 2.0000 % average of rows 1 to 3
1.1000 2.0300
>> xMerged = builtin('_mergesimpts',x,[0.05 eps],'average')
xMerged =
1.0000 2.0000
1.0800 2.0000 % average of rows 2 and 3
1.1000 2.0300 % row 4 not merged because of second dimension
Merge based on both dimensions:
>> xMerged = builtin('_mergesimpts',x,[0.05 .1],'average')
xMerged =
1.0000 2.0000
1.0867 2.0100 % average of rows 2 to 4
This is a difficult problem. I'd even claim it to be impossible to solve in general, because of what I'd call the transitivity problem. Suppose that we have three elements in a set, {A,B,C}. I'll define a simple function isSimilarTo, such that isSimilarTo(A,B) will return a true result if the two inputs are within a specified tolerance of each other. (Note that everything I will say here is meaningful in one dimension as well as in multiple dimensions.) So if two numbers are known to be "similar" to each other, then we will choose to group them together.
So suppose we have values {A,B,C} such that isSimilarTo(A,B) is true, and that isSimilarTo(B,C) is also true. Should we decide to group all three together, even though isSimilarTo(A,C) is false?
Worse, move to two dimensions. Start with k points equally spaced around the perimeter of a circle. Assume the tolerance is chosen such that any point is within the specified tolerance of its immediate neighbors, but not to any other point. How would you choose to resolve which points are "unique" in the setting?
I'll claim that this problem of intransitivity makes the grouping problem not possible to resolve, at least not perfectly, and certainly not in any efficient manner. Perhaps one might try an approach based on a k-means style of aggregation. But this will be quite inefficient, as well, such an approach generally needs to know in advance the number of groups to look for.
Having said that, I would still offer a compromise, something that can sometimes work within limits. The trick is found in Consolidator, as found on the Matlab Central file exchange. My approach was to effectively round the inputs to within the specified tolerance. Having done that, a combination of unique and accumarray allows the aggregation to be done efficiently, even for large sets of data in one or many dimensions.
This is a reasonable approach when the tolerance is large enough that when multiple pieces of data belong together, they will be rounded to the same value, with occasional errors made by the rounding step.
As of R2015a, there is finally a function to do this, uniquetol (before R2015a, see my other answer):
uniquetol Set unique within a tolerance.
uniquetol is similar to unique. Whereas unique performs exact comparisons, uniquetol performs comparisons using a tolerance.
The syntax is straightforward:
C = uniquetol(A,TOL) returns the unique values in A using tolerance TOL.
As are the semantics:
Each value of C is within tolerance of one value of A, but no two elements in C are within tolerance of each other. C is sorted in ascending order. Two values u and v are within tolerance if:
abs(u-v) <= TOL*max(A(:),[],1)
It can also operate "ByRows", and the tolerance can be scaled by an input "DataScale" rather than by the maximum value in the input data.
But there is an important note about uniqueness of the solutions:
There can be multiple valid C outputs that satisfy the condition, "no two elements in C are within tolerance of each other." For example, swapping columns in A can result in a different solution being returned, because the input is sorted lexicographically by the columns. Another result is that uniquetol(-A,TOL) may not give the same results as -uniquetol(A,TOL).
There is also a new function ismembertol is related to ismember in the same way as above.
There is no such function that I know of. One tricky aspect is that if your tolerance is, say, 1e-10, and you have a vector with values that are equally spaced at 9e-11, the first and the third entry are not the same, but the first is the same as the second, and the second is the same as the third - so how many "uniques" are there?
One way to solve the problem is that you round your values to a desired precision, and then run unique on that. You can do that using round2 (http://www.mathworks.com/matlabcentral/fileexchange/4261-round2), or using the following simple way:
r = rand(100,1); % some random data
roundedData = round(r*1e6)/1e6; % round to 1e-6
uniqueValues = unique(roundedData);
You could also do it using the hist command, as long as the precision is not too high:
r = rand(100,1); % create 100 random values between 0 and 1
grid = 0:0.001:1; % creates a vector of uniquely spaced values
counts = hist(r,grid); % now you know for each element in 'grid' how many values there are
uniqueValues = grid(counts>0); % and these are the uniques
I've come across this problem before. The trick is to first sort the data and then use the diff function to find the difference between each item. Then compare when that difference is less then your tolerance.
This is the code that I use:
tol = 0.001
[Y I] = sort(items(:));
uni_mask = diff([0; Y]) > tol;
%if you just want the unique items:
uni_items = Y(uni_mask); %in sorted order
uni_items = items(I(uni_mask)); % in the original order
This doesn't take care of "drifting" ... so something like 0:0.00001:100 would actually return one unique value.
If you want something that can handle "drifting" then I would use histc but you need to make some sort of rough guess as to how many items you're willing to have.
NUM = round(numel(items) / 10); % a rough guess
bins = linspace(min(items), max(items), NUM);
counts = histc(items, bins);
unit_items = bins(counts > 0);
BTW: I wrote this in a text-editor away from matlab so there may be some stupid typos or off by one errors.
Hope that helps
This is hard to define well, assume you have a tolerance of 1.
Then what would be the outcome of [1; 2; 3; 4]?
When you have multiple columns a definition could become even more challenging.
However, if you are mostly worried about rounding issues, you can solve most of it by one of these two approaches:
Round all numbers (considering your tolerance), and then use unique
Start with the top row as your unique set, use ismemberf to determine whether each new row is unique and if so, add it to your unique set.
The first approach has the weakness that 0.499999999 and 0.500000000 may not be seen as duplicates. Whilst the second approach has the weakness that the order of your input matters.
I was stuck the other day with a MatLab 2010, so, no round(X,n), no _mergesimpts (At least I couldn't get it to work) so, a simple solution that works (at least for my data):
Using rat default tolerance:
unique(cellstr(rat(x)))
Other tolerance:
unique(cellstr(rat(x,tol)))