Reputation: 605
I am trying to use for loops to calculate the following formula:
However, since the number of elements for 't' and 'tau' are different, I'm not sure how to properly index the code.
This is what I have done so far:
t = [0:0.1:15];
tau = [0:2:10];
dtau = tau(2)-tau(1);
BB = 4*tau;
u = 2*t;
B = zeros(1,length(t));
for ii = 1:length(t)
for jj = 1:length(tau)
B(ii) = B(ii) + BB(jj)*u(ii-jj+1)*dtau;
end
end
To elaborate a bit more - the upper integration limit is the 't' in this case, so for every B(t) I would like to integrate from tau(0) to tau=t. Any suggestions? Thank you.
Upvotes: 0
Views: 166
Reputation: 45741
You are doing convolution so just use Matlab's built-in functions if you can i.e. conv
. But here is a loopy version for your understanding:
using your data
t = [0:0.1:15];
tau = [0:2:10];
dtau = tau(2)-tau(1);
BB = 4*tau;
u = 2*t;
B = zeros(1,length(t));
We flip u
and then slide it over `BB'. It's easiest to just pad BB with zeros so you don't have to deal with edges:
U = fliplr(u);
BB = [zeros(1,length(u)-1), BB, zeros(1,length(u)-1)];
for ii = 1:length(t) %//This should actually go to 21, I don't feel like working out why right now
B(ii) = sum(U.*BB(ii:(ii+length(u)-1)));
end
Upvotes: 3
Reputation: 1566
To answer your question:
If you want to do it like that, you only have to define tau
inside the for ii = 1:length(t)
loop, that's all.
So it would look something like this:
t = [0:0.1:15];
u = 2*t;
B = zeros(1,length(t));
for ii = 1:length(t)
tau = [0:0.2*ii:ii]
dtau = tau(2)-tau(1);
BB = 4*tau;
for jj = 1:length(tau)
B(ii) = B(ii) + BB(jj)*u(ii-jj+1)*dtau;
end
end
That being said, I think Dan's comment is on spot: unless you want to play with the parameters by yourself, you are performing a simple convolution there.
Upvotes: 2