Michael
Posts:
4
Registered:
3/26/12
|
|
Speeding up calculation of matrix
Posted:
Mar 26, 2012 3:09 PM
|
|
Hi,
I am calculating a matrix M from two column vectors and two coefficients, calculated like so:
%%%%%%%%%%%%% x=rand(10,1); y=rand(10,1); fit_x = 2; fit_y = 3;
% initialize M nRows = length(x); nCols = (fit_x+1)*(fit_y+1); M=ones(nRows,nCols);
% build each column of M iCol = 1; for px=0:fit_x for py=0:fit_y M(:,iCol)=x.^px .* y.^py; iCol=iCol+1; end end
%%%%%%%%%%%%%
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?
|
|