Octave Matrix of discretized Legendre polynomials - matrix

I need to get N x columns(L) matrix of legendre polynomials evaluated over L for arbitrary N.
Is there a better way of computing the matrix than just explicitly evaluating the polynomial vector for each row? The code snippet for this approach (N = 4) is here:
L = linspace(-1,1,800);
# How to do this in a better way?
G = [legendre_Pl(0,L); legendre_Pl(1,L); legendre_Pl(2,L); legendre_Pl(3,L)];
Thanks,
Vojta

Create an anonymous function. Documentation at http://www.gnu.org/software/octave/doc/interpreter/Anonymous-Functions.html
f = #(x) legendre_Pl(x,L);
Then use arrayfun to apply the function, f to an array [1:N] Documentation at http://www.gnu.org/software/octave/doc/interpreter/Function-Application.html
CellArray = arrayfun(f, [1:N], "UniformOutput", false);
That gives you a cell array. If you want the answer in a matrix, use cell2mat
G = cell2mat(CellArray);

Related

Quaternion(Hurwitz Integers) gcrd algorithm

I want a ref or pseudo-algorithm or an actual algorithm for Quaternion GCD, I need this to find out the 4 squares that make up any given integer $n$, I did all the other work but I am stuck on this since there is no information on Wikipedia or Arxiv on how to do such GCD.
Thanks.
I tried to Extend the Complex(Gaussian Integers) gcd but with no success.
The key for these things is the Euclidean algorithm:
def euclidean_rightdiv_hurwitz(B,D):
#if B is not D, returns q,r such that
#B = qD + r
#r==0 or norm(r)< norm(D)
nor = norm(D)
for a,b,c,d in [-sqrt(nor), sqrt(nor)+1]:
r = quaternion(a,b,c,d)
if r==0 or norm(r)< nor:
diff = (B-r)
if hurwitz_is_rightdivisible(diff,D):
return diff/D, r
To implement hurwitz_is_rightdivisible, notice that if diff is rightdivisible by D it must be the case that diff*inv(D) is an integer, so just compute it and check each coordinate.

Numeric and symbolic gradients don't match although Hessians do

