lundi 29 août 2016

if-statement: how to rewrite in matlab

I newby in Matlab. I have took the work code with complex if-statement condition and need to rewrite it. This code should prepare some initial data to solve an optimization task. This if-statement condition looks like:

x=[784.8 959.2 468 572 279 341 139.5 170.5 76.5 93.5 45 55];
a=combntns(x,6); % all possible combinations from 6 elements of x
n=length(a);
q=[];

 for i=1:n

if( ((a(i,1)==x(1)) & (a(i,2)==x(2))) | 
    ((a(i,1)==x(3)) & (a(i,2)==x(4))) | 
    ((a(i,1)==x(5)) & (a(i,2)==x(6))) |  
    ((a(i,1)==x(7)) & (a(i,2)==x(8))) |
    ((a(i,2)==x(3)) & (a(i,3)==x(4))) |  
    ((a(i,2)==x(5)) & (a(i,3)==x(6))) | 
    ((a(i,2)==x(7)) & (a(i,3)==x(8))) |  
    ((a(i,3)==x(3)) & (a(i,4)==x(4))) |  
    ((a(i,3)==x(5)) & (a(i,4)==x(6))) |  
    ((a(i,3)==x(7)) & (a(i,4)==x(8))) |  
    ((a(i,3)==x(9)) & (a(i,4)==x(10)))|  
    ((a(i,4)==x(5)) & (a(i,5)==x(6))) |  
    ((a(i,4)==x(7)) & (a(i,5)==x(8))) |  
    ((a(i,4)==x(9)) & (a(i,5)==x(10)))|  
    ((a(i,5)==x(5)) & (a(i,6)==x(6))) |  
    ((a(i,5)==x(7)) & (a(i,6)==x(8))) |  
    ((a(i,5)==x(9)) & (a(i,6)==x(10)) | 
    ((a(i,5)==x(11)) & (a(i,6)==x(12)))))
   q(i,:)=a(i,:);
end;
end;
q;
R1=a-q;
R1(~any(R1,2),:) = [];
R1(:, ~any(R1)) = [];

Here x and is a 12-size vector of real numbers, a is 924-by-6 matrix: a=combntns(x,6)

Question: Could anyone give an idea how to rewrite if-statement to improve readability of code?

Update. After the Andras Deak's comments and the Mingjing Zhang's answer I have tried to rewrite the code:

x=[784.8 959.2 468 572 279 341 139.5 170.5 76.5 93.5 45 55];
a = nchoosek(1:length(x), 6); %  all possible combinations from 6 indeces of x

success = any (mod(a(:,1:end-1), 2) & diff(a,1,2)==1);

n=length(a);
q=[];

for i=1:n
if()  
    q(i,:)=a(i,:);
end;
end;
q;
R1=a-q;

The all success(i) is true and I couldn't figure out how to use this logic in the if-statement. I have tried to write

for i=1:n
if(success(i))  
    q(i,:)=a(i,:);
end;
end;

but later I couldn't to use R1=a-q; because the the a and q sizes aren't equal.

Aucun commentaire:

Enregistrer un commentaire