help regarding conditional if statement

조회 수: 1 (최근 30일)
Prince Igweze
Prince Igweze 2019년 12월 9일
답변: Jakob B. Nielsen 2019년 12월 9일
How do i write the code for the if statement such that if the condition fails it maintains the previous model (m)
theta = [0:90]';
M = [1800;400;1850;0.2;0.5]';
Dm = ref_coeff(M,theta);
Ds = Dm + (0.02*randn(size(Dm)) + 0);
T = [logspace(3,0,200)]';
Mint = M;
for i = 1 : length(T)
Er = ((abs(Ds - Dm)).^2)./(2*(0.02^2));
E = sum(Er); % Initial Energy State%
n1 = 25 .* randn(1,1) + 1800;
m1 = 1500 + n1*(2000 - 1500); % Perturbation in Model Parameters%
n2 = 50 .* randn(1,1) + 400;
m2 = 0 + n2*(1000 - 0);
n3 = 50 .* randn(1,1) + 1850;
m3 = 1200 + n3*(2200 - 1200);
n4 = 0.05 .* randn(1,1) + 0.2;
m4 = 0 + n4*(1 - 0);
n5 = 0.05 .* randn(1,1) + 0.5;
m5 = 0 + n5*(1 - 0);
m = [m1;m2;m3;m4;m5]';
dm = ref_coeff(m,theta);
ds = dm + (0.02*randn(size(dm)) + 0);
En1 = ((abs(ds - dm)).^2)./(2*(0.02)^2);
En = sum(En1); % New Energy State%
Ec = En - E;
if Ec >= 0
Mint = m;
z(i,:) = Mint
elseif (exp(Ec/T(i))) >= randn(0,1)
Mint = m;
else
???????
end
end
  댓글 수: 1
Prince Igweze
Prince Igweze 2019년 12월 9일
Also im not really sure if my method of storing all iterations of the model(m) is efficently correct. Help

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

답변 (1개)

Jakob B. Nielsen
Jakob B. Nielsen 2019년 12월 9일
At a glance, you could put m_old=m in the very top of your for statement, which will be the model of your most recent iteration. Then, if the bottom condition fails, you simply flip it, m=m_old.
That will of course give a problem on the very first iteration, so put in a condition that when i=1 you skip that comparison.
I dont know if this is what you want?
theta = [0:90]';
M = [1800;400;1850;0.2;0.5]';
Dm = ref_coeff(M,theta);
Ds = Dm + (0.02*randn(size(Dm)) + 0);
T = [logspace(3,0,200)]';
Mint = M;
for i = 1 : length(T)
if i==1
%Skip if its the first iteration, where m does not exist yet
else
m_old=m;
end
Er = ((abs(Ds - Dm)).^2)./(2*(0.02^2));
E = sum(Er); % Initial Energy State%
n1 = 25 .* randn(1,1) + 1800;
m1 = 1500 + n1*(2000 - 1500); % Perturbation in Model Parameters%
n2 = 50 .* randn(1,1) + 400;
m2 = 0 + n2*(1000 - 0);
n3 = 50 .* randn(1,1) + 1850;
m3 = 1200 + n3*(2200 - 1200);
n4 = 0.05 .* randn(1,1) + 0.2;
m4 = 0 + n4*(1 - 0);
n5 = 0.05 .* randn(1,1) + 0.5;
m5 = 0 + n5*(1 - 0);
m = [m1;m2;m3;m4;m5]';
dm = ref_coeff(m,theta);
ds = dm + (0.02*randn(size(dm)) + 0);
En1 = ((abs(ds - dm)).^2)./(2*(0.02)^2);
En = sum(En1); % New Energy State%
Ec = En - E;
if Ec >= 0
Mint = m;
z(i,:) = Mint
elseif (exp(Ec/T(i))) >= randn(0,1)
Mint = m;
else
if i==1
%skip once again
else
m=m_old;
end
end
end

카테고리

Help CenterFile Exchange에서 General Applications에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by