Efficient Optimization for Linear Dynamical Systems with Applications to Clustering and Sparse Coding