Tag Info

New answers tagged

5

why not simply: x2[n_, a_] := PadRight[x, n, 0] + (SparseArray[n -> a] // Normal) x2[10,5] (*{1, 2, 3, 4, 0, 0, 0, 0, 0, 5}*)


2

Playing with UpValues: Unprotect@Part; Part/:Set[Part[list_,part_],value_]:= list=MapAt[value&,If[Length@list<part,PadRight[list,part],list],part] Protect@Part; Now you can do: l = {1, 2, 3, 4}; l[[10]] = "x" and get: {1, 2, 3, 4, 0, 0, 0, 0, 0, "xx"} Important: I do not recommend to Unprotect system symbols.


8

Bear in mind that I'm not completely sure what you are calculating, here is my 5 cents towards what can help you get a better performance. I haven't benched marked the MATLAB code on my system, but the changes implemented in Mathematica lead to a runtime decrease from 78.036 s down to to 0.171 s. The slowing factors where mainly that you handle a lot of ...


5

More for my own personal edification and possible enlightenment from more experienced users, here are two other possibilities. First, Use a sparse array with a size much larger than expected. a = Range@3; b = SparseArray[a, 10^7]; It results in a bit of overhead ByteCount /@ {a, b} (* {128, 720} *) Which decreases with increasing (initial) array size ...


4

test = {1, 2, 3} addEm[list_, position_, ele_] := Module[{tmp = Join[list, ConstantArray[0, position - Length@list]]}, tmp[[position]] = ele; tmp] addEm[test, 6, 55] (* {1, 2, 3, 0, 0, 55} *) You'll probably want to add sanity checks...



Top 50 recent answers are included