Sign in to follow this  
Followers 0
XuxinhaKill

File to matrix help

5 posts in this topic

Hey I need to read a file and save in a matrix of ints but dont know how to do it... something like that:

File content:

564 507

570 480

Matrix content:

[0][0] = 564

[0][1] = 507

[1][0] = 570

[1][1] = 480

Hope you can help me guys.

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

I guess there are several UDFs that will do this. Anyway I have written some example code which I hope will help you.

#include <Array.au3> ; Needed for _ArrayDisplay()

Local $FileData = _ ; This data can be obtained using FileRead()
"564 507" & @CRLF & _
"570 480"
MsgBox(0, "$FileData", $FileData)

Local $aArray = StringSplit($FileData, @CRLF, 1) ; Split each line - Alternatively use _FileReadToArray() instead of FileRead() above.

Local $iRows = $aArray[0], $iCols = 0
For $i = 1 To $iRows ; This step can be omitted if we know how many columns we need.
    If StringInStr($aArray[$i], " ", 2, $iCols +1) Then ; Test each line for the delimiter string - Space
        While StringInStr($aArray[$i], " ", 2, $iCols +1)
            $iCols += 1
        WEnd
    EndIf
Next
$iCols += 1

Local $aTemp, $aMatrix[$iRows][$iCols]
For $i = 1 To $iRows
    $aTemp = StringSplit($aArray[$i], " ")
    For $j = 1 To $aTemp[0]
        $aMatrix[$i -1][$j -1] = $aTemp[$j]
    Next
Next

_ArrayDisplay($aMatrix)

MsgBox(0, "[0][0]", $aMatrix[0][0])
MsgBox(0, "[0][1]", $aMatrix[0][1])
MsgBox(0, "[1][0]", $aMatrix[1][0])
MsgBox(0, "[1][1]", $aMatrix[1][1])
Edited by czardas

Share this post


Link to post
Share on other sites

Pretty much the same thing. Remove the "2" parameter from StringSplit() if you like the usefullness of having the count in the first array element.

#include <Array.au3> ; Needed for _ArrayDisplay()
Local $FileData = "564 507" & @CRLF & "570 480" ; This data can be obtained using FileRead()
MsgBox(0, "$FileData", $FileData)

$string = StringReplace($FileData, @CRLF, " ")
MsgBox(0, "$FileData", $string)

Local $aArray = StringSplit($string, " ", 2) ;
_ArrayDisplay($aArray)

Share this post


Link to post
Share on other sites

Thanks a lot guys! Really helped me!

Share this post


Link to post
Share on other sites

XuxinhaKill, I forgot to welcome you to the forum. I'm happy if the code helps you. Merry Christmas. :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0