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