Effacer les filtres
Effacer les filtres

How to store all outputs from this nested for loop

2 vues (au cours des 30 derniers jours)
Leo Tu
Leo Tu le 9 Juil 2021
Commenté : Leo Tu le 9 Juil 2021
I have this for loop which goes through 3 different variables. I need to record all outputs so that I can plot the 3 variables and the outputs as a 3D colour surface plot similar to the second plot here https://www.mathworks.com/help/matlab/ref/surf.html
At the moment it only gives the last output so if someone can point me in the right direction to gettiing all outputs.
for s=0:9 % Variable 1
for om=0.1:0.1:1 % Variable 2
for mu=0.1:0.1:1 % Variable 3
nll = mylikelihood(s,om,mu); % This is a function I made.
end
end
end
Also if anyone could see how I can vectorise the code so that it runs faster that would be appreciated.
  2 commentaires
Walter Roberson
Walter Roberson le 9 Juil 2021
That code cannot be vectorized unless your function can be vectorized, but you did not show the code for your function so we do not know what can be done with it.
Leo Tu
Leo Tu le 9 Juil 2021
Thank you @Walter Roberson, the function is quite long as it contains a function itself and requires the temperatures vector attached. I'm not sure if it can be vectorized any further.
function nll = mylikelihood(s,om,mu)
% 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
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); % this function can be seen below
t = max(s)+1:numel(AT);
for ti = 1:numel(t)
k = abs(s:-1:(s-t(ti)+1));
id = ((t(ti)-1):-1:0)+1;
lambda(t(ti)) = mu+sum(om.^k.*AT(id))/sum(om.^k);
% store all the results
end
nll = 0;
nll = nll - (r(ti).*log(lambda(t(ti)))) + (lambda(t(ti)));
end
function r = mypoiss(s,om,mu)
% output; r is synthetic time series for number of cases
% input; s is lag, om is decay rate, mu is baseline rate
% T is temperatures, t = time in days
load("Temperature.mat")
T = T'; % from column vector to row vector
AT = T-min(T); % this is the adjusted positive temperatures
for t=s+1:length(AT)
k = abs(s:-1:(s-t+1));
id=[(t-1):-1:0]+1;
lambda(t) = mu+sum(om.^k.*AT(id))/sum(om.^k);
end
r = poissrnd(lambda);

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 9 Juil 2021
Vs = 0:9; % Variable 1
Vom = 0.1:0.1:1; % Variable 2
Vmu = 0.1:0.1:1; % Variable 3
Ns = numel(Vs);
Nom = numel(Vom);
Nmu = numel(Vmu);
nll = nan(Ns,Nom,Nmu);
for k1 = 1:Ns
for k2 = 1:Nom
for k3 = 1:Nmu
nll(k1,k2,k3) = mylikelihood(Vs(k1),Vom(k2),Vmu(k3));
end
end
end

Plus de réponses (0)

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by