问题
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