MATLAB: Different length array comparison and replacements

matrixmatrix arraymatrix manipulation

If I have 2 different length array, and I want to compare the values between these two arrays. First I sort both arrays in 'ascend' manner. So I start comparing the 1st term of Array A with the 1st term of Array B. If A(i)<B(j) then replace in a C predefined matrix. Once a element is replace in C, I need to move to the second term of A. I don't need to compare every element of A with the rest of B, because I already make a replacement. Also it can be the case that any member of A is less than B.
I tried with the double "for" loop, but it is not working. Because It compares every element of A with every element of B, it does not matter if it make a replacement.
For example:
if true
A=[445;
874]
B= [265;
446;
744;
872;
875]
for i=1:length(A)
for j=1:length(B)
if A(i)<B(j)
C(j)=A(i);
end
end
end
end
In this example A(1) should replace C(3) and A(2) should replace C(5). But as mention, it can be the case where any member of A replace a member of C.
Thanks!

Best Answer

Add a break in the if so the function will break out of the inner-loop, and moves on to the next element of A:
help break
In addition, you can pre-allocate C before the loops
C = zeros(size(B))
Last, it can be the case that an element of C is overwritten (e.g., when A = [2 3], B = [1 4 10], which will result in C = [0 3 0]). Is this your intention?