Different length array comparison and replacements

3 ビュー (過去 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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by