k_1=100;
while (abs(k_1-k)>0.0001)
k=k_1;
y_hat=x*b;
r=(y-y_hat);
s_squared=norm(r)/(n-p-1);
k_1=p*s_squared/(b'*b);
pseudo = sqrt(k_1) * eye(p);
x_ridge = [x;pseudo];
y_ridge = [y;zeros(p,1)];
b = x_ridge\y_ridge;
end
I have a piece of code which seeks to iterate the k value until it converges (i.e. subsequent iterations are less than a certain distance apart). The while loop has to run at least once: the initial k_{t} value has already been calculated, the first iteration of the while loop provides the first k_{t+1} and in theory this could be within the distance specified in the while loop.
The code above works but is inefficient. So I'm really looking for best practice/efficiency gains.
Currently k is set to k_1 on the first line. This is fine if more iterations are required, but if the first k_1 is convergent then having the code set up this way will necessitate an unwarranted additional loop.
Ideally I'd have a structure that is do_while rather than while_do as it is set up in Matlab. That way it would calculate the initial k_{t+1} and then test the condition. So that if it is convergent on the first loop (and indeed a lot of them do seem to be) then it will only loop once.
I could work around this by using an if structure and telling it to break out if the convergence criteria has been met and setting k_t=k_{t+1} otherwise. But this seems rather combersome get around that might actually increase the computational burden, not to mention that the test for convergence will be conducted twice every loop when it need only be done once.
What is the best matlab solution in this situation?
whileloop "works but is inefficient." Is your question essentially about how to avoid unnecessary computation on the last iteration? On thing you can try to do to re-order your calculation is take some of the bits for the first iteration outside thewhileloop and evaluate them before.whileloop. Since your example code isn't runnable, I'm not going to be able to play around myself to see if such a thing is possible.