How can I merge the values of one matrix into another matrix based on one column value?
1 view (last 30 days)
Show older comments
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:
- 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).
- 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.
0 Comments
Accepted Answer
Chunru
on 22 Sep 2022
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
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
0 Comments
See Also
Categories
Find more on Numeric Types 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!