How to input corresponding data from separate matrices

4 ビュー (過去 30 日間)
Noah
Noah 2023 年 1 月 5 日
編集済み: Voss 2023 年 1 月 6 日
I have a matrix
A = [1 2 3 4 5 6 7 8 9 10] '
and
B = [ 2 3 1 7 9 10 4 6 5 8; 12 43 64 94 27 58 64 13 90 74]'
I am trying to make a script that reads the i-th value of matrix A and matches it to the same value in matrix B. Then take the corresponding value in matrix B from the same row (so for A(1,1) it will read B(3,1)) and take the value 64 from B(3,2) and put it in a separate column matrix.

採用された回答

Voss
Voss 2023 年 1 月 6 日
編集済み: Voss 2023 年 1 月 6 日
A = [1 2 3 4 5 6 7 8 9 10].';
B = [ 2 3 1 7 9 10 4 6 5 8; 12 43 64 94 27 58 64 13 90 74].';
[ism,idx] = ismember(A,B(:,1));
C = B(idx(ism),2)
C = 10×1
64 12 43 64 90 13 94 74 27 58

その他の回答 (1 件)

Bora Eryilmaz
Bora Eryilmaz 2023 年 1 月 5 日
編集済み: Bora Eryilmaz 2023 年 1 月 5 日
A = [1 2 3 4 5 6 7 8 9 10]';
B = [ 2 3 1 7 9 10 4 6 5 8; 12 43 64 94 27 58 64 13 90 74]';
% Iterate over every element of A
N = numel(A(:));
C = zeros(N, 1); % Output column matrix
for i = 1:N
rowA = A(i);
rowB = find(B(:,1) == rowA) % Find row of B corresponding to the element of A
C(rowA) = B(rowB,2); % Rows of C match rows of A
%C(rowB) = B(rowB,2); % Rows of C match rows of B
end
rowB = 3
rowB = 1
rowB = 2
rowB = 7
rowB = 9
rowB = 8
rowB = 4
rowB = 10
rowB = 5
rowB = 6
C
C = 10×1
64 12 43 64 90 13 94 74 27 58

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by