function [x_updated, P_updated, K] = kalman_update(x_pred, P_pred, z, H, R)
%KALMAN_UPDATE Performs the correction (update) step of the linear Kalman filter.
%
% Inputs:
%   x_pred  - Predicted state estimate (nx1 vector)
%   P_pred  - Predicted state covariance (nxn matrix)
%   z       - Measurement vector (mx1 vector)
%   H       - Measurement matrix (mxn matrix)
%   R       - Measurement noise covariance (mxm matrix)
%
% Outputs:
%   x_updated - Updated state estimate (nx1 vector)
%   P_updated - Updated state covariance (nxn matrix)
%   K         - Kalman gain (nxm matrix)

% Compute the Kalman gain
S = H * P_pred * H' + R;       % Innovation (residual) covariance
K = P_pred * H' / S;           % Kalman gain

% Compute the innovation (residual)
beta = z - H * x_pred;

% Update the state estimate
x_updated = x_pred + K * beta;

% Update the estimate covariance
I = eye(size(P_pred));
P_updated = (I - K * H) * P_pred;

end
