Compact way to write matrices containing indices
Mostrar comentarios más antiguos
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 comentario
Respuesta aceptada
Más respuestas (1)
David Hill
el 6 de Abr. de 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)];
1 comentario
Sim
el 6 de Abr. de 2022
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!