How could I translate this Python code to Matlab?
조회 수: 7 (최근 30일)
이전 댓글 표시
I have this python code that I would like to convert to Matlab code. Could anyone help me understand what is going on and help convert from one language to the other?
The code is as follows:
import random
N = 15
L = 10
sigma = 0.075
n_runs = 800
for runs in range(n_runs):
y = [random.uniform(0.0, L - 2 * N * sigma) for k in range(N)]
y.sort()
print [y[i] + (2 * i + 1) * sigma for 1 in range (N)]|
Much thanks to anyone who can assist me.
Update: I updated the code, if anyone can help, that would be great.
댓글 수: 2
채택된 답변
Andrei Bobrov
2017년 10월 26일
편집: Andrei Bobrov
2017년 10월 26일
N = 15;
L = 10;
sigma = 0.075;
n_configs = 100;
rejections = 0 ;
x = zeros(N,n_configs);
for config = 1:n_configs
while 1
x(:,config) = sort((L-2*sigma)*rand(N,1));
if min(diff(x(:,config))) > 2*sigma
break
end
end
end
or
LL = linspace(0,L,N+1)';
x = (L/N - 2*sigma)*rand(N,n_configs) + LL(1:end-1) + sigma;
댓글 수: 2
추가 답변 (1개)
harshi yaduvanshi
2018년 4월 6일
i have this question i want to convert this python code to matlab.
import random;
import pandas as pd
import numpy as np
def sqrt_sum(a,b): return round(np.sqrt(np.sum((np.array(a)-np.array(b))**2)),5)
def weighted(W,d): return (np.multiply(W,d))
def partition(X,N,L,R,W):
#compute distances
p=[[] for i in range(N)]
w_dist=[]
for i in range(N):
for j in range(L):
dj=sqrt_sum(X.ix[i].tolist(),R[j])
p[i].append(dj)
wj=sum(weighted(W,p[i]))
w_dist.append(wj)
max_d=max(w_dist)
min_d=min(w_dist)
interval_length=(max_d - min_d)/L
#find ranges ranges=[] ranges.append(min_d) #find all ranges for j in range(L): rangej=min_d + interval_length min_d=rangej ranges.append(rangej)
X=X.values.tolist()
#now put the elements into range intancess
#############################################
pj=[[] for i in range(L)]
for i in range(N):
for j in range(len(ranges)-1):
if w_dist[i]>=ranges[j] and w_dist[i]<=ranges[j+1]:
pj[j].append(X[i])
return ranges,pj
def Search_phase(X,N,L,R,W,K,Q,ranges,pj): dq=0 knn=[] for j in range(L): d=sqrt_sum(Q,R[j]) dq=dq+weighted(W[j],d) for i in range(len(ranges)-1): if dq>=ranges[i] and dq<=ranges[i+1]: distance=[] for j in range(len(pj[i])): distance.append(float(sqrt_sum(Q,pj[i][j]))) distance=np.asarray(distance) lists=distance.argsort()[:5] for x in lists: knn.append(pj[i][x])
return knn
def fetching_data(): X=pd.read_csv("IRIS(2).csv",header=None) N=len(X) L=4 R = X.sample(L)
R=R.values.tolist()
W=[0.1,0.3,0.8,0.2]
K=5
Q=[0.196667,0.166667,0.389831,0.375000]
return X,N,L,R,W,K,Q
X,N,L,R,W,K,Q=fetching_data() ranges,pj=partition(X,N,L,R,W) KNN=Search_phase(X,N,L,R,W,K,Q,ranges,pj) print("top k-nn are",KNN)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!