MATLAB: A for loop implementation… given matrix A=299×10, calculate the autocorrelation for every row of Matrix A one at a time

for looptoeplitz

Hi, given that size(A)= 299×10, I need to put the following code into a for loop, to avoid writing the 299 lines ….
if true
%
row1=A(1,:)
R1=xcorr(row1)
row2=A(2,:)
R2=xcorr(row2)
.
.
.
row299=A(299,:)
R299=xcorr(row299)
end
Once a new variable B is created(every row in B should have the autocorrelation of the corresponding row in A)
Then I need to calculate the Toeplitz of B toeplitz(B)
Thank you!!

Best Answer

If my reading of the xcorr doc is correct (I don't have the signal processing toolbox), you could just apply xcorr to the whole matrix (transposed as xcorr works columnwise) and then discard the columns that are to cross-correlations with other columns:
allcorrelations = xcorr(A'); %transpose A since xcorr works on columns
ncols = size(A, 1); %number of columns in the transposed matrix = rows in the original
autocorrelations = allcorrelations(:, sub2ind([ncols ncols], 1:ncols, 1:ncols))'; %extract autocorrelation and transpose back
%note: you could replace the sub2ind(...) by
% 1:ncols+1:ncols*ncols
%it does the same thing but for me sub2ind shows the intent better
Alternatively:
autocorrelations = cellfun(@xcorr, num2cell(A, 2), 'UniformOutput', false);
autocorrelations = vertcat(autocorrelations{:});
The second option is possibly slower than the first since it is basically loops over each row. On the other hand it doesn't waste time calculating the cross-correlations. It is certainly going to be more memory efficient.