For context, I have a small project in MATLAB where I try to replicate an algorithm involving some optimisation with the Newton algorithm. Although my issue is mainly with MATLAB, maybe it's my lacking profound background knowledge what's keeping me from finding a solution, so feel free to redirect me to the appropriate StackExchange site if needed.
The function I need to calculate the gradient vector and Hessian matrix for the optimization is :
function [zi] = Zi(lambda,j)
zi = m(j)*exp(-(lambda*v_tilde(j,:).'));
end
function [z] = Z(lambda)
res = arrayfun(#(x) Zi(lambda,x),1:length(omega));
z = sum(res);
end
function [f] = F(lambda)
f = log(Z(lambda));
end
where omega and v_tilde are Matrices of n d-Dimensional vectors and lambda is the d-Dimensional argument to the function. (right now, m(j) are just selectors (1 or 0), but the algorithm allows to refine these, so they shouldn't be removed.
I use the Derivest Suite to calculate the gradient and Hessian numerically, and, although logically slow for high dimensions, the algorithm as a whole works.
I implemented the same solution using the sym package, so that I could compute the gradient and Hessian in advance for some fix n and d, so they can then be evaluated quickly when needed. This would be the symbolic version:
V_TILDE = sym('v_tilde',[d,n])
syms n k
lambda = sym('lambda',[d,1]);
F = log(M*exp(-(transpose(V_TILDE)*lambda)));
matlabFunction( grad_F, 'File', sprintf('Grad_%d_dim_%d_n.m',d,n_max), 'vars',{a,lambda,V_TILDE});
matlabFunction( hesse_F, 'File', sprintf('Hesse_%d_dim_%d_n.m',d,n_max), 'vars',{a,lambda,V_TILDE});
As n is fix, there is no need to iterate over omega. The gradient and Hessian of this can be obtained through the corresponding functions of sym and then stored as matlabFunctions.
However, when I test both implementations against some values, they don't match, surprisingly though, the values of the hessian matrix match while the values of the gradient don't (the numerical calculation being correct), and the Newton algorithm iterates until the values are just NaN. These are some example values for d=2 and n=8:
Omega:
12.6987 91.3376
95.7507 96.4889
15.7613 97.0593
95.7167 48.5376
70.6046 3.1833
27.6923 4.6171
9.7132 82.3458
95.0222 3.4446
v:
61.2324
52.2271
gNum = HNum = 1.0e+03 *
8.3624 1.4066 -0.5653
-1.1496 -0.5653 1.6826
gSym = HSym = 1.0e+03 *
-52.8700 1.4066 -0.5653
-53.3768 -0.5653 1.6826
As you can see, the values of HNum and HSym match, but the gradients don't.
I'm happy to give any more context information, code snippets, or anything that helps. Thank you in advance!
Edit: As requested, here is a minimal test. The problem is basically that the values of gNum and gSym don't match (longer explanation above):
omega = [[12.6987, 91.3376];[95.7507, 96.4889];[15.7613, 97.0593];
[95.7167, 48.5376];[70.6046, 3.1833];[27.6923, 4.6171];[9.7132, 82.3458];
[95.0222, 3.4446]];
v = [61.2324;52.2271];
gradStr = sprintf('Grad_%d_dim_%d_n',length(omega(1,:)),length(omega));
hesseStr = sprintf('Hesse_%d_dim_%d_n',length(omega(1,:)),length(omega));
g = str2func(gradStr);
H = str2func(hesseStr);
selector = ones(1,length(omega)); %this will change, when n_max>n
vtilde = zeros(length(omega),length(omega(1,:)));
for i = 1:length(omega)
vtilde(i,:) = omega(i,:)-v;
end
lambda = zeros(1,length(omega(1,:))); % start of the optimization
[gNum,~,~] = gradest(#F,lambda)
[HNum,~] = hessian(#F,lambda)
gSym = g(selector,lambda.',omega.')
HSym = H(selector,lambda.',omega.')
Note: The DerivestSuite is a small library (~6 source files) that can be obtained under https://de.mathworks.com/matlabcentral/fileexchange/13490-adaptive-robust-numerical-differentiation

vectorization of a single loop in matlab (multiplication and then addition)

I have a nX2 matrix A and a 3D matrix K. I would like to take element-wise multiplication specifying 2 indices in 3rd dimension of K designated by each row vector in A and take summation of them.
For instance of a simplified example when n=2,
A=[1 2;3 4];%2X2 matrix
K=unifrnd(0.1,0.1,2,2,4);%just random 3D matrix
L=zeros(2,2);%save result to here
for t=1:2
L=L+prod(K(:,:,A(t,:)),3);
end
Can I get rid of the for loop in this case?
How's this?
B = A.'; %'
L = squeeze(sum(prod(...
reshape(permute(K(:,:,B(:)),[3 1 2]),2,[],size(K,1),size(K,2)),...
1),...
2));
Although your test case is too simple, so I can't be entirely sure that it's correct.
The idea is that we first take all the indices in A, in column-major order, then reshape the elements of K such that the first two dimensions are of size [2, n], and the second two dimensions are the original 2 of K. We then take the product, then the sum along the necessary dimensions, ending up with a matrix that has to be squeezed to get a 2d matrix.
Using a bit more informative test case:
K = rand(2,3,4);
A = randi(4,4,2);
L = zeros(2,3);%save result to here
for t=1:size(A,1)
L = L+prod(K(:,:,A(t,:)),3);
end
B = A.'; %'
L2 = squeeze(sum(prod(reshape(permute(K(:,:,B(:)),[3 1 2]),2,[],size(K,1),size(K,2)),1),2));
Then
>> isequal(L,L2)
ans =
1
With some reshaping magic -
%// Get sizes
[m1,n1,r1] = size(K);
[m2,n2] = size(A);
%// Index into 3rd dim of K; perform reductions and reshape back
Lout = reshape(sum(prod(reshape(K(:,:,A'),[],n2,m2),2),3),m1,n1);
Explanation :
Index into the third dimension of K with a transposed version of A (transposed because we are using rows of A for indexing).
Perform the prod() and sum() operations.
Finally reshape back to a shape same as K but without the third dimension as that was removed in the earlier reduction steps.

How is `(d*a)mod(b)=1` written in Ruby?

How should I write this:
(d*a)mod(b)=1
in order to make it work properly in Ruby? I tried it on Wolfram, but their solution:
(da(b, d))/(dd) = -a/d
doesn't help me. I know a and b. I need to solve (d*a)mod(b)=1 for d in the form d=....
It's not clear what you're asking, and, depending on what you mean, a solution may be impossible.
First off, (da(b, d))/(dd) = -a/d, is not a solution to that equation; rather, it's a misinterpretation of the notation used for partial derivatives. What Wolfram Alpha actually gave you was:
, which is entirely unrelated.
Secondly, if you're trying to solve (d*a)mod(b)=1 for d, you may be out of luck. For any value of a and b, where a and b have a common prime factor, there are an infinite number of values of d that satisfy the equation. If a and b are coprime, you can use the formula given in LutzL's answer.
Additionally, if you're looking to perform symbolic manipulation of equations, Ruby is likely not the proper tool. Consider using a CAS, like Python's SymPy or Wolfram Mathematica.
Finally, if you're just trying to compute (d*a)mod(b), the modulo operator in Ruby is %, so you'd write (d*a)%(b).
You are looking for the modular inverse of a modulo b.
For any two numbers a,b the extended euclidean algorithm
g,u,v = xgcd(a, b)
gives coefficients u,v such that
u*a+v*b = g
and g is the greatest common divisor. You need a,b co-prime, preferably by ensuring that b is a prime number, to get g=1 and then you can set d=u.
xgcd(a,b)
if b = 0
return (a,1,0)
q,r = a divmod b
// a = q*b + r
g,u,v = xgcd(b, r)
// g = u*b + v*r = u*b + v*(a-q*b) = v*a+(u-q*v)*b
return g,v,u - q*v

Matrix using matlab

this is my first question on this website. I'm looking at a Matlab problem, and don't seem to know how to do it. Before I type the question, I want to make it clear that I'm looking for an UNDERSTANDING, NOT an ANSWER. Although, I must admit, I won't be angry if an answer is posted. But more importantly, I need to understand this.
"The matrix factorization LU = PA can be used to compute the determinant of A. We have
det(L)det(U) = det(P)det(A).
Because L is triangular with ones on the diagonal, det(L) = 1. Because U is
triangular, det(U) = u 11 u 22 · · · u nn . Because P is a permutation, det(P) =
+1 if the number of interchanges is even and −1 if it is odd. So
det(A) = ±u 11 u 22 · · · u nn .
Modify the lutx function so that it returns four outputs.
function [L,U,p,sig] = lutx(A)
%LU Triangular factorization
% [L,U,p,sig] = lutx(A) computes a unit lower triangular
% matrix L, an upper triangular matrix U, a permutation
% vector p, and a scalar sig, so that L*U = A(p,:) and
% sig = +1 or -1 if p is an even or odd permutation.
Write a function mydet(A) that uses your modified lutx to compute the
determinant of A. In Matlab, the product u 11 u 22 · · · u nn can be computed
by the expression prod(diag(U))."`
The lutx code can be found here:
I'm having difficulty understanding the concept of the problem, and also the code that needs to be written. Any help would be very appreciated. Thank you.
As you mentioned in your problem in the following equation:
det(L)det(U) = det(P)det(A)
actually the lutx function decompose the input matrix and returns the decomposed elements. It means if you give it the A matrix, it will calculate the L,U,p. you can check the source code.
actually in your problem, three out of four elements are 'known', so you can use the lutx function to find the det(A).
because :
det(A) = det(L)det(U) / det(P);
so what you can do is this:
[L,U,p,sig] = lutx(A); % here I am using the modified version of lutx that you mentioned
DetA = 1 * prod(diag(U)) * sig;
because, det(L) = 1 (I mention it in the previous line of code just for underestanding), and det(U) = prod(diag(U)), and sig gives the sign.
finally you can compare your result with matlab function: det(A).
The exercise appears to be mainly to compute "sig", which lutx currently doesn't return. As a hint, you must compute
delta_p = (1:length(p))-p;
and check whether delta_p has an even or odd number of non-zero elements. That will determine the sign of sig.

Resources