MATLAB: How to fix this

array indices;energyerrors

dw = 0.01;
w = -31.4:dw:31.4;
dt = 0.1;
t = -100:dt:100;
G_omega = @(w) 2.*((abs(w)>=5)-(abs(w)>=10));
H_omega = @(w) (5.*abs(w)).*((w>=-20)&(w<=20));
M_omega = @(w) abs(G_omega(w)) .* abs(H_omega(w));
m_t = zeros(size(t));
for ii=1:length(w)
m_t = m_t + M_omega(w(ii))*exp(j*w(ii)*t)*dw/2/pi;
end
energy=trapz(t,abs(m_t(t)).^2)
When running this I get the error "Array indices must be positive integers or logical values" and I'm not completely sure why? The error comes from when I'm calculating the energy. I seem to have this issue often when I'm creating an array from a for loop like this and then to do anything with it other than plot it. Any suggestions would be much appreciated.

Best Answer

You are using t as an index to m_t, but that contains negative values. (in the call to trapz)
I suspect you want to run the line below instead.
energy=trapz(t,abs(m_t).^2);