How does the following syntax may be shortened and improved?

2 ビュー (過去 30 日間)
Antonio Morales
Antonio Morales 2017 年 2 月 21 日
コメント済み: Antonio Morales 2017 年 2 月 21 日
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
Akira Agata 2017 年 2 月 21 日
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 件のコメント
Antonio Morales
Antonio Morales 2017 年 2 月 21 日
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

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2017 年 2 月 21 日
編集済み: Jan 2017 年 2 月 21 日
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, :);

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by