Jeff
Posts:
103
Registered:
11/22/09
|
|
Can my code be made more efficient using MATLAB's vectorization?
Posted:
Feb 14, 2013 12:49 PM
|
|
Is there a better, more MATLAB-y way, to write this code (that is, using vectors)? Eventually, this will be used for large amounts of data (from a program running on a cluster), so I need it as efficient as possible.
U and W are T rows x N columns matrices. Variable evals is a 1 by N matrix of the eigenvalues (of some other matrix which doesn't matter for this post). For now, the largest value of T is about 1000, but eventually it will be many thousands (maybe even millions).
So the first thing I need to do (variable P_p) is subtract the each entry on the row from the one to its right (for now, I only have periodic conditions coded). I think I have that variable coded fairly efficiently (yes? no?).
if strcmp(boundary,'periodic') nMinusOne=[N 1:N-1]; nPlusOne=[2:N 1]; elseif strcmp(boundary,'fixed') nMinusOne=[1:N-1]; nPlusOne=[2:N]; end
P_p = ((U(:,nPlusOne)-U(:,n)).^2); Q_p = Udot(:,n).^2; H = P_p + Q_p;
But for variable P_f I need to square each element of W, then multiply everything in column 1 by eval(1), everything in column 2 by evals(2), ... everything in column n by evals(n) (where, obviously, n=1..N). Finally, I need to divide each element of P_f by N. In math terms, I'm trying to do something like
(W_{i,j}^2)*eval_j ------------------ N
And this code is the most efficient I could think of. It's not terribly fast (on my quad core PC). Can it be improved?
P_f = zeros(t_end,N); for m=1:t_end P_f = W(m,:).^2.*evals; end P_f = -P_f./N;
Q_f = (Wdot.^2)./n; H_f = P_f + Q_f;
|
|