Why do I get this error message "Array indices must be positive integers or logical values."
Show older comments
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 Comment
the cyclist
on 28 Aug 2020
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.
Accepted Answer
More Answers (1)
James Tursa
on 28 Aug 2020
Edited: James Tursa
on 28 Aug 2020
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.
1 Comment
Samuel Tate
on 28 Aug 2020
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!