How to put value from one matrix into another matrix
16 views (last 30 days)
Show older comments
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
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1309500/image.jpeg)
0 Comments
Answers (3)
Torsten
on 28 Feb 2023
Edited: Torsten
on 28 Feb 2023
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
Stephen23
on 1 Mar 2023
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]
R = nan(size(B));
[X,Y] = ismember(B,A(:,1));
R(X) = A(Y(X),2)
See Also
Categories
Find more on Matrix Indexing 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!