MATLAB: Unable to calculate xcorr in for loop

for loopsubscript mismatchxcorr

I tried to calculate the xcorr using a for loop and i got the 'subscript mismatch error'.
The code looks like:
for k = 2:numel(rep)
X(k) = xcorr(wg1(:,1),wg1(:,k));
L = length(wg1(:,1));
[m(k),d(k)]=max(X(k));
delay (k) = d(k)-max(L);
tX(k)=[delay(k)+1:length(wg1(:,k))+delay(k)]./Fs;
end
Any ideas? Cheers!

Best Answer

A simplification to avoid repeated calculations:
L = size(wg1, 1); % Better than: length(wg1(:,k))

for k = 2:numel(rep)
X(k) = xcorr(wg1(:,1), wg1(:,k));
[m(k), d(k)] = max(X(k));
delay(k) = d(k)-max(L);
tX(k) = (delay(k)+1:L + delay(k)) ./ Fs;
end
I've replaced the square brackets by parentheses, see http://www.mathworks.com/matlabcentral/answers/35676-why-not-use-square-brackets
Now look on the assignment of tX(k): On the right side is a vector, and on the left side a scalar. Then the assignment cannot work. To store vectors of different lengths you need a cell array:
L = size(wg1, 1); % Better than: length(wg1(:,k))
tX = cell(1, numel(rep));
for k = 2:numel(rep)
X(k) = xcorr(wg1(:,1), wg1(:,k));
[m(k), d(k)] = max(X(k));
delay(k) = d(k)-max(L);
tX{k} = (delay(k)+1:L + delay(k)) ./ Fs;
end
But wait! xcorr replies a vector also. Then "X(k) = xcorr(...)" suffers from the same problem also. It would be more clear, which line causes the troubles, if you post the complete error message, which mentions all details. If you just post a tiny part of the message, the readers have to guess the details - inefficient.