function main() % Constants for test a = 3; b = 5; d = 12; w = 1; % Testing all possible bridge positions (0 to d) [bridge_pos, path_distance] = fminbnd(@(x) calc_path(a,b,w,d,x), 0, d) end % a : vertical distance from town A to the river % b : vertical distance from town B to the river % w : width of the river % d : horizontal distance from town A to town B % x : horizontal distance of the bridge from town A function path_distance = calc_path(a, b, w, d, x) path_distance = sqrt(x^2+a^2) + sqrt((d-x)^2+b^2) + w; end