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: Speeding up calculation of matrix
Replies: 5   Last Post: Mar 27, 2012 11:21 AM

Advanced Search

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

Posts: 4
Registered: 3/26/12
Speeding up calculation of matrix
Posted: Mar 26, 2012 3:09 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply


I am calculating a matrix M from two column vectors and two coefficients, calculated like so:

fit_x = 2;
fit_y = 3;

% initialize M
nRows = length(x);
nCols = (fit_x+1)*(fit_y+1);

% build each column of M
iCol = 1;
for px=0:fit_x
for py=0:fit_y
M(:,iCol)=x.^px .* y.^py;


where x and y are normally input vectors, and fit_x and fit_y are input scalars. This function is called many times by my code, and after profiling, a significant portion of time is spent generating this M matrix.

Is there a better way to do this? I feel like I am overlooking a one-line vectorized solution to this, replacing the loop. I have tried:


x_power = kron(0:fit_x,ones(nRows,fit_y+1));
y_power = repmat(0:fit_y,nRows,fit_x+1);

x2 = repmat(x,1,nCols);
y2 = repmat(y,1,nCols);

M2 = x2.^x_power .* y2.^y_power;

to compute the matrix in one shot, but it takes significantly longer - in fact, each call to repmat in the second method takes about as long as generating the matrix using the double loop. Any suggestions?

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.