How can I merge the values of one matrix into another matrix based on one column value?

2 次查看(过去 30 天)
I have the following matrices:
A = zeros([7 4])
A(:,1) = 1104849000:60:1104849400
B = rand([3 4])
B(1,1) = 1104849000
B(2,1) = 1104849180
B(3,1) = 1104849240
And I would like to fill in the rows in matrix A with the values in matrix B based on the first column matching.
So the end result will be:
C = zeros([7 4])
C(:,1) = 1104849000:60:1104849400
C(1,:) = B(1,:)
C(4,:) = B(2,:)
C(5,:) = B(3,:)
Which would be the idiomatic way to achive this in Matlab (obviously for much larger matrices)?
Assumptions:
  1. Matrix A will ALWAYS contain the values of the first column in Matrix B (so Matrix B is always a subset of Matrix A in terms of first column values).
  2. Both Matrix A and B contain always sorted and unique values for the first column.
This is a simplified reproducible example, in my real example I am trying to ensure that an incomplete time series (Matrix B) fills a complete time series (Matrix A). First column are epoch seconds; in case there is another approach suitable for this.
Note: I want to learn how to use matrices, not TimeTables.

采纳的回答

Chunru
Chunru 2022-9-22
A = zeros([7 4]);
A(:,1) = 1104849000:60:1104849400;
B = rand([3 4]);
B(1,1) = 1104849000;
B(2,1) = 1104849180;
B(3,1) = 1104849240;
A, B
A = 7×4
1.0e+09 * 1.1048 0 0 0 1.1048 0 0 0 1.1048 0 0 0 1.1048 0 0 0 1.1048 0 0 0 1.1048 0 0 0 1.1048 0 0 0
B = 3×4
1.0e+09 * 1.1048 0.0000 0.0000 0.0000 1.1048 0.0000 0.0000 0.0000 1.1048 0.0000 0.0000 0.0000
C = zeros([7 4]);
C(:,1) = A(:, 1);
for i=1:height(C)
idx = find(B(:,1) ==C(i,1), 1);
if ~isempty(idx)
C(i, :) = B(idx, :);
end
end
C
C = 7×4
1.0e+09 * 1.1048 0.0000 0.0000 0.0000 1.1048 0 0 0 1.1048 0 0 0 1.1048 0.0000 0.0000 0.0000 1.1048 0.0000 0.0000 0.0000 1.1048 0 0 0 1.1048 0 0 0

更多回答(1 个)

Mario
Mario 2022-9-22
编辑:Mario 2022-9-22
Additional to the answer above, I found that ismember can be also used here
A = zeros([7 4]);
A(:,1) = 1104849000:60:1104849400;
B = rand([3 4]);
B(1,1) = 1104849000;
B(2,1) = 1104849180;
B(3,1) = 1104849240;
format long
C=A
C = 7×4
1.0e+09 * 1.104849000000000 0 0 0 1.104849060000000 0 0 0 1.104849120000000 0 0 0 1.104849180000000 0 0 0 1.104849240000000 0 0 0 1.104849300000000 0 0 0 1.104849360000000 0 0 0
C(ismember(A(:,1),B(:,1)),:)=B(:,:)
C = 7×4
1.0e+09 * 1.104849000000000 0.000000000797805 0.000000000828391 0.000000000912236 1.104849060000000 0 0 0 1.104849120000000 0 0 0 1.104849180000000 0.000000000016681 0.000000000523010 0.000000000855862 1.104849240000000 0.000000000730961 0.000000000517466 0.000000000437620 1.104849300000000 0 0 0 1.104849360000000 0 0 0
Is there any preference in terms of performance (like avoiding loops)? If so which approach would perform better?

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by