Compact way to write matrices containing indices

1 view (last 30 days)
Hi, I have an array A and a matrix B.
(Task 1) First, I would like to check which elements of A are members of the first column of B.
(Task 2) Then, I would like to return (i.e. write down) my matrix B with the same order of the elements of A, and leaving a NaN (or zero) for those elements of A that were not found in B. Is there a compact way to accomplish the Task 2 ?
OK, a little bit messy to explain, but with this example it should be easier to understand what I need:
% Input
A = [3
4
9
1
5];
B = [3 5
6 2
4 8
5 7
9 7];
% Task (1) - Easy
[~,i] = ismember(A,B(:,1))
% Task (2) - First naive attempt gives an error
>> B(i,:)
Index in position 1 is invalid. Array indices must be positive integers or logical values.
% Task (2) - A second naive attempt works, but the 4th row of A is missing
>> B(i(i~=0),:)
ans =
3 5
4 8
9 7
5 7
% Desired Output - Here the 4th row of A is present with a NaN in the
% second column
>> B(?,?)
ans =
3 5
4 8
9 7
1 NaN
5 7
% Is there a compact way to get my desired output?
% Maybe just writing something like: B(?,?)
  1 Comment
Sim
Sim on 6 Apr 2022
Edited: Sim on 6 Apr 2022
Basically, I would like to avoid this loop:
% Task (1)
[~,i] = ismember(A,B(:,1));
% Task (2) - Desired Output
for j = 1 : length(i)
if i(j)~=0
B_des_output(j,:) = B(i(j),:);
else
B_des_output(j,:) = [A(j) NaN];
end
end
% Result
>> B_des_output
3 5
4 8
9 7
1 NaN
5 7

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 6 Apr 2022
Edited: Stephen23 on 6 Apr 2022
A = [3;4;9;1;5];
B = [3,5;6,2;4,8;5,7;9,7];
[X,Y] = ismember(A,B(:,1));
M = A;
M(:,2) = NaN;
M(X,2) = B(Y(X),2)
M = 5×2
3 5 4 8 9 7 1 NaN 5 7
  1 Comment
Sim
Sim on 6 Apr 2022
All great solutions @David Hill and @Stephen, but this one looks like even more compact than other ones!
Many thanks to everyone for your contribution, I would accept all the answers :)

Sign in to comment.

More Answers (1)

David Hill
David Hill on 6 Apr 2022
[~,idx]=ismember(A,B(:,1));
f=find(idx==0);
idx(idx==0)=1;
C=B(idx,:);
C(f,:)=[A(f),nan(length(f),1)];

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!