Passing multidimensional arrays as function arguments in C

Pass an explicit pointer to the first element with the array dimensions as separate parameters. For example, to handle arbitrarily sized 2-d arrays of int: void func_2d(int *p, size_t M, size_t N) { size_t i, j; … p[i*N+j] = …; } which would be called as … int arr1[10][20]; int arr2[5][80]; … func_2d(&arr1[0][0], 10, 20); … Read more

Java ArrayList of Arrays?

Should be private ArrayList<String[]> action = new ArrayList<String[]>(); action.add(new String[2]); … You can’t specify the size of the array within the generic parameter, only add arrays of specific size to the list later. This also means that the compiler can’t guarantee that all sub-arrays be of the same size, it must be ensured by you. … Read more

Sort multidimensional array based on 2nd element of the subarray

list.sort, sorted accept optional key parameter. key function is used to generate comparison key. >>> sorted(lst, key=lambda x: x[1], reverse=True) [[‘I’, 219], [‘A’, 22], [‘P’, 14], [‘V’, 13], [‘G’, 10], …] >>> sorted(lst, key=lambda x: -x[1]) [[‘I’, 219], [‘A’, 22], [‘P’, 14], [‘V’, 13], [‘G’, 10], …] >>> import operator >>> sorted(lst, key=operator.itemgetter(1), reverse=True) [[‘I’, … Read more

PyTorch memory model: “torch.from_numpy()” vs “torch.Tensor()”

from_numpy() automatically inherits input array dtype. On the other hand, torch.Tensor is an alias for torch.FloatTensor. Therefore, if you pass int64 array to torch.Tensor, output tensor is float tensor and they wouldn’t share the storage. torch.from_numpy gives you torch.LongTensor as expected. a = np.arange(10) ft = torch.Tensor(a) # same as torch.FloatTensor it = torch.from_numpy(a) a.dtype … Read more

Efficiently count zero elements in numpy array?

A 2x faster approach would be to just use np.count_nonzero() but with the condition as needed. In [3]: arr Out[3]: array([[1, 2, 0, 3], [3, 9, 0, 4]]) In [4]: np.count_nonzero(arr==0) Out[4]: 2 In [5]:def func_cnt(): for arr in arrs: zero_els = np.count_nonzero(arr==0) # here, it counts the frequency of zeroes actually You can also … Read more