Home Matlab to Numpy translation - matrix + scalar differences
Reply: 0

# Matlab to Numpy translation - matrix + scalar differences

user1734
1#
user1734 Published in April 21, 2018, 3:59 am
 I'm trying to translate a Matlab script into Numpy. This is part of the Matlab code: function [idx,D]=knnsearch(varargin) [N,M] = size(Q); L=size(R,1); idx = zeros(N,K); D = idx; for k=1:N d=zeros(L,1); for t=1:M d=d+(R(:,t)-Q(k,t)).^2; end d(k)=inf; [D(k),idx(k)]=min(d); end  where Q and R are matrices that can be considered e.g. as eye(5); you can consider K = 1. An example function call could be: Q = eye(5); R = eye(5); [idx,D] = knnsearch(Q,R,1);  which returns: idx: 2 1 1 1 1 D: 2 2 2 2 2  This is the Numpy code: import numpy as np def knnsearch(Q, R, K): (N,M) = Q.shape L = len(R[:,1]) idx = np.zeros((N,K), dtype=int) D = np.copy(idx) for k in range(0, N): d = np.zeros((L, 1)) for t in range(0, M): d = d + (R[:,t] - Q[k,t])**2 d[k] = np.inf idx[k] = np.argmin(d) D[k] = np.amin(d) return (idx, D)  where Q0 = np.identity(5) R0 = np.identity(5) idxout, Dout = knnsearch(Q0, R0, 1)  This returns different from Matlab: idx: [[5] [1] [2] [3] [4]] D: [[0] [0] [0] [0] [0]]  There is a problem with the row number 9. The second part of the row, the scalar ((R(:,t)-Q(k,t)).^2), returns the same values for both Matlab and Numpy. Instead, the addition (d + scalar) returns different values. So, the matrix d contains different values in Matlab and Numpy. Thanks in advance.
 You need to login account before you can post.
Processed in 0.383954 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO