Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Efficient way to copy a matrix except for one column

Consider a matrix where you don’t need the third column:

X = zeros(Int64, (8, 3));
X[:, 1] = [0, 0, 0, 0, 1, 1, 1, 1];
X[:, 2] = [1, 1, 2, 2, 1, 1, 2, 2];
julia> X
8×3 Matrix{Int64}:
 0  1  0
 0  1  0
 0  2  0
 0  2  0
 1  1  0
 1  1  0
 1  2  0
 1  2  0

So you want to select (copy) everything except column 3:

8×2 Matrix{Int64}:
 0  1
 0  1
 0  2
 0  2
 1  1
 1  1
 1  2
 1  2

Is there a shorthand way to express this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

These work, but feel impractical when you have a large number of columns:

X[:, [1, 2]]
X[:, sort(collect(setdiff(Set([1, 2, 3]), Set([3]))))]

>Solution :

There are plenty of ways to do this. Below is a solution in which you express which ranges of column numbers to include:

X = zeros(Int64, (8, 3));
X[:, 1] = [0, 0, 0, 0, 1, 1, 1, 1];
X[:, 2] = [1, 1, 2, 2, 1, 1, 2, 2];

return X[:,1:2] #Columns 1 through 2 are being directly included.

Alternatively, you could express which you would like to exclude, which is perhaps a more widely useful version of the code:

return X[:, 1:end .!= 3] #column number 3 is being directly excluded.

Both of which would return:

8×2 Matrix{Int64}:
 0  1
 0  1
 0  2
 0  2
 1  1
 1  1
 1  2
 1  2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading