%% Listing 4.1 (ch4ex1.m) clear; close all; % set s to zero so that 1/n^2 can be repeatedly added to it s=0; N=10000; % set the upper limit of the sum for n=1:N % start of the loop s = s + 1/n^2; % add 1/n^2 to s each iteration end % end of the loop fprintf(' Sum = %g \n',s) % print the answer %% Listing 4.4 (ch4ex4.m) clear; close all; a=1; b=3; if a>0 c=1 %Ifaispositivesetcto1 else c=0 %if a is 0 or negative, set c to zero end %% % if either a or b is non-negative, add them to obtain c; % otherwise multiply a and b to obtain c if a>=0 | b>=0 % either non-negative c=a+b else c=a*b % otherwise multiply them to obtain c end %% Listing 4.5 (ch4ex5.m) clear; close all; term=1 % load the first term in the sum, 1/1^2=1 s=term; % load s with this first term % start of the loop - set a counter n to one n=1; while term > 0.001 % loop until term drops below 1e-10 n=n+1; % add 1 to n so that it will count: 2,3,4,5,... term=1/n^2; % calculate the next term to add s=s+term; % add 1/n^2 to s until the condition is met end % end of the loop fprintf(' Sum = %g \n',s) %% Listing 4.6 (ch4ex6.m) clear; close all; term=1; % load the first term in the sum, 1/1^2=1 s=term; % load s with this first term % start of the loop - set a counter n to one n=1; while term > 1e-100 % set a ridiculously small term. % Don't really do this, as you % only have 15 digits of precision. n=n+1; % add 1 to n so that it will count: 2,3,4,5,... term=1/n^2; s=s+term; if n>1000 break end end % end of the loop fprintf(' Sum = %g \n',s) %% Listing 7.4 (SquareWell.m) %function [x,psi,E] = SquareWell(n,a,NPoints) % Calculate the energy and wavefunction for an % electron in an infinite square well % % Inputs: n is the energy level; must be a positive integer % a is the well width in nanometers % NPoints is the number of points in the x grid % % Outputs: x is the grid for the plot, measured in nanometers % psi is the normalized wave function % E is the energy of the state in electron-volts % Make the x-grid xmin = 0; xmax = a; x = linspace(xmin,xmax,NPoints); % Wave number for this energy level k = n * pi / a; % Calculate the wave function psi = sqrt(2/a) * sin(k*x); global hbar m % Calculate energy in electron-volts E = n^2*pi^2*hbar^2 / (2*m*(a*1e-9)^2) / 1.6e-19; end %% Listing 7.5 (ch7ex5.m) clear; close all; global hbar m % Constants in MKS units hbar = 1.05e-34; m=9.11e-31; % remember that n must be a positive integer n=3; % Set the width to an Angstrom a=0.1; % Get the values [x,psi,Energy] = SquareWell(n,a,100); % Make the plot and label it plot(x,psi) s=sprintf('\\Psi_%g(x); a=%g nm; Energy=%g eV',n,a,Energy); title(s); xlabel('x (nm)'); ylabel('\Psi(x)');