Why do I get this error message "Array indices must be positive integers or logical values."

2 次查看(过去 30 天)
fyi - first time posting.
Why do I get this error message?
Array indices must be positive integers or logical values.
Error in task2testdimforxandy (line 15)
Z = x.^2*y(y-1)*(y+1)
And what would you suggest to fix?
thanks.
clear, clc
x = -1:2/9:1
y = -2:4/9:2
% create grid
for i = 1:length(x)
for j = 1:length(y)
% i is being used to step along the x axis
% j is being used to step along the y axis
% Note the ORDER of i and j when indexing
X(j,i) = x(i) % store x position
Y(j,i) = y(j) % store y position
end
end
% calculate the heights for all points on the grid
Z = x.^2*y(y-1)*(y+1)
surf(X,Y,Z)
xlabel('x')
ylabel('y')
zlabel('z')
title('x^2*y(y-1)*(y+1) using surf')
  1 个评论
the cyclist
the cyclist 2020-8-28
FYI, I edited your question a bit, so that your code appears like code instead of just plain text. I did that by using the CODE section in the toolbar.

请先登录,再进行评论。

采纳的回答

the cyclist
the cyclist 2020-8-28
编辑:the cyclist 2020-8-28
You have three distinct problems in this one line of code:
Z = x.^2*y(y-1)*(y+1)
One of them is causing the error you are seeing. You'll also need to fix the other two.
  1. Where you wrote y(y-1), MATLAB thinks you are calling a function, with argument y-1. Instead, you need y.*(y-1).
  2. All of those multiplications should be element-wise rather than matrix multiplications. If you don't know what that means, read this documentation.
  3. You need X and Y here, not x and y.
Put it all together, and you need
Z = X.^2.*Y.*(Y-1).*(Y+1);
  3 个评论
Stephen23
Stephen23 2020-8-28
"Where you wrote y(y-1), MATLAB thinks you are calling a function..."
The error message tells us that MATLAB is attempting to index into a variable, not call a function.
the cyclist
the cyclist 2020-8-28
@Samuel:
Stephen is correct here, and it's worth thinking about the difference there. I mainly intended to explain that the y(y-1) syntax, which is usual for multiplication in mathematics, means something different in MATLAB. But I got the "something different" wrong. :-)
Also, is this a homework assignment? It's starting to sound like a homework assignment.

请先登录,再进行评论。

更多回答(1 个)

James Tursa
James Tursa 2020-8-28
编辑:James Tursa 2020-8-28
You forgot to multiply between the y and (y-1)
Z = x(:).^2.*y.*(y-1).*(y+1);
Also, make sure to use element-wise operators (with the dot). And to get a matrix result for Z, make one of x or y a column vector (I did that by using the x(:) syntax).
The syntax you were using, namely y(y-1), is interpreted by MATLAB as meaning you are trying to index into the y vector using y-1 as the element index ... hence the error message.

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by