MATLAB: Index exceeds the number of array elements (1).

MATLAB: Index exceeds the number of array elements (1).

errorinput

So I’m trying to get user input but when I run the code, I get the error “Index exceeds the number of array elements (1).” I looked up how to use the input function and it looks correct so I’m not sure why this error is coming up. I’m on macOS if that’s relevent at all.
prompt = 'Amount to add: ';
var = input(prompt);
mysum(var);
function sum = mysum(var)
sum = 0;
for i = 1:var
sum = sum + i;
end
end

Best Answer

  • The input call works correctly for me.
    I suspect that you have assigned ‘input’ as a variable earlier in your code. In doing that, you have ‘overshadowed’ the input function, and that is causing the error.
    To solve that problem, name the ‘input’ variable something that does not conflict with the name of a MATLAB function. (It might actually be better to use inputdlg instead.)
  • Add a Comment

    Your email address will not be published. Required fields are marked *