I keep getting "Array indices must be positive integers or logical values."

2 views (last 30 days)
Tracy on 27 Nov 2020
Commented: Tracy on 28 Nov 2020
clear;clc
x = .993 : 0.01 : 1.283;
for n = 1 :1: length(x)
f(x) = 7*x(n)^3 - 2*x(n)^2 + 7*x(n) - 14;
g(x) = -19*x(n)^3 + 3*x(n)^2 + 16*x(n) + 8;
end
plot(x,f,'+r',x,g,'-.b')
xlabel('x values')
ylabel('f(x) and g(x) values')
legend('f(x)','g(x)')
I keep getting:
Array indices must be positive integers or logical values.
Error in (line 9)
f(x) = 7*x(n)^3 - 2*x(n)^2 + 7*x(n) -14;

Sulaymon Eshkabilov on 27 Nov 2020
Edited: Sulaymon Eshkabilov on 27 Nov 2020
clearvars;clc
x = .993 : 0.01 : 1.283;
for n = 1 :length(x)
f(n) = 7*x(n)^3 - 2*x(n)^2 + 7*x(n) - 14; % Index has to be n
g(n) = -19*x(n)^3 + 3*x(n)^2 + 16*x(n) + 8; % Index has to be n
end
plot(x,f,'+r',x,g,'-.b')
xlabel('x values')
ylabel('f(x) and g(x) values')
legend('f(x)','g(x)')
Tracy on 28 Nov 2020
thanks!!

VBBV on 27 Nov 2020
Edited: VBBV on 27 Nov 2020
%true
clearvars;clc
x = .993 : 0.01 : 1.283;
f = 7*x.^3 - 2*x.^2 + 7*x - 14;
g = -19*x.^3 + 3*x.^2 + 16*x + 8;
plot(x,f,'+r',x,g,'-.b')
xlabel('x values')
ylabel('f(x) and g(x) values')
legend('f(x)','g(x)')
for loop is not necessary in your case.

Andrei Bobrov on 27 Nov 2020
x = (.993 : 0.01 : 1.283)';
f = polyval([7;-2;7;-14],x);
g = polyval([-19; 3; 16; 8],x);

Image Analyst on 27 Nov 2020