Finding couple of values in other vector of values

조회 수: 8 (최근 30일)
Ouatehaouks
Ouatehaouks 2021년 12월 21일
댓글: Ouatehaouks 2021년 12월 23일
Say I have a list of couple of values and another list of couple of values which belong to Xd,Yd but that I don't know. How do I efficiently get the list of index locating xv,yv in Xd,Yd ?
All I could find so far is using a loop which is very slow...
[Xd,Yd] = meshgrid(linspace(0,100,101),linspace(0,100,101));
Xd=Xd(:);
Yd=Yd(:);
xv = randi(101,[20,1]);
yv = randi(101,[20,1]);
for i=1:length(xv)
Iv(i) = find(ismember(Xd,xv(i)) & ismember(Yd,yv(i))==1);
end
EDIT : this is a dummy exemple. I need to do that with a very long vectors of values.

채택된 답변

Ouatehaouks
Ouatehaouks 2021년 12월 23일
% I have three vectors of values vi on different zones (xi,yi) with overlapping areas i.e. they share some
% exact positions
% I build the global domain
Xd = [x1 x2 x3];
Yd = [y1 y2 y3];
% I remove the duplicates
[~,inds,~] = unique([Xd,Yd],'rows','stable');
Xd = Xd(inds);
Yd = Yd(inds);
% I put each zone on the global domain
% this means that I need to find where (xi,yi) are locatedd in (Xd,Yd)
% hence the ismember over all couples
v1g = nan(size(Xd));
Iin = ismember([Xd,Yd],[x1,y1],'rows')
v1g(Iin) = v1;
v2g = nan(size(Xd));
Iin = ismember([Xd,Yd],[x2,y2],'rows')
v2g(Iin) = v2;
v3g = nan(size(Xd));
Iin = ismember([Xd,Yd],[x3,y3],'rows')
v3g(Iin) = v3;
% I get the mean
meand = mean([v1g v2g v3g],2,'omitnan');

추가 답변 (1개)

Image Analyst
Image Analyst 2021년 12월 21일
Takes 1 millisecond (0.000897 seconds) on my computer. Why is that not fast enough for you?
There is a problem with the code in that sometimes it finds no match. What do you want to do in that situation? Here is a suggestion:
[Xd,Yd] = meshgrid(linspace(0,100,101),linspace(0,100,101));
Xd=Xd(:);
Yd=Yd(:);
xv = randi(101,[20,1]);
yv = randi(101,[20,1]);
tic
Iv = nan(length(xv), 1);
for k = 1 : length(xv)
locations = find(ismember(Xd,xv(k)) & ismember(Yd,yv(k))==1);
if ~isempty(locations)
Iv(k) = locations;
end
end
toc
Elapsed time is 0.013204 seconds.
  댓글 수: 6
Image Analyst
Image Analyst 2021년 12월 21일
I'm not sure I'm visualizing this correctly. Do you have a diagram?
Maybe unique([x,y,z], 'rows') could help you identify duplicates and unique rows.
Ouatehaouks
Ouatehaouks 2021년 12월 23일
This is indeed what I do to remove the duplicate and I realized I actually can do the same with ismember....so thank you, the results are now given almost instantaneously ! I added the complete answer below.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by