Jump to content
Sign in to follow this  
logmein

Matrix Generate Script

Recommended Posts

logmein

Hi there!

I have been learning linear algebra in my university for months. The subject was rather hard, I did't understand it much so I sent a email to my teacher to ask him. But I realized that typing a matrix by text was extremely hard. I don't want to make a LaTex function, save to a file, attach it to the mail, bla bla bla!!! It's complicated! So I spent 2 hours yesterday to make this tool. Just type the number of lines and columns and matrix values, it will generate a quite nice matrix in ASCII characters :)

Enjoy!

Notes: It will rearrage your numbers to straight columns.

1x1 will cause error.

ConsoleWrite (@CRLF & '------------------------------------MATRIX TEST-----------------------------------------' &@CRLF)
Dim $c = 6;column
Dim $l = 4;line
Dim $n = '1,6,2,4,b,a,7,6,6,0,44,4,6,3,6,2,6,8,9,6,6,1,2,logmein'

$split = StringSplit ($n,',')
If $c * $l <> $split[0] Then
ConsoleWrite ('! Matrix values number do not match the columns and lines !' & @CRLF)
Exit
EndIf

Dim $char[$l][$c], $len[$l][$c], $maxlen[$c][3]



For $i = 0 To $l-1
For $u = 0 To $c -1
$v = $i*($c) + $u +1
$char[$i][$u] = $split[$v]
$len[$i][$u] = StringLen ($split[$v])
If $len[$i][$u] > $maxlen[$u][0] Then
$maxlen[$u][0] = $len[$i][$u]
$maxlen[$u][1] = $i
$maxlen[$u][2] = $u
EndIf
Next
Next

Local $finallen

For $u = 0 To $c - 1
$finallen += $maxlen[$u][0]
Next

ConsoleWrite (' _' & _Repeat(' ',$finallen + $c) & '_' & @CRLF)

For $i = 0 To $l-1;write lines
For $u = 0 To $c-1;write columns
$v = $i*($c) + $u +1
$char[$i][$u] = $split[$v]
Switch $u
Case 0; the first column
If StringLen ($char[$i][$u])<$maxlen[$u][0] Then
ConsoleWrite ('| ' & $char[$i][$u] & _Repeat(' ', $maxlen[$u][0]-StringLen ($char[$i][$u])+1))
Else

ConsoleWrite ('| ' & $char[$i][$u] & ' ')
EndIf

Case 1 To $c-2 ;middle columns
If $i > 0 Then
If StringLen ($char[$i][$u]) < $maxlen[$u][0] Then
ConsoleWrite ($char[$i][$u] & _Repeat(' ', $maxlen[$u][0]-StringLen ($char[$i][$u])+1))
Else
ConsoleWrite ($char[$i][$u] & ' ' )
EndIf
Else
If StringLen ($char[$i][$u]) < $maxlen[$u][0] Then
ConsoleWrite ($char[$i][$u] & _Repeat(' ', $maxlen[$u][0]-StringLen ($char[$i][$u])+1))
Else
ConsoleWrite ($char[$i][$u] & ' ' )
EndIf
EndIf


Case Else ; the last column
If StringLen ($char[$i][$u])<$maxlen[$u][0] Then
ConsoleWrite ($char[$i][$u] & _Repeat(' ', $maxlen[$u][0]-StringLen ($char[$i][$u])+1) & ' |' & @CRLF)
Else
ConsoleWrite ($char[$i][$u] & ' |' & @CRLF)
EndIf
EndSwitch

Next
Next


ConsoleWrite ('|_' & _Repeat(' ',$finallen + $c ) & '_|' & @CRLF)


Func _Repeat($chars, $times);repeat a character in a specified time
Local $rChar
For $a = 1 To $times
$rChar &= $chars
Next
Return $rChar
EndFunc ;==>_Repeat
Edited by logmein

Share this post


Link to post
Share on other sites
guinness

I have examples with 0 posts and 0 stars, so what is the problem?


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
spudw2k

No one cares?

Mod, please close this thread.

wah! :

Just like guinness said...

I have examples with 0 posts and 0 stars, so what is the problem?

We all experience this. If your intent was to get some sort of accolade from the community, better get used to disappointment.

Asking for a mod to close the post because you are un-pleased with the response demonstrates a lack of respect for the forum and is frankly a waste of time.

