I don't think you need to loop over b values here. Can't this be vectorized?