Match each element of one array with each element of other array without loops

조회 수: 1 (최근 30일)
Abdulllah
Abdulllah 2019년 5월 22일
답변: Image Analyst 2019년 5월 25일
Hello,
I want to match each element of one array with elements of the other array say "cc". Then multiply with a number from the third array. I am doing using loops. The length of arrays are very large therefore it takes couple of hours. Is it possible to do wihtout loops or make it faster. Here is the code, I am doing,
uniquec=sort(unique(cc));
maxc=max(uniquec);
c35p=0.35*maxc;
g=2;
lessnum=uniquec(uniquec<=c35p);
greaternum=uniquec(uniquec>c35p);
gl=linspace(1,2,length(lessnum));
gr=linspace(2,1,length(greaternum));
newC=zeros(size(cc));
for i=1:length(gl)
newC(cc==lessnum(i))= cc(cc==lessnum(i)).*gl(i);
end
for i=1:length(gr)
newC(cc==greaternum(i))= cc(cc==greaternum(i)).*gr(i);
end
  댓글 수: 2
Stephen23
Stephen23 2019년 5월 22일
편집: Stephen23 2019년 5월 22일
Have you used the profiler to actually check which part of your code is the bottleneck ?
If CC is very large then your code has a few "features" that might prevent it from running efficiently. For example:
  • unique already returns a sorted output, so calling sort will waste time.
  • duplicating data into lessnum and greaternum likely wastes memory.
  • duplicating exactly the same equivalence operations (e.g. indexing inside the loop).
It seems that the loops could be replaced with some logical/subscript indexing. As KSSV wrote, you should read about ismember.
Abdulllah
Abdulllah 2019년 5월 22일
Hello Stephen, you are right. I should not write sort. I dont have issue with the memeory, I have 64GB RAM. lessnum and greaternum are differenet numbers you have seen. I had only this logic in mind to implement. The issues are with the loops. Every entery of the loop has to comapre the full array cc.

댓글을 달려면 로그인하십시오.

답변 (2개)

KSSV
KSSV 2019년 5월 22일
편집: KSSV 2019년 5월 22일
Read about ismember, ismembertol and knnsearch.
  댓글 수: 9
Stephen23
Stephen23 2019년 5월 22일
편집: Stephen23 2019년 5월 22일
" Locb gives number of matches of each number but it do not give indices for them. "
That is incorrect. ismember does not provide any histogram/counting functionality. Its second output are the indices of the values of A in array B. Since R2013a the default is to return the index of the first instance. In your example the first instance of the value 4 is a position 2, the first instance of value 2 is at position 1.
>> Locb(Lia)
ans =
2 1
>> B(Locb(Lia))
ans =
4 2

댓글을 달려면 로그인하십시오.


Image Analyst
Image Analyst 2019년 5월 25일
You say "Every entery of the loop has to comapre the full array cc."
You might want to take a look at pdist2(), if you have the stats toolbox.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by