I have a solution vector
$$\begin{equation}H^{(\text{LR})}:= \frac{1}{\Delta x^{2}}\sum\limits_{n=1}^{N}\sum\limits_{m=1}^{N}\frac{u_{n}u_{n+m} + v_{n}v_{n+m}}{m^{1+\alpha}}\end{equation}$$
where $u_k$ is the real part of a solution of ODEs (resp. $v_k$). Here, the index is periodic, e.g, $n+N \equiv n$.
I want to compute this function for every time-step in my numerical scheme, e.g, $10^{5}$ time steps. My attempt takes longer than actually solving the system of ODEs that this Hamiltonian is for. I've already tried vectorizing the code.. what else can I do?
MWE:
%% HAMILTONIAN MONITORING
u = rand(10000,1024);
tic
u_real = real(u); % Extract real part
v_imag = imag(u); % Extract imaginary part
N = width(u); % Number of spatial points
T = length(u); % Number of time steps
% Precompute the denominator terms for efficiency
alpha = 1; % Adjust alpha based on problem
m_vals = (1:N); % Vector of m values
denominator = m_vals.^(1+alpha); % Vectorized power computation
% Preallocate Hamiltonian vector
HAMILTONIAN = zeros(T, 1);
% Compute Hamiltonian for each time step
for t = 1:T
% Compute u_n^2 + v_n^2 for all n (vectorized)
%u_sq = u_real(t,:).^2;
%v_sq = v_imag(t,:).^2;
% Compute the sum for all n
sum_over_n = 0;
% Compute H_temp in a vectorized manner
for n = 1:N
% Index shift using mod, avoiding explicit loops
idx = mod(n + m_vals', N); % Pre-compute the indices
idx(find(idx == 0)) = N; % There is no 0-index. 0-index corresponds to the Nth index.
H_summands = (u_real(t,n) * u_real(t,idx)' + v_imag(t,n) * v_imag(t,idx)') ./ denominator';
% Accumulate the sum over n
sum_over_n = sum_over_n + sum(H_summands);
end
% Store in Hamiltonian vector
HAMILTONIAN(t) = sum_over_n;
end
MWE using MATLAB 2024a
u = randn(N, 1)oru = transpose(1:n)in the MWE? Any timing will likely not depend on the content of those vectors. $\endgroup$