lundi 27 avril 2015

How to call multiple functions using if statement?

I want to perform the following function using if statement which has variables in it. Consider three cell arrays A, B and C of size 16 x 16 each.for example I'm just taking 4 x 4 cell arrays.

 A = A B C D            B = C A B D          C = 0 2 1 3               
     D C B A                B D A C              3 2 3 1              
     C B D A                A B A D              2 1 0 1                     
     B A D C                D A A C              3 2 2 2

with respect to the values in C I need to perform functions on A and B as follows,

if C == 0
   Out = B;
elseif C == 1
   Out = complement (B);
elseif C == 2
   Out = XX(A,B);
elseif C == 3
   Out = NX(A,B);
end 

Here complement, XX and NX are the functions that are to be called. I tried the following code but somehow 'if' statement is making it hard to get the results. I've defined the functions as well as the code I used to perform the above operation.

   for i=1:1:16
      for j=1:1:16
         if C(i,j) == 0
            O(i,j) = B(i,j);
         elseif C(i,j) == 1
               O(i,j) = XX(A(i,j),B(i,j));
         elseif C(i,j) == 2
               O(i,j) = complement(B(i,j)); 
          elseif C(i,j) == 3
               O(i,j) = NX(i,j);
          end
       end end

The function complement is as follows

  function [Q]=complement(P)
  [W1,W2] = size(P);
  Q = zeros(W1,W2);
  P1 = cell2mat(P)
  for i=1:1:W1
     for j=1:1:W2
         if P1 == 'A'
           Q(i,j) == 'D';
         elseif P1 == 'B'
               Q(i,j) == 'C';
         elseif P1 == 'C'
               Q(i,j) == 'B';
         elseif P1 == 'D'
               Q(i,j) == 'A';
         end  end  end

The function XX is as follows function [Q] = XX(T,P) T = cell2mat(T); P = cell2mat(P);

  Q(T == 'A'  & P == 'A') = 'A'; Q(T == 'A'  & P == 'B') = 'B'; Q(T == 'A'  & P == 'C') = 'C'; Q(T == 'A'  & P == 'D') = 'D';
  Q(T == 'B'  & P == 'A') = 'B'; Q(T == 'B'  & P == 'B') = 'A'; Q(T == 'B'  & P == 'C') = 'D'; Q(T == 'B'  & P == 'D') = 'C';
  Q(T == 'C'  & P == 'A') = 'C'; Q(T == 'C'  & P == 'B') = 'D'; Q(T == 'C'  & P == 'C') = 'A'; Q(T == 'C'  & P == 'D') = 'B';
  Q(T == 'D'  & P == 'A') = 'D'; Q(T == 'D'  & P == 'B') = 'C'; Q(T == 'D'  & P == 'C') = 'B'; Q(T == 'D'  & P == 'D') = 'A';

The function NX is similar to XX only substitution differs. I don't know where I'm going wrong either in the functions or in the 'if' statement. When I run the code the first if statement and the 'first if statement' from the complement function alone are getting executed, the remaining functions are not performed. Thanks.

Aucun commentaire:

Enregistrer un commentaire