“Unexpected MATLAB expression” when creating sparse graph

后端 未结 3 626
清歌不尽
清歌不尽 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:42

    Congratulations, you have found a bug in the MATLAB documentation!

    The cm = at the end belongs on the next line and is actually the output MATLAB gives you when you type

    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)
    

    MATLAB uses linebreaks to signify the end of a command unless you end the line with ..., and after the closing bracket on your second line it doesn't understand what the cm is supposed to mean ;-)

    0 讨论(0)
  • 2021-01-29 14:48

    You shouldn't write the cm = part at the end. That is, when you 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)
    

    on the command line, you will get

    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
    

    This is because, you didn't write a semicolon at the end of the statement. If you don't want to see the value of cm, just add a semicolon after the closing the parentheses. In addition ... tells to write multi-line statement. You can 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)
    

    alternatively.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题