1

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!

  • There's [251 questions](http://stackoverflow.com/search?q=%5Bmatlab%5D+Index+exceeds+matrix+dimensions) with this exact error on SO. – Adriaan Oct 02 '15 at 15:16
  • 1
    Look at the dimensions of `X`... then look at how `t` is being used to index into `X`. `X` --> `1 x 2`... `t` goes from 1 to 1000000. – rayryeng Oct 02 '15 at 15:29

1 Answers1

5

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
Divakar
  • 218,885
  • 19
  • 262
  • 358