I have :
A =
1 2 3
2 4 5
5 5 5
and
[U S V]=svd(A)
How can I remove the dimension of A matrix from SVD function?
I'm assuming you want to get a reduced version of the matrix A.
This is done by using PCA, search it. For example, if you want the reduced matrix A to have K dimensions:
[m, ~] = size(A);
Sigma = 1.0/m .* A' * A;
[U, S, ~] = svd(Sigma);
newA = zeros(size(A, 1), K);
for i = 1:size(A, 1),
for j = 1:K,
x = A(i, :)';
projection_k = x' * U(:, j);
newA(i, j) = projection_k;
end
end
end
So the matrix newA will be a reduced version of A with K dimensions.
It's better for you to search about PCA.
Related
In this case,this is the array which serves as coefficients and degrees which first value having no degree.
double[] arr = { 12, 2, 3 ,4};
I then made a method to print the above array in terms of polynomial equation.
It gives output in type string as follows :
2x^2 + 3x^3 + 4x^4 + 12
I want to a function which takes an argument x and then solve the above polynomial with respect to value of x.
How can I do that?
Any kind of help will be appreciated!.
Edit: Question Solved
To evaluate it you can simply sum the power values times the coefficients. Using LINQ, that's one line:
double result = arr.Select((c,i) => c * Math.Pow(x, i)).Sum();
Here i is the index into your array, it starts at zero, so x^0 = 1 * 12 == 12 etc.
You can also do it without LINQ like this:
List<string> debug = new List<string>();
double y = 1.0;
result = 0.0;
for (int i = 0; i < arr.Length; i++)
{
debug.Add($"{arr[i]} * x^{i}");
result = result + arr[i] * y;
y = y * x;
}
Console.WriteLine(string.Join(" + ", debug));
Console.WriteLine(result);
Which, for x=3 outputs:
12 * x^0 + 2 * x^1 + 3 * x^2 + 4 * x^3
153
Same result as LINQ.
This is what I created:
for (int i = 1; i < degree.Length; i++)
{
result_first += degree[i] * Math.Pow(x, degree[i]);
}
result_first += degree[0];
It works perfectly.
I'm looking for a way to calculate the the start and end index for of each sub array when dividing a larger array into n pieces.
For example, let's say I have an array of length 421 and I want to divide it up into 5 (relatively) equal parts. Then beginning and ending indices of the five sub arrays would be something like this: [0, 83], [84, 167], [168, 251], [252, 335], [336, 420]. Note that this isn't a homework question. Just worded the problem in more general terms.
Let's say we have n elements in the array. We want to divide it into k parts. Then if n%k == 0 it's easy enough - every subarray will contain n/k elements. If n%k != 0 then we must uniformly distribute n%k among some subarrays, for example the first ones.
To find a start and end index(inclusive) of each consecutive subarray do as follows:
Calculate n % k as remainder to keep track of whether a subarray should be 1 position longer or not.
Introduce 2 variables for keeping start and end positions left and right. For the first subarray, left = 0.
Calculate right as left + n/k + remainder > 0 : 1 : 0. Store or print left and right.
Update left to a new position left = right + 1. Decrement remainder as it has just been used.
Repeat steps 3 and 4 until all k intervals are created.
Now let's see some sample code:
public static void main(String[] args) {
int n = 421;
int k = 5;
int length = n / k;
int remaining = n % k;
int left = 0;
for (int i = 0; i < k; i++) {
int right = left + (length - 1) + (remaining > 0 ? 1 : 0);
System.out.println("[" + left + "," + right + "]");
remaining--;
left = right + 1;
}
}
Output
[0,84]
[85,168]
[169,252]
[253,336]
[337,420]
The required integer math makes it a bit tricky. Integer division always truncates but you need to round so the error is distributed evenly. Integer rounding X / Y is done by adding half of Y, so (X + Y/2) / Y. The last interval is special, it needs to end at exactly the array length with no regard for rounding.
Encoding this approach in a method:
public static int[] Partition(Array arr, int divisions) {
if (arr.Length < divisions || divisions < 1) throw new ArgumentException();
var parts = new int[divisions + 1];
for (int ix = 0; ix < divisions; ++ix) {
parts[ix] = (ix * arr.Length + divisions / 2) / divisions;
}
parts[divisions] = arr.Length;
return parts;
}
Test it like:
static void Main(string[] args) {
var arr = new int[421];
var parts = Partition(arr, 1);
for (int ix = 0; ix < parts.Length-1; ++ix) {
Console.WriteLine("{0,3}..{1,-3}", parts[ix], parts[ix + 1]);
}
Console.ReadLine();
}
Get confident that it works well by checking the edge cases, like Partition(new int[6], 5). In which case you want one division that is 2 long and the rest is 1. That works, try some other ones.
I like to think of it this way:
If you want to divide M elements into N parts, then all together the first x parts should should have Math.round(x*M/N) elements.
If you want to find the start and end of segment x, then, you can calculate those directly, because it starts after the first Math.round((x-1)*M/N) elements and includes up to the Math.round(x *M/N)th element.
Note that I'm not providing formulas for the actual indexes because there are a lot of ways to represent those -- 0 or 1-based, inclusive or exclusive ranges -- and it can be confusing to try to remember the right formulas for different schemes. Figure it out in terms of the number of elements before the start and to the end, which always applies.
P.S. You can do that rounding multiplication and division in integer arithmetic like this: Math.round(x*M / N) = (x * M + (N/2)) / N
You can create a formula for both start and end indexes for any sub array.
let say x is a size of sub array, then start index of nth array will be (n-1)*x and end index will be (n*x-1)
int arrLength = 424; // your input
int sections = 5;// your input
int minSize = arrLength / sections; // minimum size of array
int reminder = arrLength % sections; // we need to distribute the reminder to sub arrays
int maxSize = minSize + 1; // maximum size of array
int subArrIndex = 1;
// lets print sub arrays with maximum size which will be equal to reminders
while (reminder > 0 && subArrIndex <= sections )
{
Console.WriteLine(string.Format("SubArray #{0}, Start - {1}, End - {2}", subArrIndex, ((subArrIndex-1)*maxSize), (subArrIndex*maxSize-1)));
reminder--;
subArrIndex++;
}
// lets print remaining arrays
while (subArrIndex <= sections)
{
Console.WriteLine(string.Format("SubArray #{0}, Start - {1}, End - {2}", subArrIndex, ((subArrIndex - 1) * minSize), (subArrIndex * minSize - 1)));
subArrIndex++;
}
Output :
SubArray #1, Start - 0, End - 84
SubArray #2, Start - 85, End - 169
SubArray #3, Start - 170, End - 254
SubArray #4, Start - 255, End - 339
SubArray #5, Start - 336, End - 419
I am trying to implement this without success and I have to do this without using external modules numpy, etc. There are 3 modules in the app I am coding this, Python and C#, C++ but no other fancy libraries other than standard ones.
On a separate application, I used numpy's svd and it works very accurately. So I am using it to match my results. My method is PCA and everything is good up to this point. But after I calculate my symmetric covariance matrix, I don't know how to find the largest eigenvector.
The data set is always 3d points, x, y and z.
vector center;
for(point p in points):
center += p;
center /= points.count;
sumxx = 0;
sumxy = 0;
sumxz = 0;
sumyy = 0;
sumyz = 0;
sumzz = 0;
for(point p in points):
vector s = p - center;
sumxx += s.x * s.x;
sumxy += s.x * s.y;
sumxz += s.x * s.z;
sumyy += s.y * s.y;
sumyz += s.y * s.z;
sumzz += s.z * s.z;
matrix3 mat = invert(matrix3(sumxx, sumxy, sumxz, sumxy, sumyy, sumyz, sumxz, sumyz, sumzz));
vector n;
if (determinant(mat) > 0)
normal = find_largest_eigenvalue
Let us recap what you are asking, to clarify :
Find an eigenvector of a matrix mat
This eigenvector should be associated with the largest eigenvalue of the matrix
The matrix is the symmetric covariance matrix of a principal component analysis. In particular, it is symmetric.
Your matrix is square of size 3 by 3, as shown in your code by matrix3 mat = ... and confirmed in a (now deleted) comment.
Under these very specific circumstances, the following answer applies. However tmyklebu warns against numerical instability of this approach for some pathological matrices, typically when r is close to -1.
Alright, lets start with a bit of reading from wikipedia's page on Characteristic polynomials
In linear algebra, the characteristic polynomial of a square matrix is a polynomial, which is invariant under matrix similarity and has the eigenvalues as roots.
blah blah blah, let's skip directly to the 3x3 matrix section in the page on Eigenvalue algorithms.
If A is a 3×3 matrix, then its characteristic equation can be expressed as:
Followed a few lines later by (more or less) this pseudo-code, for symmetric matrices (which you say you have, if I'm not mistaken -- otherwise you might have complex eigenvalues) :
p1 = A(1,2)^2 + A(1,3)^2 + A(2,3)^2
if (p1 == 0)
% A is diagonal.
eig1 = A(1,1)
eig2 = A(2,2)
eig3 = A(3,3)
else
q = (A(1,1) + A(2,2) + A(3,3)) / 3
p2 = (A(1,1) - q)^2 + (A(2,2) - q)^2 + (A(3,3) - q)^2 + 2 * p1
p = sqrt(p2 / 6)
B = (1 / p) * (A - q * I) % I is the identity matrix
r = determinant(B) / 2
% In exact arithmetic for a symmetric matrix -1 <= r <= 1
% but computation error can leave it slightly outside this range.
if (r <= -1)
phi = pi / 3
elseif (r >= 1)
phi = 0
else
phi = acos(r) / 3
end
% the eigenvalues satisfy eig3 <= eig2 <= eig1
eig1 = q + 2 * p * cos(phi)
eig3 = q + 2 * p * cos(phi + (2*pi/3))
eig2 = 3 * q - eig1 - eig3 % since trace(A) = eig1 + eig2 + eig3
end
So you want max(eig1,eig2,eig3) in the first case, eig1 in the second case. Let us call e this largest eigenvalue.
For the eigenvector, you can now just solve (A-e*I)x=0
There are different algorithms for finding eigenvalues. Some work from smallest to largest, like QR; others work from largest to smallest, like power iteration or Jacobi-Davidson.
Maybe a switch of algorithm is what you want. Try power method and see if that helps.
https://scicomp.stackexchange.com/questions/1681/what-is-the-fastest-way-to-calculate-the-largest-eigenvalue-of-a-general-matrix
Problem: Topcoder SRM 170 500
Consider a sequence {x0, x1, x2, ...}. A relation that defines some term xn in terms of previous terms is called a recurrence relation. A linear recurrence relation is one where the recurrence is of the form xn = c(k-1) * x(n-1) + c(k-2) * x(n-2) + ... + c(0) * x(n-k)
where all the c(i) are real-valued constants, k is the length of the recurrence relation, and n is an arbitrary positive integer which is greater than or equal to k.
You will be given a int[] coefficients, indicating, in order, c(0), c(1), ..., c(k-1). You will also be given a int[] initial, giving the values of x(0), x(1), ..., x(k-1), and an int N. Your method should return xN modulo 10.
More specifically, if coefficients is of size k, then the recurrence relation will be
xn = coefficients[k - 1] * xn-1 + coefficients[k - 2] * xn-2 + ... + coefficients[0] * xn-k.
For example, if coefficients = {2,1}, initial = {9,7}, and N = 6, then our recurrence relation is xn = xn-1 + 2 * xn-2 and we have x0 = 9 and x1 = 7. Then x2 = x1 + 2 * x0 = 7 + 2 * 9 = 25, and similarly, x3 = 39, x4 = 89, x5 = 167, and x6 = 345, so your method would return (345 modulo 10) = 5.
Constraints:
- Code must run in less than or equal to 2 seconds
- Memory utilization must not exceed 64 MB
My attempted Solution:
class RecurrenceRelation
{
public int moduloTen(int[] coefficients, int[] initial, int N)
{
double xn = 0; int j = 0;
int K = coefficients.Length;
List<double> xs = new List<double>(Array.ConvertAll<int, double>(initial,
delegate(int i)
{
return (double)i;
}));
if (N < K)
return negativePositiveMod(xs[N]);
while (xs.Count <= N)
{
for (int i = xs.Count - 1; i >= j; i--)
{
xn += xs[i] * coefficients[K--];
}
K = coefficients.Length;
xs.Add(xn);
xn = 0;
j++;
}
return negativePositiveMod(xs[N]);
}
public int negativePositiveMod(double b)
{
while (b < 0)
{
b += 10;
}
return (int)(b % 10);
}
}
My problem with this solution is the precision of the double representation, and since I can't use a third party library or the BigInteger library in .NET for this SRM, i need to find a way of solving it without them. I suspect I could use recursion but I'm a little clueless on how to go about that.
Here is a test case that shows when my code works and when it doesn't
{2,1}, {9,7}, 6 - Successfully returns 5
{9,8,7,6,5,4,3,2,1,0}, {1,2,3,4,5,6,7,8,9,10}, 654 - Unsuccessfully returns 8 instead of 5 due to precision of double type
Can anyone help me figure this out? I was going to consider using arrays to store the values but it is a little bit beyond me especially on how to cater for multiplication and still be within the time and space complexity set out in the problem. Perhaps my entire approach is wrong? I'd appreciate some pointers and direction (not fully fleshed out answers) answers please.
Thanks
Notice that we only need to return the modulo 10 of xn.
We also need to know that if a = b + c, we have a % 10 = (b % 10 + c % 10) %10.
And a = b*c, so we also have a % 10 = (b %10 * c % 10) % 10;
So, for
xn = c(k-1) * x(n-1) + c(k-2) * x(n-2) + ... + c(0) * x(n-k)
= a0 + a1 + .... + an
(with a0 = c(k - 1)*x(n-1), a1 = ...)
we have xn % 10 = (a0 % 10 + a1 % 10 + ...)%10
And for each ai = ci*xi, so ai % 10 = (ci % 10 * xi % 10)% 10.
So by doing all of these math calculations, we can avoid to use double and keep the result in manageable size.
As Pham has answered, the trick is to realize that you only need to return a modulo, thereby bypassing the problem of overflow. Here is my quick attempt. I use a queue to put in the last result xN, and evict the oldest one.
static int solve(int[] coefficients, int[] seed, int n)
{
int k = coefficients.Count();
var queue = new Queue<int>(seed.Reverse().Take(k).Reverse());
for (int i = k; i <= n; i++)
{
var xn = coefficients.Zip(queue, (x, y) => x * y % 10).Sum() % 10;
queue.Enqueue(xn);
queue.Dequeue();
}
return (int) (queue.Last() );
}
Edit:
Getting the same results as you expect, however I don't guarantee that there is no bug in this example.
Assume we have a triangle that each node has K children.
An example for K = 2 is:
1
2 3
4 5 6
An example for K = 3 is:
1
2 3 4
5 6 7 8 9
An example for K = 4 is:
1
2 3 4 5
5 6 7 8 9 1 2
etc.
I would like to store those triangles in an array. I am looking to retrieve the total height of the triangle (assuming they are complete triangles) given the total number of elements T and the number of children per node K
I am also looking to find what is the offset for each element in an array to each children. I know that for the example above where K = 2 the array is [1, 2, 3, 4, 5, 6] where for each level L the offset is L * (L + 1) / 2 (because Level 1 has 1 element, Level 2 has 2, Level 3 has 3 ...)
EDIT: The example is correct. Each node has access to K child nodes. for K = 3 1 has access to 2 3 and 4. 2 has access to 5 6 and 7. 3 has access to 6 7 and 8.
These are triangles and not graphs or trees.
Now that you have clarified your requirement ...
For K=2 there are
1
1+1
1+1+1
...
elements in each level, this is the series 1,2,3,.... If n is the level number then there are n elements at each level. Note that this can also be written as 1+1(n-1)
For K=3 there are
1
1+2
1+2+2
...
elements in each level, this is the series 1,3,5,...; there are 1+2(n-1) elements at each level.
For K=4 there are
1
1+3
1+3+3
...
elements in each level, this is the series 1,4,7,.... There are 1+3(n-1) elements at each level.
At each level in each triangle there are 1+(K-1)(n-1) elements. I expect you can carry on from here.
The total number of elements T for a triangle of height h will be:
T = ∑1...h (1 + (K-1)(n-1))
T = h + (K-1) * ∑1...h (n-1)
T = h + (K-1) * ∑0..h-1 (n)
T = h + (K-1) * ((h-1)² + h-1) / 2
T = h + (K-1) * (h² + 1 - 2h + h-1) / 2
T = h + (K-1) * (h² - h) / 2
Calculating the height
So to get the height h you insert the value of K and solve the equation. Here's an example of an easy case where K equals 3.
T = h + (K-1) * (h² - h) / 2
T = h + (3-1) * (h² - h) / 2
T = h + (h² - h)
T = h²
h = √T
Calculating the offsets
As for the offsets you use the same equation we used to calculate the total number of elements but set h to height-1. Here's an example of getting the offset for row 3 in a triangle with a K of 4.
offset(h) = h-1 + (K-1) * ((h-1)² - (h-1)) / 2
offset(3) = 3-1 + (4-1) * ((3-1)² - (3-1)) / 2
offset(3) = 2 + 3 * (4 - 2) / 2
offset(3) = 5