Search code examples
arraysmatlabcell-array

assign a cell to a cell array


I have the following matrix :

 adj =     O1   O2    O3    O4    S1    S2    S3    S4    S5

 O1        0     0     0     0     0     1     1     0     0
 O2        0     0     0     0     0     1     0     1     0
 O3        0     0     0     0     0     1     1     0     0
 O4        0     0     0     0     0     0     0     1     1
 S1        0     0     1     0     0     0     0     0     0
 S2        0     1     0     0     0     0     0     0     0
 S3        0     1     1     0     0     0     0     0     0
 S4        0     1     0     1     0     0     0     0     0
 S5        0     0     0     1     0     0     0     0     0

I have a cellarray nodeNames that contains the labels of the lines and columns of my matrix so :

nodeNames = {O1 O2 O3 O4 S1 S2 S3 S4 S5}

I want to do the following: browse the matirce adj in the lines from the nodes S (i = 5: 9) and for the columns the nodes O (j = 1; 4) if adj (i, j) = 1 then get the label of the node Oj from nodeNames and put it in the cell w {i} of a new cellarray that we will name w. so I want to have the following:

w{1}={O3}.
w{2}={O2}.
w{3}={O2 O3}.
w{4}={O2 O4}.
w{5}={O4}.

I have tried to do that but I get an empty cellarray in my result :

for i=5 : 9
    k=1;
    for j=1:4
        if adj(i,j)==1;
            w{i}{k}=nodeNames{j};
        end
        k=k+1;
    end
end

I know that the problem is in the assignment to the cellarray w but can't get the right one , Any suggestion ?


Solution

  • nodeNames or nodNames, also your k=k+1 must be in the if-statement.

    adj=[0,0,0,0,0,1,1,0,0;0,0,0,0,0,1,0,1,0;0,0,0,0,0,1,1,0,0;0,0,0,0,0,0,0,1,1;0,0,1,0,0,0,0,0,0;0,1,0,0,0,0,0,0,0;0,1,1,0,0,0,0,0,0;0,1,0,1,0,0,0,0,0;0,0,0,1,0,0,0,0,0]==1;
    nodeNames = {'O1','O2','O3','O4','S1','S2','S3','S4','S5'};
    w={};
    for i = 5:9
        k=1;
        for j=1:4
            if adj(i,j)
            w{i-4,k}=nodeNames{j};
            k=k+1;
            end
        end
    end
    

    Result:

    w =
    
      5×2 cell array
    
        'O3'      []
        'O2'      []
        'O2'    'O3'
        'O2'    'O4'
        'O4'      []