0

I want to plot an equation using a for-loop. I have tried several different ways, but keep getting the apparently common error "Subscript indices must either be real positive integers or logicals". The equation I want to plot is y(x) = (x^4)-(4*x^3)-(6*x^2)+15.

The last code I tried was the following:

y(0) = 15;
for x = [-3 -2 -1 0 1 2 3 4 5 6];
    y(x) = (x^4)-(4*x^3)-(6*x^2)+15;
end
plot(x,y)
1
  • Welcome to Matlab. The error you got is not specific to the way of calculation, but the language syntax itself. Commented Jun 8, 2016 at 6:47

2 Answers 2

2

To start from the beginning,

y(0) = 15;

will give you the following error:

Subscript indices must either be real positive integers or logicals.

This is because Matlab's indexing starts at 1. Other languages like C and Python start at 0.


Matlab can work directly with vectors. So in your code, there is no need for a loop at all.
You can do it like this:

x = [-3 -2 -1 0 1 2 3 4 5 6];
y = (x.^4) - (4*x.^3) - (6*x.^2) + 15;
plot(x, y);

Note that we need to use element-wise operators like .* and .^ to calculate the values vectorized for every element. Therefore a point . is written in front of the operator.


Additionally, we can improve the code substantially by using the colon operator to generate x:

x = -3:6; % produces the same as [-3 -2 -1 0 1 2 3 4 5 6]
y = (x.^4) - (4*x.^3) - (6*x.^2) + 15;
plot(x, y);

If you want finer details for your graph, use linspace as suggested by @Yvon:

x = linspace(-3, 6, 100); % produces a vector with 100 points between -3 and 6.
y = x.^4-4*x.^3-6*x.^2+15;
plot(x,y)
Sign up to request clarification or add additional context in comments.

2 Comments

It would be good to include why the error occurred and what the OP should do to avoid it next time. We need to make the users understand what they are doing wrong, not only present a working solution. For example: Why y(x) does not work. Perhaps introducing the : operator to generate the x values directly with x = -3:6 would be helpful, too.
@Matt great feedback! Updated the answer.
0
x = linspace(-3, 6, 100);
y = x.^4-4*x.^3-6*x.^2+15;
plot(x,y)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.