Re-index a vector based on the indices of another vector

30 views (last 30 days)
Hi all,
I have a vector A:
A = [1 1 1 1
1 1 1 1
1 1 1 1
1 1 2 2
1 1 2 2
1 1 3 3
1 1 3 3
1 1 3 3
1 1 3 3
1 2 1 4];
where the final column corresponds to the index of each row.
I have another vector B:
B =[1 2 1
1 2 1
1 1 3
1 1 3
1 1 1
1 1 1
1 1 3
1 1 2
1 1 2
1 1 2];
I want to add an index column (a fourth column) to vector B where it's decided based on the value of each element in the row and then comparing it with vector A. For example, if all elements equal to 1 in vector B, then the index is 1 as shwon in A. As a result, I should get the following:
B_new = =[1 2 1 4
1 2 1 4
1 1 3 3
1 1 3 3
1 1 1 1
1 1 1 1
1 1 3 3
1 1 2 2
1 1 2 2
1 1 2 2
];
My attempt to do this seems complicated and it doesn't work and I'm sure there is a simpler one, but here it is anyway:
B_new = [];
for i = 1:size(A,1)
if (B(i,1)==A(i,1) && ...
B(i,2)==A(i,2) && ...
B(i,3)==A(i,3))
Bnew = [B(i,:) A(i,4)];
B_new = [B_new ; Bnew];
end
end
Any help would be appreicted.
Thanks

Accepted Answer

Voss
Voss on 1 Nov 2024 at 17:18
[ism,idx] = ismember(B,A(:,[1 2 3]),'rows');
assert(all(ism))
B_new = [B A(idx,4)];

More Answers (1)

Anjaneyulu Bairi
Anjaneyulu Bairi on 1 Nov 2024 at 19:01
Hi,
To create another column in 'B' based on matching of its row values with vector 'A', refer the below code:
B =[1 2 1
1 2 1
1 1 3
1 1 3
1 1 1
1 1 1
1 1 3
1 1 2
1 1 2
1 1 2];
A = [1 1 1 1
1 1 1 1
1 1 1 1
1 1 2 2
1 1 2 2
1 1 3 3
1 1 3 3
1 1 3 3
1 1 3 3
1 2 1 4];
% Initialize the new B with an additional column for the index
B_new = [B zeros(size(B, 1), 1)];
% Find the index for each row in B by comparing with A
for i = 1:size(B, 1)
for j = 1:size(A, 1)
if isequal(B(i, :), A(j, 1:3))
B_new(i, 4) = A(j, 4);
break;
end
end
end
% print the vector
disp(B_new);
1 2 1 4 1 2 1 4 1 1 3 3 1 1 3 3 1 1 1 1 1 1 1 1 1 1 3 3 1 1 2 2 1 1 2 2 1 1 2 2
I hope it helps to resolve your query.

Community Treasure Hunt

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

Start Hunting!