Message Boards Message Boards

0
|
3699 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Subtracting two lists of unequal length?

Posted 3 years ago

Hello everyone,

Broadly, I am trying to subtract two lists of unequal length. More specifically, I am hoping to find a way to determine which list has the least number of elements (N) and subsequently find the absolute difference between the first N elements of the two lists.

For instance, imagine t1 has 3 elements {0, 1, 2} and list t2 has 4 elements {0, 1, 2, 3}. I am hoping to do something like the following:

Abs[t1 - t2] = Abs[{0,1,2} - {0,1,2}] = {0,0,0}.

Is there an efficient way to do this?

Thank you,

Alex

Attachments:
POSTED BY: Alex L
2 Replies
Posted 3 years ago

Hi Alex,

Here is one way using the example from the attached notebook

t1 = {0, 5, 4, 6, 7}
t2 = {0, 1, 3}

Abs[Subtract @@ PadRight[{t2, t1}]][[;; Min[Length@t1, Length@t2]]]
(* {0, 4, 1} *)

The order does not matter

Abs[Subtract @@ PadRight[{t1, t2}]][[;; Min[Length@t1, Length@t2]]]
(* {0, 4, 1} *)

I have not done any timing to see how efficient it is. How long are the lists you are working with?

POSTED BY: Rohit Namjoshi
Posted 3 years ago

This is such a cool way to do it; wish I had thought of that! Thank you so much! And, the lists vary from about 8-15 elements, so I think this will work great.

Alex

POSTED BY: Alex L
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