How does the following syntax may be shortened and improved?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Antonio Morales
le 21 Fév 2017
Commenté : Antonio Morales
le 21 Fév 2017
Given a 12 x 13 matrix, I need to select the row with the greatest value in column 9, every two rows, and create a matrix containing the selected rows. The following piece of code does the job, but I was wondering how this syntax could be improved and shortened.
A = rand(12,13);
a = A(1:2,:);
if a(1,9) > a(2,9)
a = A(1,:);
else
a = A(2,:);
end
b = A(3:4,:);
if b(1,9) > b(2,9)
b = A(3,:);
else
b = A(4,:);
end
c = A(5:6,:);
if c(1,9) > c(2,9)
c = A(5,:);
else
c = A(6,:);
end
d = A(7:8,:);
if d(1,9) > d(2,9)
d = A(7,:);
else
d = A(8,:);
end
e = A(9:10,:);
if e(1,9) > e(2,9)
e = A(9,:);
else
e = A(10,:);
end
f = A(11:12,:);
if f(1,9) > f(2,9)
f = A(11,:);
else
f = A(12,:);
end
SELECTED_A = [a;b;c;d;e;f];
0 commentaires
Réponse acceptée
Akira Agata
le 21 Fév 2017
How about trying this?
A = rand(12,13);
SELECTED_A = zeros(6,13);
for kk=1:6
if A(2*kk-1,9) > A(2*kk,9)
SELECTED_A(kk,:) = A(2*kk-1,:);
else
SELECTED_A(kk,:) = A(2*kk,:);
end
end
1 commentaire
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!