Different length array comparison and replacements

조회 수: 1 (최근 30일)
Patty
Patty 2014년 5월 27일
편집: George Papazafeiropoulos 2014년 5월 27일
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일
편집: 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