[ism,idx] = ismember(B,A(:,[1 2 3]),'rows'); assert(all(ism)) B_new = [B A(idx,4)];
Re-index a vector based on the indices of another vector
조회 수: 3 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Voss
2024년 11월 1일
추가 답변 (1개)
Anjaneyulu Bairi
2024년 11월 1일
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);
I hope it helps to resolve your query.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!