To programmatically assign an image to a post as the featured image you need to use the function set_post_thumbnail(), which takes two parameters a post ID and the attachment ID.
set_post_thumbnail( $postId, $attachmentId );