write a function that calculates the distance traveled in a straight line; inputs times and a vector of velocity values at the corresponding times and outputs the total distance traveled as a scalar in matlab

main.m
function totalDistance = calculateTotalDistance(times, velocities)
    % Check if input sizes are the same
    if length(times) ~= length(velocities)
        error('Input sizes must be the same');
    end

    % Initialize variables
    totalDistance = 0;
    numPoints = length(times);

    % Calculate total distance
    for i = 2:numPoints
        timeInterval = times(i) - times(i-1);
        avgVelocity = (velocities(i) + velocities(i-1)) / 2;
        distance = avgVelocity * timeInterval;
        totalDistance = totalDistance + distance;
    end
end
559 chars
19 lines

related categories

gistlibby LogSnag