MATLAB: Trouble with plotting a for loop

for loopplotting

I have some trouble with plotting a for loop.
P1 = 1; %The sound pressure in Pa at 1 m range
f = 1e3;% The frequency, Hz
w = 2*pi*f; % Angular frequency, radHz (Omega)
c = 340; % Sound speed, m/s
lambda = c/f; % Wavelength, m
k = 2*pi/lambda; % Wave number, m-1
r = 0.1:0.01:10; % range vector, interspaced by 1 cm
fs = 1e5;
t = [0 : 1/fs : 10/f]; %time scale, running over ten periods
p0 = 1e-6; % ref pressure, μPa
Loop to find the pressure at time and distance
for i=1:length(t)
p(i,:) = (P1./r).*sin(w*t(i)-k*r);
end
I am trying to plot the intensity (in decibels re 1 μPa rms) as a function of range within the loop.
for i=1:length(t)
prms=rms(p);
intensity = 20*log10((prms)/p0);
plot(r,intensity(i,:))
xlabel('m');
ylabel('dB re 1 μPa rms')
axis([0 max(r) 0 160])
pause(0.1)
end
Unfortunately, I don't see the plot of the intensity (in decibels re 1 μPa rms) as a function of range moving at all.
Does anyone know how I could make the loop work? I was hoping to plot the intensity as a function of range within the loop.
Thanks in advance!

Best Answer

Why are you applying rms() to all of p each cycle? That repeats calculation needlessly.
By default rms operates along the first dimension. Your first dimension is time, so you are left with a vector the same length as r. But then you try to index it at i which goes to legnth(t) rather than length( r).