octaveoctave-gui

How to read a matrix from STDIN in Octave


This is how the input look like. The first line of input is the square matrix size.

3
1 2 3
4 5 6
7 8 9

Solution

  • Here is one way. There are many others.

    DataStr   = fileread( 'data.txt' )               # read in whole file
    StrTokens = strsplit( DataStr )                  # split into string tokens
    Tokens    = cellfun( @str2double, StrTokens )    # convert string tokens to numerical
    NumRows   = Tokens(1)                            # First token gives number of rows
    NumElems  = NumRows ^ 2                          # Total number of elements in matrix
    Elems     = Tokens(2 : 1 + NumElems)             # select appropriate elements from tokens
    Matrix    = reshape( Elems, [NumRows, NumRows] ) # reshape into square matrix
    

    This reads from a file. If you want to 'pipe' input to this as an octave script instead, you can replace the first line with something like:

    DataStr   = fread( stdin, 'char' )
    DataStr   = char( DataStr.' )
    

    This means you could call this from a linux terminal as follows:

    echo -e "3\n1 2 3\n2 3 4\n3 4 5" | octave myscript.m