Message Boards Message Boards

0
|
2161 Views
|
6 Replies
|
4 Total Likes
View groups...
Share
Share this post:

How to make absolute value of an arbitrary column?

Posted 2 years ago

Let's say we have a list m={{1,-1},{-2,2},{3,-3}}. I want to make an absolute value of every second element of that list. So the final result should be mabsolute={{1,1},{-2,2},{3,3}}. I tried with the following command:

Map[Abs,m,2]

Unfortunately, I received a list in which every element was taken with absolute value.

Thank you for your attention and help.

POSTED BY: Maciej Kozyra
6 Replies
Posted 2 years ago

Thank you kindly for each answer. It's an honour to be a member of such a wonderful community!

MK

POSTED BY: Maciej Kozyra

You can also use replacement rules, if you find that style more readable:

m = {{1, -1}, {-2, 2}, {3, -3}};
m /. {x_, y_?NumberQ} :> {x, Abs[y]}

This may be slower for very large lists.

POSTED BY: Gianluca Gorni

Maciej,

You can also use Map[] by defining a function that only operates on the second item. m is a list of pairs in the form {first, second}. You create a function that returns a list of {first, Abs[second]}:

Map[{#[[1]], f[#[[2]]]} &, m]

or

Map[{#[[1]], Abs[#[[2]]]} &, m]

in your case.

Regards,

Neil

POSTED BY: Neil Singer
Posted 2 years ago

How to make absolute value of a arbitrary column?

POSTED BY: Maciej Kozyra
Posted 2 years ago

Try MapAt.

test = Partition[Range[8], 2]
(*{{1, 2}, {3, 4}, {5, 6}, {7, 8}}*)

MapAt[f, test, {All, 1}] (*apply to first column*)
(*{{f[1], 2}, {f[3], 4}, {f[5], 6}, {f[7], 8}}*)

MapAt[f, test, {2 ;; ;; 2}] (*apply to every other starting at position 2*)
(*{{1, 2}, f[{3, 4}], {5, 6}, f[{7, 8}]}*)

MapAt[f, test, {3, 1}] (*apply to specific location*)
(*{{1, 2}, {3, 4}, {f[5], 6}, {7, 8}}*)

So, since you want Abs applied to the second column:

m = {{1, -1}, {-2, 2}, {3, -3}};
MapAt[Abs, m, {All, 2}]
(*{{1, 1}, {-2, 2}, {3, 3}}*)
POSTED BY: Eric Rimbey
Posted 2 years ago

Thank you kindly for your help! I'm very grateful to you for exhaustive answer.

POSTED BY: Maciej Kozyra
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