I don't understand why this code works:
% Important constants and variables. All units SI unless noted otherwise.
k = 8.99e9;q = 1e-6; % Point charge magnitude
Q = 1e-3; % Rod charge magnitude
L = 1; % Rod length
xPoint = 0.25; % Distance from center of rod to point charge
N = 10;% Initialize the force
f = [0, 0];% Calculate the magnitude of each charge in the rod given N chunks
dQ = Q/N;% Calculate the separation between charges
% (Depends on method, value is incorrect)
chargeSep = L/N;% y coordinate of top charge (Depends on method, value is incorrect)
y = L/2 - chargeSep/2;for i = 1:N % For the given coordinates, find the vector to the point charge
% from the ith charge on the rod (values are incorrect)
rVec = [xPoint, -y]; rMag = sqrt(xPoint^2 + y^2); rHat = rVec/rMag; % Calculate the force for this particular point charge using
% Coulomb's law
dF = k*dQ*q/rMag^2 * rHat; % Add to the total force
f = f + dF; % Advance to the next charge on the rod
y = y - chargeSep;endf
(f = 64.3779 0)
While this one doesn't
% Important constants and variables. All units SI unless noted otherwise.k = 8.99e9;q = 1e-6; % Point charge magnitudeQ = 1e-3; % Rod charge magnitudeL = 1; % Rod lengthxPoint = 0.25; % Distance from center of rod to point chargerodForce(10)% Make a function that calculates the force on the rod given the number of
% chunks. For now, we will make the only input the number of chunks
function f = rodForce(N) % Declare global variables
global Q global xPoint global q global L global k % Initialize the force f = [0, 0]; % Calculate the magnitude of each charge in the rod given N chunks dQ = Q/N; % Calculate the separation between charges % (Depends on method, value is incorrect) chargeSep = L/N; % y coordinate of top charge (Depends on method, value is incorrect) y = L/2 - chargeSep/2; for i = 1:N % For the given coordinates, find the vector to the point charge % from the ith charge on the rod (values are incorrect) rVec = [xPoint, -y]; rMag = sqrt(xPoint^2 + y^2); rHat = rVec/rMag; % Calculate the force for this particular point charge using % Coulomb's law dF = k*dQ*q/rMag^2 * rHat; % Add to the total force f = f + dF; % Advance to the next charge on the rod y = y - chargeSep; endend
When I examine the output it seems that my variables dQ, chargeSep, etc (those calculated within the function) are not used. This is maddening.
Best Answer