필터 지우기
필터 지우기

Combining matrices into one

조회 수: 1 (최근 30일)
Joel Schelander
Joel Schelander 2021년 3월 11일
편집: Jan 2021년 3월 15일
I have one vector denoting every minute of the year: T=[1:525600].'
I have a matrix containing 2 coulumns and 13777 rows(B). The first column describes the minute that a EV is charging, the second column describes how much is charged that minute.
What I need is a matrix that contains all the minutes of the year as well as the values from column 2 in B:
B=[3849 0.183333333333333
3850 0.183333333333333
3851 0.183333333333333
3852 0.183333333333333];
The matrix contains every minute of year as well as the values from B, if there is no value in B for a certain minute, that row in the second column should be 0.
Like this
[ 3847 0
3848 0
3849 0.18333
3850 0.18333
3851 0.18333
3852 0.18333
3853 0
3854 0]
I have tried for loops back and forth, but not sure how I can create this matrix.

채택된 답변

Jan
Jan 2021년 3월 11일
T = (1:525600).';
B = [3849, 0.1833; ... % Different values to avoid confusion
3850, 0.1834; ...
3851, 0.1835; ...
3852, 0.1836];
match = ismember(T, B(:,1)); % Assuming that B is sorted
T(match, 2) = B(:, 2); % Fills other values with 0
  댓글 수: 4
Joel Schelander
Joel Schelander 2021년 3월 12일
B=cell2mat(CAR(1));
T = (1:525600).';
match = ismember(T, B(:,1)); % Assuming that B is sorted
T(match, 2) = B(:, 2); % Fills other values with 0
B is a 13377x2 double but looks the same as the one above. However I tried this formula and I get this error
Unable to perform assignment because the size of the left side is 13330-by-1 and the size of the right side is 13377-by-1.
Error in DRIVE (line 29)
T(match, 2) = B(:, 2); % Fills other values with 0
Jan
Jan 2021년 3월 15일
편집: Jan 2021년 3월 15일
Replace
B=cell2mat(CAR(1));
by the more efficient:
B = CAR{1};
If B(:,2) has more elements than match, some of the times in B are not found in T or they exist multiple times. There is no general solution to handle this. Check which times are concerned:
T = (1:525600).';
[matchT, indexB] = ismember(T, B(:, 1));
% Show problems:
C = B;
C(indexB, :) = [];
disp('Missing:')
disp(C)
% Copy the matching values:
T(matchT, 2) = B(indexB, 2);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by