| Author |
Comment/Response |
Randy Silvers
|
05/29/08 8:08pm
Joel, you are close. You're right in that there is a problem with using brackets. Only use brackets to enclose arguments to a function.
Here, you want a function applying to two elements, each element being drawn from a separate list. Thus, both lists act as one argument to the Map function, and so need to be enclosed in brackets.
As you have it, Map at level 2 only will yield two lists, one list of the function evaluated at each element of matrixa, the other list of the function evaluated at each element of matrixb. Hardly what you want.
One way to solve your problem is to use MapThread.
MapThread[If[#1!=0,#1,#2]&,{matrixa,matrixb},2]
works as you desire.
It's a lot of practice, but it's worthwhile to understand the difference between Map, Apply, Thread, and MapThread.
Another way, using Map, would be to use Transpose to create a matrix of paired elements. If you had matrixab={{0,a},{1,b},{0,c},{2,d}} then
Map[If[#[[1]]!=0,#[[1]],#[[2]]]&,matrixab]
Hope that helps, at least to clarify the difference between Map and MapThread.
URL: sirandol@deakin.edu.au, |
|