Extract data based on columns

8 visualizzazioni (ultimi 30 giorni)
novice modeler
novice modeler il 4 Giu 2017
Risposto: Guillaume il 5 Giu 2017
Altruists,
I have the data in the following matrix.
Year month value
2000 1 10
2000 2 20
2000 3 30
I have to extract this values to the following matrix in repetition, for example:
Year month value
2000 1 ?
2000 1 ?
2000 2 ?
Thanks

Risposte (2)

Walter Roberson
Walter Roberson il 5 Giu 2017
Modificato: Walter Roberson il 5 Giu 2017
YourMatrix = [2000 1 10
2000 2 20
2000 3 30];
probe_rows = [2000 1
2000 1
2000 2];
[uniqYM, ~, uniq_rowidx] = unique(YourMatrix(:,1:2), 'rows', 'stable');
[tf, index_in_uniqYM] = ismember(probe_rows, uniqYM, 'rows');
valid_idx_in_uniqYM = index_in_uniqYM(tf);
output = YourMatrix( ismember(uniq_rowidx, valid_idx_in_uniqYM), :);
Note: this code was specifically designed with the possibility that the year and month entries in the original matrix might not be unique, that you might need to retrieve multiple rows.
  2 Commenti
novice modeler
novice modeler il 5 Giu 2017
Thanks for the reply. Actually, the original matrix contains no repetitive entries but the matrix in problem requires to retrieve repetitive entries. Would you please let me know your answer for this.
Walter Roberson
Walter Roberson il 5 Giu 2017
YourMatrix = [2000 1 10
2000 2 20
2000 3 30];
probe_rows = [2000 1
2000 1
2000 2];
[tf, index_in_original] = ismember(probe_rows, YourMatrix(:, [1 2]), 'rows');
output = YourMatrix( index_in_original(tf), : );

Accedi per commentare.


Guillaume
Guillaume il 5 Giu 2017
If your matrices are actually tables as your formatting sort of imply, then it's trivially done with join or outerjoin (depending on whether or not you want to include rows that don't match:
%inputs as table:
data = table([2000; 2000; 2000], [1; 2; 3], [10; 20; 30], 'VariableNames', {'year', 'month', 'value'})
probe = table([2000; 2000; 2000], [1; 1; 2], 'VariableNames', {'year', 'month'});
%include only rows that match
result = join(probe, data)
%include rows of probe that do not match
result = outerjoin(probe, data, 'Type', 'left');
If your inputs are actually matrices, then convert them to tables or use Walter's answer.

Categorie

Scopri di più su Tables in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by