How to write a function and create 3 nested loop then evaluate an integral?

25 views (last 30 days)
Fatin on 6 Oct 2014
Commented: Fatin on 7 Oct 2014
I have a matrix of Density values (rho) of size 15x121 , I have lambda is a row of size 1x20 and the values of lambda between 0 and 2 .I want to evaluate the following function : f(t)= [exp(-lambda*t)*rho] then I want the integral of f with respect to t and the integral from t_j-1 to t_j The values of t is between 0 and 1 , and those are 15 intervals (( i.e 15 intervals [t_j-1,t_j] ))
Thanks for any help

Mike Hosea on 6 Oct 2014
Edited: Mike Hosea on 6 Oct 2014
I'm not sure if there is supposed to be a relationship between the t intervals and rho, or whether the fact that there are 15 rows and 15 intervals is a coincidence. I'm assuming it's a coincidence, but hopefully you will see how to proceed from the principle of the following.
I've made up some data just so it would run.
lambda = linspace(0,2,17);
rho = rand(15,121);
t = linspace(0,1,16);
Here's brute force and ignorance, so to speak, with nested loops and collecting each (scalar) integral in a 4-D array.
f = @(t,lambda,rho)exp(-lambda*t)*rho;
Q = zeros([size(rho),numel(lambda),numel(t)-1]);
for i1 = 1:size(rho,1)
for i2 = 1:size(rho,2)
for i3 = 1:numel(lambda)
for j = 1:numel(t)-1
Q(i1,i2,i3,j) = integral(@(x)f(x,lambda(i3),rho(i1,i2)),t(j),t(j)+1);
end
end
end
end
We can improve on this by using the 'ArrayValued' option of INTEGRAL, treating rho as a matrix input to the qs function rather than a scalar.
f = @(t,lambda,rho)exp(-lambda*t)*rho;
Q = zeros([size(rho),numel(lambda),numel(t)-1]);
for i3 = 1:numel(lambda)
for j = 1:numel(t)-1
Q(:,:,i3,j) = integral(@(x)f(x,lambda(i3),rho),t(j),t(j)+1,'ArrayValued',true);
end
end
But why not let lambda be an array in qs as well? We just need to be clever so that we do every combination of rho elements and lambda elements. Here I've used an outer product of vectors and reshaped it.
f = @(t,lambda,rho)reshape(rho(:)*exp(-t*lambda(:).'),[size(rho),numel(lambda)]);
Q = zeros([size(rho),numel(lambda),numel(t)-1]);
for j = 1:numel(t)-1
Q(:,:,:,j) = integral(@(x)f(x,lambda,rho),t(j),t(j)+1,'ArrayValued',true);
end
Now if each interval of t needs only one row of rho, it's a slightly different problem. But we can do that, too.
Fatin on 7 Oct 2014
This is very professional answer , i will try that . I am a new user to MATLAB, I liked it so much and I am learning fast ,but still too many command I don't know how to use it . Thank you for your help.

yonatan gerufi on 6 Oct 2014
Edited: yonatan gerufi on 6 Oct 2014
for 3 dim integral use:
integral3
Fatin on 6 Oct 2014
It is just one integral , but how to write the function f(t)= [exp(-lambda*t)*rho] and call it in the 3 loops for lambda and t and each raw of the matrix rho , then evaluate the integral of f with respect to t.