Compare matrix element without loops

조회 수: 2 (최근 30일)
shdotcom shdotcom
shdotcom shdotcom 2019년 5월 4일
댓글: dpb 2019년 5월 4일
Hi,
Is there any way to get same result without using loops?
G = [5 8; 8 5; 3 9; 7 3; 1 4; 5 10; 6 7; 4 10; 4 7; 1 6];
n = 2;
nG = size(G,1);
for ii=1:nG
zz =1;
isDom = [];
for kk=1:n
for jj=1:nG
if ii ~= jj
isDom(zz) = G(ii,kk) < G(jj,kk);
zz = zz +1;
end
end
end
R(ii) = sum(isDom==1);
end

채택된 답변

dpb
dpb 2019년 5월 4일
편집: dpb 2019년 5월 4일
Not w/o zero loops, think not, but can reduce to one...
idx=1:nG; % working index array for element logical lookup/exclusion
R=zeros(nG,1); % preallocate
for i=1:nG
isDom=(G(i,:)-G(idx~=i,:));
R(i)=sum(isDom(:)<0);
end
You can eliminate the intermediate isDom temporary if desired..."exercise for the student" :)
  댓글 수: 2
shdotcom shdotcom
shdotcom shdotcom 2019년 5월 4일
Thank you
dpb
dpb 2019년 5월 4일
You can also, of course, remove the explicit loop via arrayfun, but the loop is still there and resulting code is somewhat obfuscated and may well be slower, besides...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by