Compact way to write matrices containing indices

9 ビュー (過去 30 日間)
Sim
Sim 2022 年 4 月 6 日
コメント済み: Sim 2022 年 4 月 6 日
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 件のコメント
Sim
Sim 2022 年 4 月 6 日
編集済み: Sim 2022 年 4 月 6 日
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

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2022 年 4 月 6 日
編集済み: Stephen23 2022 年 4 月 6 日
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 件のコメント
Sim
Sim 2022 年 4 月 6 日
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 :)

サインインしてコメントする。

その他の回答 (1 件)

David Hill
David Hill 2022 年 4 月 6 日
[~,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 件のコメント
Sim
Sim 2022 年 4 月 6 日
@David Hill Coooooolll !!! Many thanks :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by