Speed up comparing two arrays and write into new array

6 ビュー (過去 30 日間)
Daniel Rohrer
Daniel Rohrer 2021 年 10 月 19 日
編集済み: Daniel Rohrer 2021 年 10 月 19 日
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

採用された回答

Bruno Luong
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
Assoc_Colors = 10×1 cell array
{[0.2511]} {[0.6004]} {[0.0595]} {[0.0595]} {[0.3949]} {[0.2511]} {[0.0595]} {[0.0937]} {[0.8265]} {[0.0935]}
% 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)))
Assoc_Colors = 10×1 cell array
{[0.2511]} {[0.6004]} {[0.0595]} {[0.0595]} {[0.3949]} {[0.2511]} {[0.0595]} {[0.0937]} {[0.8265]} {[0.0935]}
  1 件のコメント
Daniel Rohrer
Daniel Rohrer 2021 年 10 月 19 日
編集済み: Daniel Rohrer 2021 年 10 月 19 日
Thank you very much for your fast response. Your solution works perfectly fine!
Edit: Runtime of an array of 150'000 x T went down from 720s to only 0.17s. That's a significant improvement =)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Types についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by