More Fun with Arrays

2D Arrays

I have come to the alarming realization that it's been so long since I've used Matlab, that I had forgotten that 2D arrays exist, and that they're different from the arrays of arrays that you might use to approximate them. Which means that I've been foolishly using arrays of arrays in Julia this entire time. And I did realize it until I wanted to consider a single column (i.e. the ith value in each list), which was an awkward thing to do. Unless, of course, you have a real 2D array, in which case you can access the ith column just as easily as the ith row.

So, now that I remembered that 2D arrays existed, I just had to figure out how to get my data into one.

Until this point, I'd been reading data from files, one row at at time. I would split each row, and then add that array, representing one line of data, to an overall array. Which means I'd end up with an array of arrays. Luckily, it turned out to be straightforward to convert an array of arrays to a single 2D array, using the power of hcat. What I want to do is loop through my array and hcat each of it's elements, which gives me my 2D array. But even better than looping, I can use ... to pass all the individual elements of the array as arguments (instead of the array itself), which means that I can call hcat just once:

>> x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3-element Array{Array{Int64,1},1}:
 [1, 2, 3]
 [4, 5, 6]
 [7, 8, 9]

>> y = hcat(x...)
3×3 Array{Int64,2}:
 1  4  7
 2  5  8
 3  6  9

As the example illustrates, all my rows of data are now displayed as columns of the 2D array. If this bothered me, I could transpose the matrix, but this was fine for my purposes, since all I need is to be able to easily extract a given row or column, which I can do as follows:

>> y[1, :]
3-element Array{Int64,1}:
 1
 4
 7

>> y[:, 1]
3-element Array{Int64,1}:
 1
 2
 3

This took me an absurdly long time to figure out, considering how simple it ended up being. But now that I have written it down, I hope that I'll be able to do it much more easily next time.

Filtering an Array

Another useful (and simple) discovery is using filter! to remove unwanted elements from an array.

>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10

>> filter!(e->e!=5, x)
9-element Array{Int64,1}:
 1
 2
 3
 4
 6
 7
 8
 9
10

Since I'm just passing my criteria as an anonymous function, I can delete elements based on a more general condition:

>> filter!(e->e%2==1, x)
4-element Array{Int64,1}:
 1
 3
 7
 9

And that's it: a simple way to remove either a specific value, or any elements not meeting some condition. Just note that filter! is modifying the original array (as indicated by the exclamation point), not just returning a new array containing a subset of the original. Use filter instead if you don't want to change the original array.

social