Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


Math Forum » Discussions » Software » comp.soft-sys.matlab

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Nasser Abbasi

Posts: 5,647
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
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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




Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.