Message Boards Message Boards

0
|
2037 Views
|
2 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Multiply part of a list

Posted 3 years ago

Consider the list

l={1,2,3,4,5,6,7}

I want to perform an operation on l such that I end up with

l={1,4,6,8,10,12,7}

I.e., multiply by 2 the

[[2;;-2]]

Part of l.

How can I do that?

I currently have the following way to do that:

ReplacePart[l, Range[2, Length[l - 1]] -> 2 l[[2 ;; -2]]]

But I wouldn't be surprised to learn that Mathematica can do that in a cleaner way.

Any suggestion would be helpful!

POSTED BY: Ehud Behar
2 Replies
Posted 3 years ago

Silly me

The straight forward way is simply to do

l[[2 ;; -2]] = 2 l[[2 ;; -2]]
(*{4, 6, 8, 10, 12}*)
l
(*{1, 4, 6, 8, 10, 12, 7}*)

It is the former output that made me think it doesn't work.

POSTED BY: Ehud Behar
Posted 3 years ago

Hi Ehud

One way

l = {1, 2, 3, 4, 5, 6, 7}

MapAt[2 # &, l, {2 ;; -2}]
(* {1, 4, 6, 8, 10, 12, 7} *)
POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract