Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.



Re: ??? In an assignment A(I) = B, the number of elements in B and I must be the same.
Posted:
Feb 9, 2013 1:57 AM


On 2/9/2013 12:47 AM, John wrote: > I am having trouble with my code and keep getting the message in the subject block. >I am doing Newton's Method to determine a numerical solution. Also, I know >the way I have written it is a slow method. What faster ways are there >to write the code? Here's the code: > > % Newton's Method > % Let the function we are looking at be the following f(x)=55*xexp(0.5*x) > > clear all > close all > clc > > > x(1) = 0.7; % given initial guess > > err = 100; > i = 1; > > while err> 0.02 > > f(i) = 55*xexp(0.5*x); % given function > fprime(i) = 50.5*exp(0.5*x); % Derivative of the function > > x(i+1) = x(i)  (f(i)/fprime(i)); > > err=abs(x(i+1)x(i))/(x(i)); > > i = i+1; %will run the next iteration to get increasing accuracy > end > > xvec = 0:.01:4; %creates a vector for x from 3 to 7 in steps of .01 > fvec = 50.5*exp(0.5*xvec); %creates a function to plot the range of x > > plot(xvec,fvec,x(i1),f(i1), 'rs') %plots the function and boxes the solution > grid on >
 13. The variable 'f' appears to change size on every loop iteration (within a script). Consider preallocating for speed.
14: The variable 'fprime' appears to change size on every loop iteration (within a script). Consider preallocating for speed.
16: The variable 'x' appears to change size on every loop iteration (within a script). Consider preallocating for speed. 
In the line
> f(i) = 55*xexp(0.5*x); % given function
first time when i=1, it is ok. Next time when i=2, then x is now 2 element vector, but it is being assigned to one element f(i). Hence the error.
Think what happens when i=1 and when i=2 and look at the code then the problem will be clear.
Nasser



