D. Sill
D. Sill

Reputation: 307

Print selective iterations in matlab

I've written a programme to find a root of an equation using matlab. It is designed to run 300 iterations to approximate the root. However i am required to make the program only output iterations 90-100 and 290-300. I have tried making a loop within the loop and putting the print statement in this however it only seems to print the same value rather than the next iteration. Apologies if this is quite basic but im new to this and cant quite figure out what to do. Here is the code so far that runs for 300 iterations.

% MATLAB M-file to solve a single equation using the Rearrangement method.

% The function is f(x)= x^3 - 7x^2 + 11x + 5 = 0 and the rearranged function 
% is g(x) = sqrt((x^3 + 11x - 5)/7).

clc        
clear       

k = 0;      % Set the iteration number
x = 2;      % Set the starting value

diff = 1;   % Set the difference between successive x values
            % to an arbitrary value to start the iteration


fprintf('    k      xk\n')

while k < 300 

   xlast = x; 
   x = sqrt((x^3 + 11*x -5)/7);  %  defines x(k+1) = g(x(k))

   % Calculate the difference between two successive iterations
   diff = abs(x - xlast);  

   k = k + 1;   % Add 1 to the iteration number
   fprintf('%5i%10.6f\n', k, x) 

end 
fprintf('Final solution = %1.5f to 5 decimal places\n',x)

Upvotes: 2

Views: 496

Answers (2)

coucou
coucou

Reputation: 13

A somewhat more fancy version, if you want to get frequent updates (iteration-printings), but don't want the output to cover too many lines:

n = 1e4;
hundreds  = linspace(1e2,1e5,1e3);
thousands = linspace(1e3,1e6,1e3);

for i = 1:n
    if (ismember(i,[1,hundreds]));
        if (ismember(i,[1,thousands])); 
            fprintf(1,['\n n=',num2str(n),' -- '])
        end  
        fprintf(1,[num2str(i),', ']); 
    end  
end

This will give you something like this

 n=10000 -- 1, 100, 200, 300, 400, 500, 600, 700, 800, 900, 
 n=10000 -- 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 
 n=10000 -- 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 
 n=10000 -- 3000, ...
 ...        ...
 ...        ...
 n=10000 -- 9000, 9100, 9200, 9300, 9400, 9500, 9600, 9700, 9800, 9900, 
 n=10000 -- 10000

Upvotes: 0

Bruce Dean
Bruce Dean

Reputation: 2828

If I understand your problem, maybe you could just define the ranges from which you would like to print the results, like this:

range_1 = [90:100];
range_2 = [290:300];

while k < 300 
   ...

Then just wrap a conditional around your print statement:

k = k + 1;   % Add 1 to the iteration number

if ( ismember(k, [range_1, range_2]) ) 
   fprintf('%5i%10.6f\n', k, x)
end

Which seems to do the trick.

EDIT: At Dan's suggestion, used the ismember() function to check inclusion within the ranges.

Upvotes: 4

Related Questions