How to put value from one matrix into another matrix

7 次查看(过去 30 天)
I have two matrixes called A and B. The matrix A is 20x2 and matrix B is 4x5. I suppose the first column of matrix A is 1 to 20 and the second column is the values of number 1-20. The matrix B is a new rearraged matrix of the first column of matrix A (number 1-20). I want to put the values from the second column of matrix A into the matrix B.
I have search the Matlab function that maybe related is ismember. But I am still confused how to coding. Thank you in advance

回答(3 个)

Torsten
Torsten 2023-2-28
编辑:Torsten 2023-2-28
help reshape
Or are the entries of the matrix B not necessarily as regular as in your picture ?
A = [1 2 3 4 5 6 7 8;0.2 0.8 0.3 0.6 0.5 0.1 1.2 0.8].';
B = reshape(A(:,1),[4 2])
B = 4×2
1 5 2 6 3 7 4 8
Results = reshape(A(:,2),[4 2])
Results = 4×2
0.2000 0.5000 0.8000 0.1000 0.3000 1.2000 0.6000 0.8000
  1 个评论
Panida Kaewniam
Panida Kaewniam 2023-2-28
Thanks for prompt reply. I maybe did not explain my data clearly. Actually, matrix B is formed by selecting some value of matrix A. It means that not all values of the 1st column of matrix A is used in matrix B.
For example, matrix A is sized 40x2 (the 1st colomn of matrix A is 3 to 43). The matrix B use some data of matrix A like the photo below.
I am trying to write some code but it doesn't give the correct results.
Thanks again
result = [];
for i = 1:1:length(A(:,1))
result = find(ismember(B,A(:,1)));
result = A(:,2);
end

请先登录,再进行评论。


Torsten
Torsten 2023-2-28
编辑:Torsten 2023-2-28
A = [3:42;rand(1,40)].';
B = [6 45 18 24 33;5 12 17 23 32;4 11 16 22 31;3 10 15 21 30];
result = zeros(size(B));
for i = 1:size(B,1)
for j = 1:size(B,2)
index = find(A(:,1)==B(i,j));
if isempty(index)
result(i,j) = NaN;
else
result(i,j) = A(index,2);
end
end
end
result
result = 4×5
0.2359 NaN 0.6920 0.4382 0.5104 0.4386 0.3690 0.9290 0.6086 0.6957 0.1525 0.0100 0.6069 0.9521 0.7143 0.6569 0.7619 0.0783 0.6285 0.3234

Stephen23
Stephen23 2023-3-1
A = [3:42;rand(1,40)].'
A = 40×2
3.0000 0.1042 4.0000 0.3039 5.0000 0.6918 6.0000 0.0111 7.0000 0.7219 8.0000 0.6514 9.0000 0.1826 10.0000 0.4777 11.0000 0.7469 12.0000 0.0053
B = [6,45,18,24,33;5,12,17,23,32;4,11,16,22,31;3,10,15,21,30]
B = 4×5
6 45 18 24 33 5 12 17 23 32 4 11 16 22 31 3 10 15 21 30
R = nan(size(B));
[X,Y] = ismember(B,A(:,1));
R(X) = A(Y(X),2)
R = 4×5
0.0111 NaN 0.4559 0.6373 0.7475 0.6918 0.0053 0.9486 0.4545 0.9259 0.3039 0.7469 0.4148 0.8065 0.9770 0.1042 0.4777 0.0071 0.9220 0.0752

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by