Creating an adjacency matrix from a cell array

Refresh

April 2019

Views

25 time

1

I'm going to create an adjacency matrix from a cell array, but faced two main problems:

  1. I don't know how to access to cell array's elements; so an adhoc method was used.

  2. (and the most important) The code produces an error and the partial result is also a weird one!

The cell array is as the following image: screen shot of MATLAB's variable editor showing the contents of a cell array

The code is as follows:

for i=1:N
    L=size(Al{i});
    Len=L(1,2);
    for j=1:Len
        elm=Al{i};
        D=elm(i,j);
        Adjm(i,D)=1;
    end
end

The code produces this error:

screen shot of the MATLAB command window showing an error message

and the output is as follows: yet another screen shot showing defined variables

P.S.: The code is part of a program to construct adjacency matrix to represent superpixels adjacency within an image. There may be a specific solution for that!

1 answers

4

There are lots of ways your code could be made better, but the specific error you are seeing is because you want D=elm(1,j); instead of D=elm(i,j);. Note the 1 instead of i.

A somewhat more efficient approach would be to do,

for i=1:numel(Al)
    Adjm(i,Al{i})=1;
end

As with your code, this assumes that there are no empty elements in Al.