Quantcast
Viewing all articles
Browse latest Browse all 24

How to populate Matrix from a text file

AmiBroker 6.00 has introduced support for matrices. After we create a matrics with Matrix function call:

my_var_name Matrixrowscolsinitvalue);

then in order to access matrix elements, we need to use:

my_var_namerow ][ col ];

However – if we want to populate a relatively large matrix with values generated in other programs, then it may not be very practical to do it by hand in the AFL code assigning individual elements like this:

A][ ] = 1A][ ] = 4A][ ] = 6;

What we can do in such case is to store the values in a text file that we could use as input, then read through the file using fgets function and populate Matrix elements using a looping code. A sample formula showing how to perform such task is presented below.

A sample text file for this example can be found here: http://www.amibroker.com/kb/wp-content/uploads/2015/10/samplematrix.txt

// the input file path
file "C:\\samplematrix.txt";

// define the size of the desired matrix
rows 16;
cols 16;

// create matrix
myMatrix Matrixrowscols);

// open file
fh fopenfile"r" );

if( fh )
{
    0;

    // iterate through the lines of input file
    for( 0; ! feoffh ) AND rowsi++ ) 
    {
        // read a line of text
        line fgetsfh ); 

        if( line == "" )
        {
            Error("Too few rows in the data file or an empty row found");
            break;
        }
    
        // iterate through the elements of the line
        for( 0; ( item StrExtractline) ) != "" AND colsj++ ) 
        {
            // assign matrix element
            myMatrix][ ] = StrToNumitem );
        }
        
        if( cols )
        {
            Error("Too few columns in data file");
            break;
        }
    }
    
    fclosefh );
}
else
{
    Error"ERROR: file can not be opened" );
}

// spot check selected element
Title "spot check M[ 2 ][ 3 ]: " NumToStrMyMatrix][ ] );

Viewing all articles
Browse latest Browse all 24

Trending Articles