Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Topic: ??? In an assignment A(I) = B, the number of elements in B
and I must be the same.

Replies: 5   Last Post: Dec 31, 2013 3:44 PM

 Messages: [ Previous | Next ]
 Nasser Abbasi Posts: 6,569 Registered: 2/7/05
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)=5-5*x-exp(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) = 5-5*x-exp(0.5*x); % given function
> fprime(i) = -5-0.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 = -5-0.5*exp(0.5*xvec); %creates a function to plot the range of x
>
> plot(xvec,fvec,x(i-1),f(i-1), '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) = 5-5*x-exp(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

Date Subject Author
2/9/13 Nasser Abbasi
12/24/13 Charanraj
12/24/13 Curious
12/31/13 Charanraj
12/31/13 dpb