mardi 21 février 2017

How does the following syntax may be shortened and improved?

Given a 12 x 13 matrix in Matlab, 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];

Thank you.

Aucun commentaire:

Enregistrer un commentaire