How can I fix my for loop troubles in Matlab?

  • Context: MATLAB 
  • Thread starter Thread starter danbone87
  • Start date Start date
  • Tags Tags
    Loop Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
10 replies · 17K views
danbone87
Messages
28
Reaction score
0
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
 
Physics news on Phys.org
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
 
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?
 
sorry, but I am not sure what that means at all :[
 
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));
 
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
 
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...
 
I got it!

thanks so much for the help