Who knows...maybe one day a member will come across your post and find it useful. I've experienced acknowledgment years after some of my posts.

Edited by spudw2k

Share this post


Link to post
Share on other sites
kylomas

logmein,

People not commenting on this script just means that whomever is reading it has nothing to say, it is not a reflection on you or the script. As spudw2k said, sometime in the future someone may run across this and need something from it.

With that in mind, I would like to show you another way to do this. Please accept this as intended, instructional only.

#include <GUIConstantsEx.au3>
#include <windowsConstants.au3>
#include <StaticConstants.au3>
#include <editConstants.au3>

local $str
local $numcols = 5          ; inital # columns
local $numents = 100        ; number of test entries to generate
local $entlngth= 5          ; length of each test entry

local $gui010   =   guicreate('Display Matrix',500)
local $size     =   WinGetClientSize($gui010)
local $edt010   =   guictrlcreateedit('',0,0,$size[0],$size[1]-30, bitor($es_readonly,$ws_hscroll, $ws_vscroll))
                    guictrlsetfont(-1,10,800,default,'courier new')
                    guictrlcreatelabel('Number of columns:',10,$size[1]-25,120,20)
                    guictrlsetfont(-1,8.5,600,default,'Lucinda Console')
local $inp010   =   guictrlcreateinput($numcols,130,$size[1]-25,40,20)
local $btn010   =   guictrlcreatebutton('Display Matrix',190,$size[1]-25,130,20)
                    guictrlsetfont(-1,10,800)
                    guictrlsetcolor(-1,0xaa0000)
local $btn020   =   guictrlcreatebutton('Re-Gen String  ',350,$size[1]-25,130,20)
                    guictrlsetfont(-1,10,800)
                    guictrlsetcolor(-1,0xaa0000)
guisetstate()

_GenRandomString()

While 1

    switch guigetmsg()
        case $gui_event_close
            Exit
        case $btn010
            _DisplayMatrix()
        case $btn020
            _GenRandomString()
            _DisplayMatrix()
    EndSwitch

wend

func _DisplayMatrix()

    local $a10 = stringsplit($str,','), $out = '',$numcols = guictrlread($inp010)
    guictrlsetdata($edt010,'')
    for $1 = 1 to $a10[0]

        ; $numcols is the number of columns per row.  This is controlled by using
        ; modulo integer arithmetic to insert a carrige return/line feed when we have processed $colnum entries
        ; from the input, in this case an array.
        ; The strings are padded using the stringformat function (similar to sprintf in "c")

        if mod($1,$numcols) = 0 then
            $out &= stringformat('%-' & $entlngth+3 & 's',$a10[$1]) & @crlf
        else
            $out &= stringformat('%-' & $entlngth+3 & 's',$a10[$1])
        endif
    Next

    guictrlsetdata($edt010,$out)

endfunc

func _GenRandomString()

    $str = ''
    for $1 = 1 to $numents
        for $2 = 1 to random(1,$entlngth,1)
            $str &= chr(random(65,90,1))
        next
        $str &= ','
    Next

endfunc

kylomas

edit: corrected spacing control

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites
Malkey

Personally, I prefer right aligned columns in the matrix display.

Local $c = 6 ; column
Local $l = 4 ; line
Local $Mat = '1,666,2,4,b,a,7,6,6,0,44,4,6,3,6,2,6,8,9,6,6,1,2,logmein'

ConsoleWrite(@CRLF & '------------------------------------MATRIX TEST (Right aligned) -----------------------------------------' & @CRLF)
_MatrixDisplay($Mat) ; Right aligned

ConsoleWrite(@CRLF & '------------------------------------MATRIX TEST (Left aligned) -----------------------------------------' & @CRLF)
_MatrixDisplay($Mat, 0) ; Left Aligned


