“Unexpected MATLAB expression” when creating sparse graph

后端 未结 3 627
清歌不尽
清歌不尽 2021-01-29 14:16

I have tried following code for creating sparse graph in MATLAB:

cm = sparse([1 1 2 2 3 3 4 5],[2 3 4 5 4 5 6 6],...
     [2 3 3 1 1 1 2 3],6,6)cm =
3条回答
  •  迷失自我
    2021-01-29 14:48

    The MATLAB documentation has a typo, harmless to people with existing MATLAB background, but perhaps difficult to identify by beginners. To quote the MATLAB document,

    cm = sparse([1 1 2 2 3 3 4 5],[2 3 4 5 4 5 6 6],...
      [2 3 3 1 1 1 2 3],6,6)cm =
    
    (1,2)        2
    (1,3)        3
    (2,4)        3
    (3,4)        1
    (2,5)        1
    (3,5)        1
    (4,6)        2
    (5,6)        3
    

    What it really meant to say was the following:

    cm = sparse([1 1 2 2 3 3 4 5],[2 3 4 5 4 5 6 6],...
      [2 3 3 1 1 1 2 3],6,6)
    
    cm =
    
    (1,2)        2
    (1,3)        3
    (2,4)        3
    (3,4)        1
    (2,5)        1
    (3,5)        1
    (4,6)        2
    (5,6)        3
    

    Notice that cm = is now on a new line and merely indicates the beginning of the output produced by the sparse function. What you have to do to create the sparse matrix from this example is to write

    cm = sparse([1 1 2 2 3 3 4 5],[2 3 4 5 4 5 6 6],...
                [2 3 3 1 1 1 2 3],6,6)
    

    This will give you the desired result.

    In general, as some of the commenters pointed out, I would suggest going through a basic MATLAB tutorial before proceeding to more complex topics such as sparse matrices and graphs.

提交回复
热议问题