matlabif-statementmatrixfor-else

constructing a matrix in matlab using if, elseif and else


Can anyone help me with this. I am trying to construct a matrix in matlab using if, elseif and else but it does not work for me. If I skip the last else everything works correctly but if I run everything, including the last else sentence, elseif N==L(i) and elseif N==R(i) does not work. So if I skip the last else sentence if N==1, elseif N>=2 && N<=4, elseif N>=5 && N<=9, elseif N==L(i) and elseif R==L(i) runs correctly but if I run everything elseif N==L(i) and elseif R==L(i) does not work.

N = 72; 
M = 72;
adj = zeros(N,M)
L = [10:7:M-13]
R = [16:7:M-7]




for N = 1:M
    for i = 1:ceil((M-10)/15)

    if N==1
        adj(1,2:4)= 1

    elseif N>=2 && N<=4

              adj(N,(N+3))=1
              adj(N,(N+4))=1
              adj(N,(N+5))=1

      elseif N>=5 && N<=9

              adj(N,(N+5))=1
              adj(N,(N+6))=1
              adj(N,(N+7))=1

      elseif N==L(i)

              adj(N,N+7)=1
              adj(N,N+8)=1


      elseif N==R(i)

              adj(N,N+6)=1
              adj(N,N+7)=1

    else
              adj(N,N+6)=1
              adj(N,N+7)=1
              adj(N,N+8)=1    
    end


    end
end

Solution

  • Try using a switch case statement

    N = 72; 
    M = 72;
    adj = zeros(N,M);
    L = [10:7:M-13];
    R = [16:7:M-7];
    
    for N = 1:M
        for i = 1:ceil((M-10)/15)
    
            switch(N)
    
                case {1}
                   adj(1,2:4)= 1;
    
                case {2:4}
                  adj(N,(N+3))=1;
                  adj(N,(N+4))=1;
                  adj(N,(N+5))=1;
    
                case {5:9}
                  adj(N,(N+5))=1;
                  adj(N,(N+6))=1;
                  adj(N,(N+7))=1;
    
                case {L(i)}
                  adj(N,N+7)=1;
                  adj(N,N+8)=1;
    
                case {R(i)}
                  adj(N,N+6)=1;
                  adj(N,N+7)=1;
    
                otherwise
                  adj(N,N+6)=1;
                  adj(N,N+7)=1;
                  adj(N,N+8)=1;  
                end
    
    
        end
    end
    

    This gives a slightly different answer to your code. Note that only the first satisfying case will be triggered. So if both {5:9} and {L(i)} are true, only the {5:9} case will be triggered.

    Also, it may be just a typo, or me not understanding the wording, but you are writing R==L(i) in your description but that doesn't appear in your code.

    Edit:
    From your comment below, it seems you want more than one elseif or case statement to be triggered at a time. In this case, neither a series of elseifs or cases will work. Simply replace all the elseifs with separate, indivdiual if statements, without any elseifs. Just be aware that now any if statement can trigger, including the ones you don't intend to. So you will have to look carefully at each condition.