MATLAB Answers

0

Nested for loop not iterating

Asked by Brenton Hirao on 10 Oct 2019
Latest activity Commented on by per isakson
on 10 Oct 2019
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 Comments

Daniel M
on 10 Oct 2019
You're trying to access the jth element of b_p, but it is only length 1.
per isakson
on 10 Oct 2019
Was there an error message? What did it say?

Sign in to comment.

1 Answer

Answer by per isakson
on 10 Oct 2019

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;

  0 Comments

Sign in to comment.