Combining matrices into one

2 vues (au cours des 30 derniers jours)
Joel Schelander
Joel Schelander le 11 Mar 2021
Modifié(e) : Jan le 15 Mar 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.

Réponse acceptée

Jan
Jan le 11 Mar 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 commentaires
Joel Schelander
Joel Schelander le 12 Mar 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 le 15 Mar 2021
Modifié(e) : Jan le 15 Mar 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);

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by