MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

# How can i create a sparse matrix out of arrays??

Asked by John on 5 May 2013

Hello dear community,

i have a question concerning the creation of a sparse matrix for the use of the bioinformatics toolbox, especially referring to the plot function, called "view":

In the description of the toolbox, there is this example of how to create a graph and plot it:

```W = [.41 .99 .51 .32 .15 .45 .38 .32 .36 .29 .21];
DG = sparse([6 1 2 2 3 4 4 5 5 6 1],[2 6 3 5 4 1 6 3 4 3 5],W)
h = view(biograph(DG,[],'ShowWeights','on'))
```

This works perfectly. My problem is, that i´d like to do it the following way, with arrays a and b consisting of the integers above.

```DG = sparse(a,b,W)
h = view(biograph(DG,[],'ShowWeights','on'))
```

When doing so there is the error:

```>>??? Error using ==> biograph.biograph at 155
```
```>>CM must be a sparse or full square matrix
```

So my question is, if theres is apossibilty of doing it my way. My programm produces arrays , i.e. a and not those kind of numbers [1,2,3] als arguments. How can i solve the problem?

i am thankful for every help.

With best regards, John

## 1 Comment

John Doe on 5 May 2013

This works perfectly for me:

```a = [6 1 2 2 3 4 4 5 5 6 1];
b = [2 6 3 5 4 1 6 3 4 3 5];
W = [.41 .99 .51 .32 .15 .45 .38 .32 .36 .29 .21];
DG = sparse(a,b,W);
h = view(biograph(DG,[],'ShowWeights','on'))
Biograph object with 6 nodes and 11 edges.
```

I get the same plots as above.

Have you checked that DG is infact a sparse matrix?

## Products

Answer by John on 10 May 2013

Hi people,

you helped me a lot by making up my mind. It actually works well now.

Many thanks!!! thumbs up for your quick help;)

Answer by Matt J on 5 May 2013

If this is what you did, then the error is not in the code you've shown

```    W = [.41 .99 .51 .32 .15 .45 .38 .32 .36 .29 .21];
a = [6 1 2 2 3 4 4 5 5 6 1];
b = [2 6 3 5 4 1 6 3 4 3 5];```
`    DG = sparse(a,b,W); `

As you can see, a sparse matrix DG is produced

```>> whos DG
```
`   Name      Size            Bytes  Class     Attributes`
```DG        6x6               232  double    sparse
```