The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Can my code be made more efficient using MATLAB's vectorization?
Replies: 4   Last Post: Feb 16, 2013 6:55 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]

Posts: 113
Registered: 11/22/09
Can my code be made more efficient using MATLAB's vectorization?
Posted: Feb 14, 2013 12:49 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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')

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


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;
P_f = -P_f./N;

Q_f = (Wdot.^2)./n;
H_f = P_f + Q_f;

Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.