How to store all outputs from this nested for loop

조회 수: 7 (최근 30일)
Leo Tu
Leo Tu 2021년 7월 9일
댓글: Leo Tu 2021년 7월 9일
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
Walter Roberson
Walter Roberson 2021년 7월 9일
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 2021년 7월 9일
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);

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2021년 7월 9일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by