Home > OS >  Subtract an array from another array based on elements in both columns
Subtract an array from another array based on elements in both columns

Time:11-09

I am looking for an efficient way to do this:

(a=1 2; 1 3; 2 3)  - b=(1 2; 2 3) = (c=1 3)

or:

a=nchoosek([1 2 3 4 5 6],2) - b=(1 2; 1 3; 2 4;3 5;3 6) = (c=1 4;1 5;1 6;2 3;2 5;2 6;3 4;4 5;4 6; 5 6)

a and b will be given and I want to obtain c; all data is in double. There will always be two columns.

Also, is it possible to get all possible combinations of 1 number upto a certain number? For example, [1 4; 2 4;3 4;4 5;4 6] or [1 6; 2 6; 3 6; 4 6; 5 6]. In the examples, all combinations containing 4 and 6 are there respectively (up to the number 6). I am thinking of nchoosek or setdiff but not sure how.

CodePudding user response:

I am looking for an efficient way to do this:

(a=1 2; 1 3; 2 3)  - b=(1 2; 2 3) = (c=1 3)

your notation is a bit inconsistent, but it looks you want to understand a and b as a set of tuples of two numbers. That's fine, do just exactly that.

In Python, this would be super easy; I'm only using Python to illustrate the concept¹:

a = {(1,2), (1,3), (2,3)}
b = {(1,2), (2,3)}
c = a - b

In matlab, setdiff is to be used; basically, you need to have the 2-tuples as rows of a and b (so a will be a 3×2 matrix).


¹ That's not 100% true. I'm also here to tell you that if your code depends on Matlab doing a lot of set operations, then you will have a long, slow day of annoying coding, and another one of slow, annoying matlab running. It's really not something matlab is good at, neither from the development perspective, nor from the execution side. Might be worth looking at other tools than matlab!

  • Related