compare every element in the first array with the second array
Show older comments
I have two arrays
X = [1,3,5,9]
Y = [1,2,4,9]
I want a function to compare every element in array X with the whole array Y and if this element exists in array Y then write the element and if this element doesn't exist in array Y then add 1 until it find the closest number.
If we suppose the output is Z so Z should be like that Z = [1,4,9,9]
Thanks in advance
1 Comment
Accepted Answer
More Answers (1)
Hi,
Your question can also be framed as -
"For every element x in X , find the least element in y in Y , such that y>=x"
This problem can also be solved using binary search in O(|X||Y|log(|Y|) time, (here |X| represents cardinality of X) ,provided we sort the Y first .
Here's the code for my approch to the problem .
ASSUMPTION
Since you did not clarify on the output when any x in X is larger than the maximum value in Y , I assume it as -1 .
X=[5 4 -10 -2 5 8 10 88 74 5];
Y=[2 3 4 9];
your_ans =fun(X,Y)
function val = helper(x,Y)
n=length(Y);
l=1;r=n;
while(l<=r)
mid =floor(l+(r-l)/2);
if(x==Y(mid))
val=Y(mid);
return;
elseif(x<Y(mid))
r=mid-1;
else
l=mid+1;
end
end
if(l>length(Y))
val=-1;
else
val=Y(l);
end
end
function ret =fun(X,Y)
ret=zeros(1,length(X));
sort(Y);
for i=1:length(X)
ret(i)=helper(X(i),Y);
end
return
end
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!