Nested for loop not iterating

1 次查看(过去 30 天)
Brenton Hirao
Brenton Hirao 2019-10-10
评论: per isakson 2019-10-10
I have a nested for loop needed to do a gridsearch to do a linear fit of a model with two unknown constants. As far as I can tell, these for loops are not iterating because i and j both show a value of 1 in the workspace. What am I doing wrong?
Thanks for any help.
agrid=[1:0.1:100];
bgrid=[.5:.0001:1.5];
lenagrid=length(agrid);
lenbgrid=length(bgrid);
for i = 1:lenagrid
for j = 1:lenbgrid
a_p = agrid(i)
b_p=bgrid(j);
fhat(i,j)=(a_p(i))-(b_p(j)).*magrange;
TSE(i,j)=sum((fhat-magrange).^2);
end
end
  2 个评论
Daniel M
Daniel M 2019-10-10
You're trying to access the jth element of b_p, but it is only length 1.
per isakson
per isakson 2019-10-10
Was there an error message? What did it say?

请先登录,再进行评论。

回答(1 个)

per isakson
per isakson 2019-10-10
I'm just guessing. Replace
a_p = agrid(i)
b_p=bgrid(j);
fhat(i,j)=(a_p(i))-(b_p(j)).*magrange;
by
fhat(i,j) = ( agrid(i) - bgrid(i) ).*magrange;

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by