MATLAB Answers

## finding closest values in array

Asked by harley

### harley (view profile)

on 6 Aug 2013
Accepted Answer by Richard Brown

### Richard Brown (view profile)

Hello, want to locate a value from an pH array when closest to 4.756 and then locate the corresponding Vb value associated with that pH value. Any help would be appreciated. See last 2 lines.
format short
Kw = 1e-14;
Ka = 1.755388e-5;
pKa = 4.756;
%
Ca = 0.5;
Cb = 0.1;
Va = 100;
Vb = 0.05:0.05:2000;
Ma = (Ca * Va) / 1000;
Mb = (Cb .* Vb) ./ 1000;
for i = 1:length(Mb)
M_excess = Ma - Mb(i);
if abs(M_excess)<eps
Hplus = Ka * ((Ma_final * 0.999999) ./ Mb_final);
Vb_ev = Vb(i);
pH_ev = pH(end);
elseif M_excess > 0
Ma_final = (M_excess * 1000) ./ (Va + Vb(i));
Mb_final = (Mb(i) * 1000) ./ (Va + Vb(i));
Hplus = Ka * (Ma_final ./ Mb_final);
elseif M_excess < 0
OH = (M_excess * 1000 * (-1)) ./ (Va + Vb(i));
Hplus = Kw ./ OH;
end
pH(i) = -log10(Hplus);
end
%
pH_Mid_Pt2 = find pH value when closest to 4.756;
Vb_Mid_Pt2 = find corresponding Vb value at pH_Mid_Pt2;

#### 0 Comments

Sign in to comment.

## 1 Answer

Answer by Richard Brown

### Richard Brown (view profile)

on 6 Aug 2013
Accepted Answer

If I understand correctly, you want to find the pH value in your array closest to 4.756, and pull this value out, together with the corresponding Vb value. If that's right, this should do the trick.
[~, idx] = min(abs(pH - 4.756));
pH_Mid_Pt2 = pH(idx);
Vb_Mid_Pt2 = Vb(idx);

harley

### harley (view profile)

on 6 Aug 2013
thanks richard, a lot easier than the way i was trying.

Sign in to comment.