Func _MatrixDisplay(ByRef $n, $iRightAlign = 1)
    Local $split = StringSplit($n, ',')

    ; Find array of Max. column width for each column.
    Local $aMax[$c]
    For $i = 1 To $split[0]
        If StringLen($split[$i]) > $aMax[Mod($i - 1, $c)]Then $aMax[Mod($i - 1, $c)] = StringLen($split[$i])
    Next

    ; Add appropiate number of spaces to each element depending on which column the element is in.
    Local $iRowLen = 0
    For $i = 1 To $split[0]
        If $iRightAlign = 1 Then
            $split[$i] = StringRight(_Repeat(" ", $aMax[Mod($i - 1, $c)] + 1) & $split[$i], $aMax[Mod($i - 1, $c)] + 1) ; Right aligned
        Else
            $split[$i] = StringLeft($split[$i] & _Repeat(" ", $aMax[Mod($i - 1, $c)] + 1), $aMax[Mod($i - 1, $c)] + 1) ; Left aligned
        EndIf
        If $i <= $c Then $iRowLen += StringLen($split[$i]) ; For use in top and bottom matrix display.
    Next

    ; Create matrix display
    Local $sMatrix = " _" & _Repeat(" ", $iRowLen) & "_" & @CRLF
    For $i = 1 To $l
        $sMatrix &= "| "
        For $u = 1 To $c
            $sMatrix &= $split[(($i - 1) * $c) + $u]
        Next
        $sMatrix &= " |" & @CRLF
    Next
    $sMatrix &= " -" & _Repeat(" ", $iRowLen) & "-" & @CRLF

    ConsoleWrite($sMatrix & @LF)
EndFunc   ;==>_MatrixDisplay

Func _Repeat($chars, $times);repeat a character in a specified time
    Local $rChar
    For $a = 1 To $times
        $rChar &= $chars
    Next
    Return $rChar
EndFunc   ;==>_Repeat

Share this post


Link to post
Share on other sites
logmein

@Malkey and @kylomas

Wow, thanks for your scripts! It's nice and simple! :thumbsup: :thumbsup:

@spudw2k

