Subscript error: sum = sum(s)

北城以北 提交于 2021-02-08 05:12:18

问题


Below is my code, where h and Y are 47x1 vectors.

s = h-Y;
sum = sum(s);

I am getting this error:

error: sum(6057.48): subscripts must be either integers 1 to (2^31)-1 or logicals

Can somebody please explain why?


回答1:


As mentioned in the comments by Sardar Usama, you cannot use the variable name sum when you also want to use the built-in function sum.

By default, sum is a function, used as you expected it to work in your script.

In Octave, you are permitted to overshadow a built-in function, for instance

sum = 4; % Now there is a workspace variable, sum, with the value 4

When you do this, the keyword sum now stands for the variable, not the function. It's strongly advisable not to overwrite default functions, even if you're not planning on using them in that script!


To remove your overshadowing, just clear the variable,

clear sum % Now it should behave as expected.

The reason you must clear the variable before continuing is to do with your workspace. The variable sum remains in your workspace even after the program exited, so when you run it again (even if you've chosen a new variable name) you have still already changed how sum is interpreted. By clearing the variable, Octave sets it back to its default behaviour as it is removed from your workspace.


Summary: use a different variable name.

s = h-Y;
mysum = sum(s); % mysum isn't a built-in, so no clashes here!


来源:https://stackoverflow.com/questions/43744125/subscript-error-sum-sums

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!