0
votes

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)
2
Welcome to Matlab. The error you got is not specific to the way of calculation, but the language syntax itself.Yvon

2 Answers

3
votes

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)
0
votes
x = linspace(-3, 6, 100);
y = x.^4-4*x.^3-6*x.^2+15;
plot(x,y)