Different length array comparison and replacements

1 次查看(过去 30 天)
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!

采纳的回答

Jos (10584)
Jos (10584) 2014-5-27
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?
  1 个评论
Patty
Patty 2014-5-27
编辑:Patty 2014-5-27
Thanks! This is what I was looking for, to stop the inner "for". But I was not sure about the break function. :)
I just tried and it's working.

请先登录,再进行评论。

更多回答(1 个)

George Papazafeiropoulos
编辑:George Papazafeiropoulos 2014-5-27
% data
A=[445;
874];
B= [265;
446;
744;
872;
875];
% engine
AA=A(:,ones(1,size(B,1)))';
BB=B(:,ones(1,size(A,1)));
[r,c,~]=find(AA-BB<0);
ranges=histc(c,unique(c));
a=max(ranges);
ind1=reshape((1:a*length(ranges))',a,[]);
lb=0:a:a*(length(ranges)-1);
lb=lb(ones(a,1),:);
ub=ranges'+(0:length(ranges)-1)*a;
ub=ub(ones(a,1),:)+1;
ind2=ind1>lb & ind1<ub;
y(ind2)=r;
y(~ind2)=nan;
y=reshape(y,a,[]);
y=y(1,:);
u=diff(y)>0;
ind=[1 u.*(2:length(u)+1)];
A(~ind)=[];
ind(~ind)=[];
replacement_indices=y(1,ind);
% result
C=B;
C(replacement_indices)=A;
find(C-B)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by