Why do I get the error "Array indices must be positive integers or logical values" in MATLAB

Viewed 470

I need to write the function among others in MATLAB, but I keep getting "Array indices must be positive integers or logical values." error and an error for both functions f(x) and u(x) saying "Error in f(x(j)) = ..." or "Error in u(x(j)) = ....." Why is that?

This is the code relating to that


for j=1:n
    x(j)=-1+j*h;          
    f(x(j)) = (pi.^2).*(exp(cos(pi.*x(j)))).*(cos(pi.*x(j))-(sin(pi.*x(j))).^2);
    u(x(j))= -f(x(j));
end

1 Answers

The error coming from the value of h must be integer for example:

if h = 1; f(1), u(1) no error

if h = 1.3; f(1.3), u(1.3) error

The is no reserved place in array f(1.3) by 1.3;

Fix h value by an integer to solve the error.

n = 99; 
h = 2; 
x = ones(n,1); 
f = ones(n,1); 
u = ones(n,1);

for j=1:n
    x(j)    = -1+j*h;   
    f(x(j)) = (pi.^2).*(exp(cos(pi.*x(j)))).*(cos(pi.*x(j))-(sin(pi.*x(j))).^2);
    u(x(j)) = -f(x(j));
end
Related