How to remove the first element and last element based on First column
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I have a matrix 23 by 2 matrix. and it looks as below.
First Column starts from 1 to 5 and second column is the value.
I would like to removes the beginning(i.e the first element) and removes the end(i.e the last element) based on first column.
For example, for 1 from first column, I hope to remove first element [1,293] and last element [1,348]
and for 2 from first column, I hope to remove first element [2,237] and last element [2,326]
and for 3 from first column, I hope to remove first element [3,186] and last element [3,327]
until for 5 from first column.
Is there a way for it?
x1 = [1,293;...
1,274;...
1,329;...
1,348;...
2,237;...
2,374;...
2,326;...
3,186;...
3,237;...
3,274;...
3,327;...
4,186;...
4,235;...
4,274;...
4,326;...
4,359;...
5,161;...
5,164;...
5,186;...
5,235;...
5,274;...
5,326;...
5,358];
0 commentaires
Réponse acceptée
Voss
le 29 Avr 2022
Here's one way
x1 = [1,293;...
1,274;...
1,329;...
1,348;...
2,237;...
2,374;...
2,326;...
3,186;...
3,237;...
3,274;...
3,327;...
4,186;...
4,235;...
4,274;...
4,326;...
4,359;...
5,161;...
5,164;...
5,186;...
5,235;...
5,274;...
5,326;...
5,358];
idx = find(diff(x1(:,1))) % indexes where the first column of x1 changes
idx = idx+[0 1] % those indexes and the one after
idx = [idx(:); 1; size(x1,1)] % include the first and last rows of x1
x1(idx,:) = []; % remove those rows
disp(x1);
2 commentaires
Plus de réponses (1)
dpb
le 29 Avr 2022
Modifié(e) : dpb
le 29 Avr 2022
Of course there is. :)
But, specifically how to do so is dependent on answer to several other questions regarding what is really wanted.
First, how were the elements above determined to want to be removed? The best way to do something of this sort is to have an algorithm that determines which values are those in Q? and thus avoid having to make up lists of specific hard-coded values.
Secondly, however those values are determined, are there
- Possibility of more than one element of same value, and
- Are the values exactly those to machine precision (testing for equality with floating point values is an iffy proposition)
- Is there a need to remove these in pairs as given and do something else with the remainder before moving on to the next pair or can they all just be deleted in "one swell foop!"
?
With answers to those questions, there's at least enough to begin to posit an answer...
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!