Effacer les filtres
Effacer les filtres

Equivalent code in Python when appending arrays

2 vues (au cours des 30 derniers jours)
Anh Phan Viet
Anh Phan Viet le 15 Sep 2020
Modifié(e) : Anh Phan Viet le 15 Sep 2020
Hello everyone,
I've got a problem when trying to translate this code in MATLAB to Python. The problem happened when I tried to append items to list.
dict{1} = [ 24 13; 8 21 ];
dict{2} = [ 2 17; 13 21 ];
dict{3} = [ 17 1; 21 12; 22 15; 21 24; 18 29 ];
dict{4} = [ 24 3; 22 23; 11 25 ];
dict{5} = [ 3 12; 26 18 ];
result = cell(size(dict));
dk = zeros(0,2); rk = {};
for k=1:length(result) % working down, construct sequentially
rp = rk; dp = dk; dk = dict{k}; % bookkeeping and update
rk = num2cell(dk,2); % split rows as cell
[b,loc] = ismember(dk(:,1),dp(:,2)); % check for matching
p = rp(loc(b)); % build the path using for-loop instead of ARRAYFUN
n = dk(b,2);
for j=1:length(p)
p{j} = [p{j} n(j)];
end
rk(b) = p;
result{k} = rk; % assign
end
In Python:
list = {}
list[0] = np.array([[24, 13], [8, 21]])
list[1] = np.array([[2, 17], [13, 21]])
list[2] = np.array([[17, 1], [21, 12], [22, 15], [21, 24], [18, 29]])
list[3] = np.array([[24, 3], [22, 23], [11, 25]])
list[4] = np.array([[3, 12], [26, 18]])
dk = np.zeros((0,2))
rk = {}
result = {}
for k in range(len(list)):
rp = rk
dp = dk
dk = list[k]
rk = num2cell(dk)
[b, loc] = ismember(dk[...,0], dp[...,1])
if k > 0:
p = rp_array[loc]
n = dk[b, 1]
p = np.column_stack((p, n))
rk[b] = p
result[k] = rk
The error is: shape mismatch: value array of shape (1,3) could not be broadcast to indexing result of shape (1,2), which is rk[b] = p. So can anyone please help me find the equivalent code to this?

Réponses (0)

Catégories

En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by