How does the following syntax may be shortened and improved?

2 visualizaciones (últimos 30 días)
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];

Respuesta aceptada

Akira Agata
Akira Agata el 21 de Feb. de 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 comentario
Antonio Morales
Antonio Morales el 21 de Feb. de 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

Iniciar sesión para comentar.

Más respuestas (1)

Jan
Jan el 21 de Feb. de 2017
Editada: Jan el 21 de Feb. de 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, :);

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by