Search code examples
matlabbsxfun

Error: Index exceeds matrix dimensions while using bsxfun in matlab


My code is :

A =[1 5 8; 3 4 7;9 10 11]
B = bsxfun(@rdivide,A,sum(A));

On running, I get an error : index exceeds matrix dimension

Please help.


Solution

  • You have (very likely) defined a variable called sum in your workspace. clear it, rename it, and you'll be fine.

    A =[1 5 8; 3 4 7;9 10 11];
    B = bsxfun(@rdivide,A,sum(A))
    B =
    
       0.076923   0.263158   0.307692
       0.230769   0.210526   0.269231
       0.692308   0.526316   0.423077
    
    
    sum = 5;   %% Oops!
    
    B = bsxfun(@rdivide,A,sum(A))
    Error: Index exceeds matrix dimensions