Uhm, I understood. Thanks! :bye:

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  

  • Similar Content

    • RTFC
      By RTFC
      Eigen4AutoIt Features:
      free, fast matrix computing environment for Windows (runs under Wine on Linux and Mac) built upon the robust Eigen code base (open-source), with many enhancements simple, intuitive functions, with extensive online documentation supports integer, single, and double precision, in real and complex matrices Tutorials with scripts, plus Test scripts for each function section easily exchange data between native binary files (.mat) and ASCII, Excel, and Xbase files, or AutoIt arrays 32-bit (x86-mode) and 64-bit (x64-mode) support in x64-mode, matrices can be any size that fits into available virtual memory (>4GB), and can be shared between processes over one thousand alias wrappers for flexibility and ease-of-use  
      The Eigen4AutoIt thread is here:
      This computing environment allows you to do matrix I/O (memory & files), matrix arithmetic, transformation, reduction, and decomposition, solve systems of linear equations, and perform statistics. Most functions can act on integer, real, or complex matrices (or the latter's real/imaginary parts separately). Much of the actual complexity of using Eigen in its native C++ environment has been hidden for AutoIt users, through extensive bounds and error checks, an intuitive function-naming convention, a large help file, and detailed tutorials and test examples.
    • RTFC
      By RTFC
      The Eigen C++ template library is a great environment for matrix computing; it is fast, reliable, extensive, and well-documented. It is also completely free, and does not rely on any external dependencies. Unfortunately for AutoIt users, the term “template library” implies that any functions you call are only instantiated upon compilation (in C++). That means there's nothing to hook into.
      To make Eigen ’s most important functionality directly accessible from within AutoIt scripts (version 3.3.12+, download it here), I developed the Eigen4AutoIt environment. It runs on Windows and under Wine also on Linux and Mac (Ubuntu, Debian, Fedora, and MacOS supported by WineHQ), and SUSE, Slackware, and FreeBSD supported by the distros).
      >Download the latest version

      It consists of:
      1) Eigen4AutoIt.au3
      an AutoIt library of wrapper functions that contain extensive bounds checks, matrix management, file I/O, type conversion, and precision control, and two-way data exchange with files and native AutoIt arrays;
      2) Eigen-wrapper dlls (EigenDense.dll, EigenDense_x64.dll)
      re-maps matrices created in AutoIt as Eigen Matrix objects, then calls Eigen’s powerful core functions; the single-precision part of the C++ source code I wrote is included in the bundle (the double-precision, integer, and complex alternatives just duplicate this with different memory mappings and variable types). The basic functions consist of a single Eigen call; decompositions and statistics are more involved. 3) Additional materials:
      the user-interactive, animated Function Selector and MatrixViewer tools the MatrixFileConverter to read/write E4A matrices from/to .csv ASCII, Excel, and Xbase files. three libraries of scientific and mathematical constants online Help Large (.chm) Help file Quickstart Manual (11-page pdf, updated) Test suite Tutorials from Basics to Advanced Please note:
      none of this is part of Eigen's own distribution you only need this bundle; you do not need to install Eigen. How it works:
      No matrix content is ever transferred, only memory pointers, meaning computations in AutoIt are virtually as fast as in Eigen’s native environment, with the added advantage of not having to be compiled first. The drawback is that Eigen's native ad-hoc expression templates (and their internal optimisations) cannot be exploited here; you have to construct your operations with the basic building blocks. These provide matrix creation, I/O, cellwise operations, reduction, multiplication, transformation, decomposition (LU, Householder, Choleski, and Jacobi SVD; these include general linear solvers) and a small statistics module by yours truly.

      IMPORTANT: Posting Rules for this thread:
       
      1) Do not post or PM me any matrix-, maths-, or Eigen-related questions. Eigen has its own User Forum for that (or try math.stackExchange.com). I am not your maths guru! If you post such questions, I will either ignore your post or remind you of this rule.

      2) Do not post or PM me your data sets and/or non-working Eigen4AutoIt scripts; I will not analyse your data or fix your scripts for you! There are many reasons why a linear algebra procedure might fail to produce the answer you expect. You are wielding great mathematical power here, so exploit the fantastic internet resources at your fingertips and learn how to use it. To get you started, I've listed a few video tutorials and other helpful materials in the header remarks of Eigen4AutoIt.au3. Also check out the test scripts, the Tutorials, and the Help file.

      3) I do warmly welcome all of the following:
      remarks, advice, suggestions for improvements, encouragement, cash; bug reports re. the Eigen4AutoIt interface (individual functions that don't work the way they should) and/or the associated dll code (ditto); your own working Eigen4AutoIt templates of general use that you'd like to see implemented in a future release. Regarding that last item, have a look at my PCA tutorial. After the step-by-step stage, I summarise the entire procedure in a "mini script" of Eigen4AutoIt calls. Then I introduce the two internal PCA functions I developed, which replace that script with two simple calls. You can do the same thing, and submit your own functional Eigen4AutoIt script in this thread. If I consider it of general use and can implement it, it may become a new Eigen4AutoIt function in the next release (with source acknowledgement, of course). This means that you'd get a precompiled dll version of your script that will likely run faster and be simpler to call. Thereby this thread would become an Eigen4AutoIt Example Scripts mini forum. It's just a thought.
       
      >Download the latest version (uncompressed size: 32.2 MB)
       
      How to Install
      You need AutoIt version 3.3.12 or later. Extraction (with 7-zip) creates subdirectory Eigen4AutoIt, where you'll find Eigen4AutoIt.ini. Open it, find global variable $EIGEN_DLLPATH, and copy/paste the full absolute path (without trailing backslash) where the Eigen4AutoIt dlls are located on your machine. Save the ini file, open the first tutorial ("intro") in Scite, and start it. This shows basic matrix I/O and mode switching (single versus double precision). If that runs, you're in business.
    • MrCheese
      By MrCheese
      hi all,
      Dumb question, but say I have a loop:
      dim $i Do     sleep(1000)          if $i = ; how do i do a function that enters this IF statement every 10 loops?         ; do stuff every 10     EndIf      Until $i = 100  
      - what commands in the if statement do I need to use to make it pass, and on every 10th loop, it enters the if statement. ?
       
      Thanks
    • jrsofsd
      By jrsofsd
      RunningStats calculates running (moving) statistics: Standard Deviation, Variance, and Mean . The single function _RunningStats(), queries, clears, restores, or adds to the running statistics.
      Example.au3 adds 7 samples of data to running statistics and displays the results using _ArrayDisplay().
      Example-Persistent-Storage.au3 adds the first 6 samples to the running statistics and stores the results in an INI file. The data is read from the INI file and restored to the running statistics. The 7th sample is added and the results displayed, matching the results from Example.au3.
      Credits: John D. Cook for his article "Accurately computing running variance" at http://www.johndcook.com/blog/standard_deviation/
      RunningStats.zip
    • scintilla4evr
      By scintilla4evr
      I started writing this UDF a while ago, so I decided to share it here.
      This is an UDF full of advanced mathematical functions. It allows to work with primes, create number sequences, interpolate, calculate values of functions like Riemann zeta.
      Full list of functions:
       
      Changelog:
      Download
×