How can I remove double values in an array

4 views (last 30 days)
i have these set of two arrays A and B,
A=
[4, 3.40 ;
6, 3.20;
7, 5.50 ;
9, 6.13;
11, 7.18;
14, 8.23;
15, 9.28;
18, 10.33;
20, 11.38 ]
B = [
1, 0 ;
2, 0;
3, 0;
4, 0 ;
5, 0 ;
6, 0 ;
7, 0;
8, 0;
9, 0 ;
10, 0 ;
11, 0;
12, 0;
13, 0;
14, 0;
15, 0;
16, 0;
17, 0;
18, 0;
19, 0 ;
20, 0 ]
and I concatenate them to get C:
C = [
1, 0;
2, 0;
3, 0;
4, 3.40;
4, 0;
5, 0;
6, 3.20;
6, 0;
7, 5.50;
7, 0;
8, 0;
9, 6.13;
9, 0;
10, 0;
11, 7.18;
11, 0;
12, 0;
13, 0 ;
14, 8.23;
14, 0 ;
15, 9.28;
15, 0;
16, 0;
17, 0;
18, 10.33;
18, 0;
19, 0;
20, 11.38 ;
20, 0 ]
The first array contains subsets of the second array. Please how can I remove the rows in C that has zero in the second column.
Thanks

Accepted Answer

Voss
Voss on 4 Jan 2023
It's better to build C the way you want it from the start:
A=[4, 3.40 ;
6, 3.20;
7, 5.50 ;
9, 6.13;
11, 7.18;
14, 8.23;
15, 9.28;
18, 10.33;
20, 11.38 ];
B = [
1, 0 ;
2, 0;
3, 0;
4, 0 ;
5, 0 ;
6, 0 ;
7, 0;
8, 0;
9, 0 ;
10, 0 ;
11, 0;
12, 0;
13, 0;
14, 0;
15, 0;
16, 0;
17, 0;
18, 0;
19, 0 ;
20, 0 ];
C = B;
[ism,idx] = ismember(A(:,1),B(:,1));
C(idx(ism),2) = A(ism,2);
disp(C);
1.0000 0 2.0000 0 3.0000 0 4.0000 3.4000 5.0000 0 6.0000 3.2000 7.0000 5.5000 8.0000 0 9.0000 6.1300 10.0000 0 11.0000 7.1800 12.0000 0 13.0000 0 14.0000 8.2300 15.0000 9.2800 16.0000 0 17.0000 0 18.0000 10.3300 19.0000 0 20.0000 11.3800
  3 Comments

Sign in to comment.

More Answers (1)

MarKf
MarKf on 4 Jan 2023
"remove rows in C that has zero in the second column" so pretty much the array B but with the 2nd column values of A whenever their 1st column values match? if that's the case:
A = [4, 3.40 ; 6, 3.20; 7, 5.50 ; 9, 6.13; ];
B = [(1:10)', zeros([10 1])];
C = B;
C(ismember(B(:,1),A(:,1)),2)=A(:,2)
C = 10×2
1.0000 0 2.0000 0 3.0000 0 4.0000 3.4000 5.0000 0 6.0000 3.2000 7.0000 5.5000 8.0000 0 9.0000 6.1300 10.0000 0
Though I guess that works only if the values in A's 1st column are all contained in B's 1st column. Otherwise you can specify:
C(ismember(B(:,1),A(:,1)),2)=A(ismember(A(:,1),B(:,1)),2);

Community Treasure Hunt

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

Start Hunting!