-2

I'm trying to figure out this bootleg programming language but keep getting stumped on things like this.

My code is as follows:

clc;
clear;

for i = -3:6;
    x(i) = i;
    y(i) = (i^4)-(4*(i^3))-(6*(i^2))+15; %being my given function
end
plot(x,y)

It works if I start from 1 because it's a positive integer. It can't access zero nor negative values. How do I go around this?

edit: thanks for the swift response you guys, I like your methods and definitely wanted to approach it different ways but one of the requirements in my text is to use the for loop, sadly

KingHarambe
  • 111
  • 6
  • If you really want to use a loop, replace `x(i)` with `x(i+4)` and `y(i)` with `y(i+4)` and consider using some other variable than [*`i` (and `j`)*](https://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) – Sardar Usama Nov 10 '17 at 21:26
  • Possible duplicate of [Plotting equation in Matlab using for loop](https://stackoverflow.com/questions/37692453/plotting-equation-in-matlab-using-for-loop) – frslm Nov 11 '17 at 03:54

2 Answers2

0

You can do this even without a for loop.

x = -3:6;
y = (x.^4)-(4*(x.^3))-(6*(x.^2))+15;

Matlab is way more effective if it's used without loops. For your case with this small range it will have no effect but if you go for way more elements you increase the speed of your code using this approach.

To answer you original question. The problem is that you are using the index based vector access. And the first element in Matlab vector is defined with index 1.

For your edit and the requirement of using the for loop you can use this approach

x = -3:6;
y = zeros(1, length(x));
% initialization prevents the vector size being changed in every iteration
for i = 1:length(x)
    y = (x(i)^4)-(4*(x(i)^3))-(6*(x(i)^2))+15;
end
FreshD
  • 2,914
  • 2
  • 23
  • 34
0

Since you can't access array elements with negative indices, you'll need to use a different variable than i to keep track of each element in x and y; this new variable should start at 1 and increment with every loop iteration.

But you don't even need to worry about managing that; you can simply assign -3:6 to x and compute your function using x as an array:

clc;
clear;

x = -3:6;
y = (x.^4)-(4*(x.^3))-(6*(x.^2))+15;
plot(x,y)

However, this will produce a graph that looks a bit jagged. If you want x to contain more points, you can use linspace() instead:

clc;
clear;

x = linspace(-3, 6); % (similar to -3:0.09:6)
y = (x.^4)-(4*(x.^3))-(6*(x.^2))+15;
plot(x,y)
frslm
  • 2,969
  • 3
  • 13
  • 26