Speed up comparing two arrays and write into new array

조회 수: 2 (최근 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 CenterFile Exchange에서 Data Types에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by