Combining matrices into one

2 Ansichten (letzte 30 Tage)
Joel Schelander
Joel Schelander am 11 Mär. 2021
Bearbeitet: Jan am 15 Mär. 2021
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.

Akzeptierte Antwort

Jan
Jan am 11 Mär. 2021
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 Kommentare
Joel Schelander
Joel Schelander am 12 Mär. 2021
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 am 15 Mär. 2021
Bearbeitet: Jan am 15 Mär. 2021
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);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by