# Matlab, for loop troubles.

1. Feb 21, 2008

### danbone87

Hi, I have this for loop where i want it to iterate for a variable ap = ap-1 -f(x)

and i want ap-1 to replace ap in each iteration.

It's pretty simple but i just can't get it to work out. any help would be appreciated and here's my code btw.

clc
a=1
fa=exp(a)*((-a^2)+(2*a)-2)+2.723684615938410;
fprimea=exp(a)*(a^2);
ap=a+(fa/fprimea);
tol=1*(10^-6);
f=abs(ap-a);
n=15;

for k=1:10
ap=a-(fa/fprimea);
f=abs(ap-a)
a=ap
end

2. Feb 21, 2008

### chroot

Staff Emeritus
From the look of it, you need to learn how to write functions. Look them up in the help.

Right now you're just calculating the fa and fprimea junk once.

- Warren

3. Feb 21, 2008

### danbone87

I've been working with those and i keep getting this dang error "index must be a positive integer or logical."

not sure what that means... any ideas?

4. Feb 21, 2008

### chroot

Staff Emeritus
It probably means you're trying to use 0 to index a vector or matrix. MATLAB indices begin at 1.

- Warren

5. Feb 21, 2008

### danbone87

sorry, but im not sure what that means at all :[

6. Feb 21, 2008

### chroot

Staff Emeritus
Well, I can't say for sure unless you show me the code and indicate what line is causing the error.

- Warren

7. Feb 21, 2008

### danbone87

function [f ap]=NR(fa,fprimea,a,tol,f,iterations)

a=1
fa=exp(a)*((-a^2)+(2*a)-2)+2.723684615938410;
fprimea=exp(a)*(a^2);
ap=a+(fa/fprimea);
tol=1*(10^-6);
f=abs(ap-a);
n=15;
iterations= input('how many interations? ')

for k=1:iterations
ap=a-(fa(a)/fprimea(a)); <----- error is in this line
f=abs(ap-a)
a=ap
end

end

error: ??? Attempted to access fa(0.998012); index must be a positive integer or logical.

Error in ==> matlabsss at 14
ap=a-(fa(a)/fprimea(a));

8. Feb 21, 2008

### chroot

Staff Emeritus
In this line:

ap=a-(fa(a)/fprimea(a));

Are you just trying to multiply fa by a and fprimea by a? If so, you need to use * to represent multiplication. MATLAB is interpreting your use of parentheses as an array lookup, e.g. fa(a) is the ath element of fa.

- Warren

9. Feb 21, 2008

### danbone87

okay, i have a function going and all that and it's still doing the same thing. it's not modifying the a to make it equal to the ap of the last iteration...

10. Feb 21, 2008

### chroot

Staff Emeritus
a only exists inside your function. It disappears as soon as the function is done running. You're passing ap out.

- Warren

11. Feb 21, 2008

### danbone87

I got it!

thanks so much for the help