0

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!

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
dtr43
  • 135
  • 7
  • 19
  • 1
    I don't understand... [here](https://stackoverflow.com/a/55085475/7328782) you got code that creates the adjacency matrix. `glcms` in that code is an adjacency matrix. All you need to do is `Adjm = glcms` and you're done. Why do you need to do all of this? – Cris Luengo Apr 18 '19 at 20:41
  • 1
    Also, "I don't know how to access to cell array's elements; so an adhoc method was used." You are indexing `Al{i}`, that is not an adhoc method, that is the normal and correct method to get the contents of a cell in a cell array. – Cris Luengo Apr 18 '19 at 20:42
  • @CrisLuengo, OMG!, I forgot about that . I was looking for a method such as the submitted answer. By the way, thank you for the reminder. – dtr43 Apr 19 '19 at 12:48

1 Answers1

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.

Phil Goddard
  • 10,571
  • 1
  • 16
  • 28