# How does the following syntax may be shortened and improved?

1 view (last 30 days)
Antonio Morales on 21 Feb 2017
Commented: Antonio Morales on 21 Feb 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];

Akira Agata on 21 Feb 2017
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
Antonio Morales on 21 Feb 2017
Thanks, another way to do it I got from someone else:
A=rand(12,13);
SELECTED_A=zeros(6,13); % preallocate solutionarray
for ii=2:2:12 % loop through every (second) row
[~,ind]=max([A(ii,9),A(ii-1,9)]); % check which element is greater
SELECTED_A(ii/2,:)=A(ii-(ind==2),:); % select corresponding row
end

Jan on 21 Feb 2017
Edited: Jan on 21 Feb 2017
A = rand(12, 13); % Test data
s1 = size(A, 1);
select = (A(1:2:s1, 9) <= A(2:2:s1, 9));
index = (1:2:s1) + select.';
SELECTED_A = A(index, :);