9
$\begingroup$

I am new to Mathematica, still trying to familiarise myself with the language.

I have a list: {2,3,4}. How can I change it to {{1,1},{1,1,1},{1,1,1,1}}?

$\endgroup$
10
$\begingroup$

You can do it like this for example:

ConstantArray[1,#]&/@{2,3,4}

{{1, 1}, {1, 1, 1}, {1, 1, 1, 1}}

$\endgroup$
  • $\begingroup$ That's perfect works! Thank you! $\endgroup$ – Yubao Deng Aug 26 '18 at 23:07
  • 1
    $\begingroup$ other options, just for fun: ArrayReshape[{1}, {#}, 1] & /@ {2, 3, 4}, PadRight[{1}, #, 1] & /@ {2, 3, 4}, Table[1, #] & /@ {2, 3, 4}, ... $\endgroup$ – AccidentalFourierTransform Aug 27 '18 at 1:51
7
$\begingroup$

Here's another way:

list = {2, 3, 4};
Sign[Range[list]]
{{1, 1}, {1, 1, 1}, {1, 1, 1, 1}}

(with a little simplification from @AccidentalFourierTransform)

$\endgroup$
  • 2
    $\begingroup$ simpler: Sign[Range[list]], or 1 + 0 Range[{2, 3, 4}]. $\endgroup$ – AccidentalFourierTransform Aug 27 '18 at 1:51
  • $\begingroup$ @bill s, Unitize seems to be cleaner ))). $\endgroup$ – garej Aug 27 '18 at 4:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.