Polynomials and Loops

 

·           Now let’s compute the roots of a polynomial for a range of c values:

 

for c=-10:1:0

A=[1,0,c];  % y=1*x.^2+0*x+c

R=roots(A);

fprintf('When c=%.1f, the roots are %.1f and %.1f \n',c,R(1),R(2))

end

 

·           Now let’s get really fancy…

 

x=linspace(-5,5,1000);

 

for c=-5:1:0

A=[1,0,c];

R=roots(A);

fprintf('When c=%.1f, the roots are %.1f and %.1f \n',c,R(1),R(2))

y=polyval(A,x);

figure(1)

plot(x,y, 'b-',R(1),0, 'r+',R(2),0, 'r+')

disp('Hit any key to move on')

pause

end

 

 

Storing Results From Each Iteration

 

·           What if we want to store all the roots we are calculating, to look at when the loop is done?  We need to assign the result obtained in each iteration to a new array element (rather than over-writing the same variable R).

 

b_array=[-10:.5:-5];

 

for b_idx = 1:length(b_array) % loop over y-intercepts we are interested in

 

R(b_idx)=roots([1,b_array(b_idx)]);  % find root of y=mx+b for m=1 and b=?

 

end

 

 

              plot(b_array,R);

              xlabel('b');

              ylabel('Root');

title('Root of y(x)=1x+b');

 

 

·           Here is another example where, instead of one root, we get two roots per loop.  We need a 2D array to store these…

 

c_array=[-15:1:-5];

 

for c_idx = 1:length(c_array)

 

R2d(:,c_idx)=roots([1,0,c_array(c_idx)]);

 

end

 

 

              plot(c_array,R2d(1,:),c_array,R2d(2,:));

              legend('First Root', 'Second Root');

              xlabel('c');

              ylabel('Root');

              title('Root of y(x)=x^2+c');

 

 

Embedded Loops

 

·           You can use for-loops inside of for-loops (embedded loops).  Here we find the root a straight line for many combinations of slopes (m) and y-intercepts (b).

 

 

m=[1:.5:5];

b=[0:-.5:-3];

 

for m_idx = 1 : length(m)

 

for b_idx = 1 : length(b)

 

myroots(m_idx,b_idx)=roots([m(m_idx),b(b_idx)]);

 

end

 

end

 

 

 

% display the results

myroots

 

% each column is for a specific b

b

 

% each row is for a specific m

m'

 

·           Let’s take a closer look at how the results are stored in the 2D array ‘myroots’ here.