Short answer: They are similar enough to substitute for cooking, but you shouldn't subsititute when baking.
Long answer: Butter is made of milk fat and starts with a 30% fat mixture called cream. The cream is beaten until it breaks emulsion and separates the fat and water. The result is buttermilk (water) and butter (about 80% fat with emulsion of 20% water). Margarine on the other hand is vegetable oil that is hydrogenated to trans-fat to solidify. Butter flavoring and color are added to mimic butter.
The difference is that the fatty acid composition is very different between the two. Butter is very diverse as it exist naturally. Margarine is much more homogenous in it's fatty acid profile.
Within fats, there are differences in chain length. Some are short like this: >C-/\/\/\/ while others are longer >C-/\/\/\/\/\/\/\/\/\/. Short fatty acids melt at lower temperatures while the longer ones melt at higher temperatures.
In butter, there is a range of different types of fats, some short and some long. During baking, as the mixture heats some of the butter melts and some of it stays solid at low temperatures. As the temperature rises, more and more of the butter melts. This is manipulated to produce different textures within baked goods. The remaining solid butter early in the baking process can provide support while the melted portions coat or penetrate before the mixture hardens...and so forth.
In margarine, the more uniform fatty acid length all melts within a similar temperature. So it remains solid early in baking and then all melts at once. Sometimes this is desirable as in pie crusts. The sudden melting of crisco shortening leaves a gap where it once was and within the crust are many gaps which make the crust surrounding it appear "flaky" as it is separated from the nearest crust pieces where the fat once was. Here's an illustration: F= fat, C= crustFCFCFCFCFCFC + baking ->
_C C C C C C
C C C C C C
and the crust can now easily be torn, appearing flaky. It really depends on the recipe which is appropriate. In baking, if it says to use butter, you should use it and so forth with margarine. Just follow directions on this one.
In cooking however, fat rarely is needed for structural support, but used for flavoring, which butter and margarine can both do. There are differences in flavor, but if you substitute one for the other in stir-fry or fried rice, the results will be less drastic.
Then there's the whole debate over trans-fat vs saturated fat... which is a whole other topic in itself... there's a lot of points and counterpoints and I'd rather not bring it up here.