Speed up comparing two arrays and write into new array
6 ビュー (過去 30 日間)
古いコメントを表示
Hello,
I compare values of two arrays, and write the values of an associated array into a new one. Unfortunately, this comparison is quite slow. I know vectorization is a way to do it, but I don't know how in this case. Below are smaller arrays for testing, it can go up to 1'000'000 x T or so. Looking at the profiler data, the comparison takes 99% of the time for below code snippet with large arrays.
I got three initial arrays:
coordIndex: 514x4 double (integer), with most values occurring several times. Same values as in Vert_ID_mat, so 218 different values. Array can contain NaN-Values
Vert_ID_mat: 218x1 double (integer), every value only once
Colors_Res: 514x4 cell (strings). Can contain zeros, which are associated to the NaN-values
Resulting array:
Assoc_Colors: 218x1 cell (strings)
I use following code right now:
for k = 1:size(coordIndex,1)
for kk = 1:size(coordIndex,2)
for i = 1:size(Vert_ID_mat,1)
if coordIndex(k,kk) == Vert_ID_mat(i) %isequal
Assoc_Colors{i} = Colors_Res(k, kk);
end
end
end
end
Assoc_Colors = Assoc_Colors.';
How can I write a faster code and achieve a faster processing time?
Best regards
Daniel
0 件のコメント
採用された回答
Bruno Luong
2021 年 10 月 19 日
編集済み: Bruno Luong
2021 年 10 月 19 日
For simplification I use numerical data for Colors_Res/Assoc_Colors adatp tou your data type
clear
% Dummy test data
coordIndex=randi(9,8,9);
Colors_Res=rand(size(coordIndex));
Vert_ID_mat=randi(9,10,1);
% Your method
for k = 1:size(coordIndex,1)
for kk = 1:size(coordIndex,2)
for i = 1:size(Vert_ID_mat,1)
if coordIndex(k,kk) == Vert_ID_mat(i) %isequal
Assoc_Colors{i} = Colors_Res(k, kk);
end
end
end
end
Assoc_Colors = Assoc_Colors.';
Assoc_Colors
% Vectorized method
coordIndexTrans = coordIndex.';
Colors_ResTrans = Colors_Res.';
[tf,loc]=ismember(Vert_ID_mat(:), coordIndexTrans(:),'legacy');
Assoc_Colors = cell(size(Vert_ID_mat));
Assoc_Colors(tf)=num2cell(Colors_ResTrans(loc(tf)))
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!