Mapping 2 vectors – help to vectorize

Oh! One other option: since you’re looking for close correspondences between two sorted lists, you could go through them both simultaneously, using a merge-like algorithm. This should be O(max(length(xm), length(xn)))-ish. match_for_xn = zeros(length(xn), 1); last_M = 1; for N = 1:length(xn) % search through M until we find a match. for M = last_M:length(xm) dist_to_curr … Read more

Efficiently Creating A Pandas DataFrame From A Numpy 3d array

Here’s one approach that does most of the processing on NumPy before finally putting it out as a DataFrame, like so – m,n,r = a.shape out_arr = np.column_stack((np.repeat(np.arange(m),n),a.reshape(m*n,-1))) out_df = pd.DataFrame(out_arr) If you precisely know that the number of columns would be 2, such that we would have b and c as the last two … Read more

Why doesn’t outer work the way I think it should (in R)?

outer(0:5, 0:6, sum) don’t work because sum is not “vectorized” (in the sense of returning a vector of the same length as its two arguments). This example should explain the difference: sum(1:2,2:3) 8 1:2 + 2:3 [1] 3 5 You can vectorize sum using mapply for example: identical(outer(0:5, 0:6, function(x,y)mapply(sum,x,y)), outer(0:5, 0:6,’+’)) TRUE PS: Generally … Read more

How do I compare all elements of two arrays?

The answers given are all correct. I just wanted to elaborate on gnovice’s remark about floating-point testing. When comparing floating-point numbers for equality, it is necessary to use a tolerance value. Two types of tolerance comparisons are commonly used: absolute tolerance and relative tolerance. (source) An absolute tolerance comparison of a and b looks like: … Read more

Vectorizing the Notion of Colon (:) – values between two vectors in MATLAB

Your sample output is not legal. A matrix cannot have rows of different length. What you can do is create a cell array using arrayfun: values = arrayfun(@colon, idx1, idx2, ‘Uniform’, false) To convert the resulting cell array into a vector, you can use cell2mat: values = cell2mat(values); Alternatively, if all vectors in the resulting … Read more