How to use meshgrid to replace the nested for loops

4 次查看(过去 30 天)
I have the following script
load("Temperature.mat") % labelled T
T = T'; % from column vector to row vector
AT = T-min(T); % this is the adjusted positive temperatures
r = mypoiss(5,0.5,1,AT); % r is a 1x12504 double, for simpilicity let it contain the values 1:12504
s = 0:3; % lag range
om = 0.1:0.1:0.4; % decay rate range
mu = 0.1:0.1:0.4; % baseline rate range
Ns = numel(s);
Nom = numel(om);
Nmu = numel(mu);
nll = nan(Ns,Nom,Nmu);
for si = 1:Ns
for omi = 1:Nom
for mui = 1:Nmu
nll(si,omi,mui) = mylikelihood(s(si),om(omi),mu(mui),AT,r);
end
end
end
[ss,omm,muu]=meshgrid(s,om,mu);
scatter3(ss(:),omm(:),muu(:),[],nll(:))
and the following function
function nll = mylikelihood(s,om,mu,AT,r)
% output; nll is the negative log likelihood
% input; s is lag, om is decay rate, mu is baseline rate
% T is temperatures, t = time in days
t = max(s)+1:numel(AT);
nll = 0;
for ti = 1:numel(t)
k = abs(s:-1:(s-t(ti)+1));
id = ((t(ti)-1):-1:0)+1;
lambda = mu+sum(om.^k.*AT(id))/sum(om.^k);
% store all the results
nll = nll - (r(ti).*log(lambda)) + (lambda);
end
Is it possible to use meshgrid to replace the use of the two nested for loops (for omi and mui) so that I am left with just the following in the loop bit
for si = 1:Ns % here I want to just be looping for values of si
nll = % ... etc
end
If anyone can point me in the right direction for using meshgrid to do this that would be helpful, thank you.

采纳的回答

Leo Tu
Leo Tu 2021-7-13
New script:
load("Temperature.mat")
T = T'; % from column vector to row vector
AT = T-min(T); % this is the adjusted positive temperatures
r = mypoiss(5,0.5,1,AT);
s = 0:3; % lag range
om = 0.1:0.1:0.4; % decay rate range
mu = 0.1:0.1:0.4; % baseline rate range
Ns = numel(s);
Nom = numel(om);
Nmu = numel(mu);
nll = nan(Ns,Nom,Nmu);
for si = 1:Ns
omi = 1:Nom;
mui = 1:Nmu;
nll(si,omi,mui) = mylikelihood2(s(si),om,mu,AT,r,Nom,Nmu);
end
[ss,omm,muu]=meshgrid(s,om,mu);
scatter3(ss(:),omm(:),muu(:),[],nll(:))
New function:
function nll = mylikelihood2(s,om,mu,AT,r,Nom,Nmu)
% output; nll is the negative log likelihood
% input; s is lag, om is decay rate, mu is baseline rate
% T is temperatures, t = time in days
t = max(s)+1:numel(AT);
[omm,muu] = meshgrid(om,mu);
nll = zeros(Nom,Nmu);
for ti = 1:numel(t)
k = abs(s:-1:(s-t(ti)+1));
id = ((t(ti)-1):-1:0)+1;
lambda = muu+sum(omm(:).^k.*AT(id))/sum(omm(:).^k);
% store all the results
nll = nll - (r(ti).*log(lambda)) + (lambda);
end

更多回答(0 个)

产品


版本

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by