Search code examples
matlabmatrixindexingsom

MATLAB Index exceeds matrix dimensions


So this is code from a book I am looking at done in Matlab. The model array M is initialized, Q is the norm of the difference of the input vector X and the best-matching model.

M = rand(64,2); % initialization of a 64-model SOM array

Q = zeros(64,1); % quantization error
for t = 1:1000000
    X = rand(1,2); % training input
    % Winner search
        for i = 1:64
            Q(i,1) = norm(X(t,:) - M(i,:));
        end
    [C,c] = min(Q);
end

I get an error Index exceeds matrix dimensions.

Error in som1 (line 8)
            Q(i,1) = norm(X(t,:) - M(i,:));

I can see (or think) the error is coming from the indexing of M, but I am not sure why or how I can fix it. Any ideas or guidance would be much appreciated!


Solution

  • Let's look for your winner by chucking the innermost loop with bsxfun -

    for t = 1:100
        X = rand(1,2); % training input
        [C,c] = min(sum(bsxfun(@minus,X,M).^2,2));
    end