Different length array comparison and replacements
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Patty
am 27 Mai 2014
Bearbeitet: George Papazafeiropoulos
am 27 Mai 2014
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!
0 Kommentare
Akzeptierte Antwort
Jos (10584)
am 27 Mai 2014
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 Kommentar
Weitere Antworten (1)
George Papazafeiropoulos
am 27 Mai 2014
Bearbeitet: George Papazafeiropoulos
am 27 Mai 2014
% 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)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!