# MATLAB: Plotting a variable that changes in a loop iteration vs the iteration number

iterationplot

I am trying to plot the change in u (diff_u) agaist the iteration to prove that diff_u converges. What is the best way to do this?
Below is my code, with z being the iteration counter:
%% Parametersrho = 1.225; % kg/m^3 - Air sea level standard dayU = 10; % m/s - freestreammu = 1.789e-5; % kg/(m*s) - Air sea level standard daynu = mu/rho; % m^2/sL = 0.25; % mH = 0.05; % m % nx and ny defines matrix grid, dx and dy for step sizenx = 50;ny = 10;dx = .005; % 50 grid points in x-dir - .005m spacingdy = .005; % 10 grid points in y-dir - .005m spacing % Re based on lengthRe_L = U*L/nu; % Filling mesh with 0 to beginv = zeros(ny,nx); % All initial v are 0u = ones(ny,nx)*U; % Filling the entire mesh with all u = 10 % Boundary Conditions% Goes (j,i) each segment, fills mesh with known valuesu(:,1) = U; % Inletv(:,1) = 0; % Inletu(1,:) = 0; % No Slip wallv(1,:) = 0; % No Slip wallu(ny,:) = U; % Free stream (top of mesh)%% Solving% Guess values of alphaalphau = 0.001; %guess, will need to figure out best value for this alphav = 0.1; % Differencesdiff_u=[];diff_v=[];diff_u_max=[];diff_v_max=[];diff_both=[]; % Tolerance and convergence for main while looptol = .001;converge = false;z = 0; % Starting the index for iterationswhile z < 20 % This is number of iterations it performs    z = z + 1;    for j = 2:1:ny-1        for i = 2:1:nx-1            u_i = u(j,i+1);            u(j,i+1) = (2*dx/u(j,i)) * (((mu/rho)*((u(j-1,i) + 2*u(j,i) + u(j+1,i))/(dy^2))) - (v(j,i)*((u(j-1,i) - u(j+1,i))/(2*dy)))) + u(j,i-1);            change_u = u_i - u(j,i+1);            u(j,i+1) = u_i + (alphau * change_u);            v_j = v(j+1,i);                   v(j,i+1) = v(j-1,i+1) - dy/2/dx*(u(j,i+1)-u(j,i)+u(j-1,i+1)-u(j-1,i));            change_v = v_j - v(j,i+1);            v(j,i+1)= v_j + (alphav * change_v);            diff_u = [diff_u change_u];            diff_v = [diff_v change_v];        end    end    diff_U = max(abs(diff_u))    diff_V = max(abs(diff_v))    diff_u_max = [diff_u_max diff_U];    diff_v_max = [diff_v_max diff_V];    diff = [diff_U diff_V];    max_diff = max(diff);        %if max_diff < tol    %    z = 0; % I dont think this is right. Want max_diff < tol then iterations = 0 so it stops iterating    %end        % WANT TO PLOT THE CHANGE IN u TO SHOW IT CONVERGES   end

#### Best Answer

• Colin - outside of the while loop, just do
plot(diff_u);
But is that what you really want to plot? Your comment
%if max_diff < tol%    z = 0; % I dont think this is right. Want max_diff < tol then iterations = 0 so it stops iterating%end    
where
diff = [diff_U diff_V];max_diff = max(diff);
also includes a v. Do you want to plot diff_v instead? Or max_diff? Also, if you want to exit the while loop, just do
if abs(max_diff) < tol    break;end