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:
- 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 个评论
采纳的回答
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
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numeric Types 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!