I have a list containing 500 rows, each of 37 elements; i.e., a 500 x 37 matrix.
My goal is to substract in each row each element from the first. My approach in mind is to call each list by a PureFunction and then to subtract the second element from the first, then the third from the first so in the end I would have a list with 500 sublists, each with 36 elements. I failed to figure out how to call single elements if, as in my case, the the list is called by a PureFunction. I also tried to work with slots, again failing to call the single elements of the already called list. I highly appreciat any help or comments!
Answer
If mat
is your matrix, the following should be fast:
mat . SparseArray[
{{1,_} -> 1, Band[{2,1}] -> -1},
Dimensions[mat][[2]]+{0,-1}
]
Addendum
Here is a brief speed comparison of the 4 suggested methods:
wreach[m_] := m[[All, 1]] - m[[All, 2 ;;]]
carl[m_] := m . SparseArray[
{{1, _} -> 1, Band[{2, 1}] -> -1},
Dimensions[m][[2]] + {0, -1}
]
goldberg[m_] := #1 - {##2} & @@@ m
tom[m_] := #[[1]] - #[[2 ;;]] & /@ m
A sample matrix:
mat = RandomReal[10^6, {10^5, 30}];
Speed comparison:
r1 = carl[mat]; // AbsoluteTiming
r2 = wreach[mat]; // AbsoluteTiming
r3 = goldberg[mat]; // AbsoluteTiming
r4 = tom[mat]; // AbsoluteTiming
r1 === r2 === r3 === r4
{0.013968, Null}
{0.029711, Null}
{1.4249, Null}
{0.346468, Null}
True
Comments
Post a Comment