TweetFollow Us on Twitter

Matrices
Volume Number:4
Issue Number:9
Column Tag:Basic School

Matrices in True Basic

By Dave Kelly, MacTutor Editorial Board

Using Cramer’s Rule and True Basic to Solve Simultaneous Equations

It is only a matter of time until each Engineering or Math student comes across the need to solve simultaneous equations. Fortunately, we live in a time when someone has already figured out the solutions and we can readily use the methods which have been discovered. In this column I hope to show how True Basic’s MAT statements can be used with Cramer’s Rule to solve simultaneous equations.

In most areas of engineering, the time comes from time to time to solve equations. Many of these solutions can be found using a pencil and paper and a little bit of logical thinking. We learn from algebra that to solve a set of equations, there needs to be one equation generated for each unknown variable. It is the responsibility of the engineer to use his expertise in his field of study to determine what the equations are. The solution of the equations are sometimes trivial, but may take time to manipulate the equations with simple algebra. Eventually the answer is found.

Computers are supposed to make life easier. Right? Well, of course! So let’s see how we can solve some equations using True Basic. First, we need a problem to solve: We want to find the current in each of three paths of a circuit. The circuit is shown in figure 1.

To determine the equations which we will use to solve the problem we will use Ohm’s law and Kirchhoff’s voltage law. For the non-engineer, Ohm’s law is a mathematical way to express the relationship between voltage, current, and resistance:

E = I * R

Figure 1.

where R is resistance, E is the voltage across the resistance, I is the current through the resistance. This simple law is basic to a beginning electronics class. Ohm’s law is named after a German physicist, George Simon Ohm, who published a pamphlet in 1827 which contained the results of his efforts to describe and relate currents and voltages mathematically. It has since been shown, however, that this result was discovered 46 years earlier in England by Henry Cavendish.

Kirchhoff’s voltage law is named after Gustav Robert Kirchhoff, a German university professor who was born about the time Ohm was doing his experimental work. Kirchhoff’s law states that the algebraic sum of the voltages around any closed path in a circuit is zero. I won’t attempt to prove this as there are many electronics books which explain how Kirchhoff’s voltage law works.

Figure 2.

Our first equation is derived by taking the loop shown in Figure 2. The path of the loop does is not important as long as the path is closed. The equation is:

-7 + 1(i1 - i2) + 3 (i3 - i2) + 1i3 = 0

which equates to:

i1 - 4i2 + 4i3 = 7.

Our second equation is derived by taking the loop where current i2 is as shown in Figure 1. The equation is:

1(i2 - i1 ) + 2 i2  + 3(i2 - i3) = 0

which equates to:

-i1 - 6i2 - 3i3 = 0.

The last equation comes from the relationship of the current source and the currents i1 and i2:

i1 - i3  =  7.

Now we have three equations and three unknown values to solve for. An easy method to use is given by Cramer’s Rule. Gabriel Cramer (1704-1752), was a Swiss mathematician, also known by his book on the theory of curves, which appeared in 1750 in Geneva. Cramer’s Rule states that if we have a system of linear equations

a11x1 + a12x2 + + a1nxn = b1,
a21x1 + a22x2 + + a2nxn = b2,
            ,
an1x1 + an2x2 + + annxn = bn

with n equations and n unknowns., the n X n coefficient matrix of the system is denoted by A. The determinant A 0, the components of the solution of the system are given by the formula,

where the matrix Bk is the same as A except that the elements aik, 1 ¾ i ¾ n, in the kth column of A have been replace by the terms bi, 1 ¾ i ¾ n, respectively.

Cramer’s Rule says that n simultaneous equations with n unknowns can be determined by taking determinants of the matrix. Each of the unknowns is calculated as follows:

and

and

and

where

The great thing about this is that with True Basic the solution is easy to calculate because of the MAT statements included in True Basic. MAT statements include MAT INPUT (for inputing an array), MAT LINE INPUT, MAT PLOT (plotting to a True Basic chart), MAT PRINT (to print a matrix, MAT READ (read an array from data statements), MAT REDIM (to reset dimensions of a matrix), and MAT WRITE (to write an array to a file). The MAT statement is an enhancement to Basic that is very welcome in the scientific/engineering community. It has been included for many years in Hewlett Packard Basic (now version 5.0).

Using Cramer’s Rule by hand the evaluation of the determinant for i3 is:

evaluation of the other determinants gives i1= 9 Amps and i2= 2.5 Amps. The evaluation of these determinants are fairly easy by hand, but with more equations and more unknowns, the it gets to be a lot of number crunching. The program at the end will do the number crunching for an n X n matrix, limited by the amount of memory you have. The number of equations is calculated in a function which uses the factorial function included in the True Basic Libraries to figure how much data is available in the DATA statements. The coefficients are entered into the DATA statements with equation coefficients in the first DATA statement and the solution coefficients in the second DATA statement. For solving for a large number of equations/unknowns you may break up the DATA into multiple lines.

Once the number of equations is determined, the program calls the sim_solve subroutine to solve the equation. Since the MAT statement does all the work, the subroutine is short and after a couple of MAT assignment statements, the matrix is ready to be crunched. True Basic also supplies us with the det function which will automatically calculate the determinant of an n X n matrix. It sure beats keeping track of a bunch of numbers by hand like I did when I went to school. Calculations are now done and our circuit has been analyzed! Now if they would only put a Mac on my desk I could use it!

{1}
! Simultaneous Equation Solver
! Dave Kelly
! ©1988 MacTutor

LIBRARY “Fnmlib”
DECLARE DEF Factrl

DEF Get_Equation_Count            !Read the number of equations
    WHEN ERROR IN
         LET Count=0
         DO
            READ value
            LET Count=Count+1
         LOOP
    USE
         RESTORE
    END WHEN
    LET n=0
    DO
       LET n=n+1
    LOOP UNTIL Factrl(n)>Count
    LET Count=n-1
    LET Get_Equation_Count=Count
END DEF

! Start Main Program
LET number_of_equations=Get_Equation_Count
DIM a(2,2),b(2,2),c(2,1),x(2)
! Set up all the equations
MAT READ a(number_of_equations,number_of_equations)
MAT READ c(number_of_equations,1)
MAT REDIM x(number_of_equations)
CALL sim_solve(a,b,c,x,number_of_equations)
MAT PRINT x                       ! Print the solutions
DATA 1,-4,4,-1,6,-3,1,0,-1        ! equation coefficients
DATA 7,0,7                        ! equation data
END

SUB sim_solve(a(,),b(,),c(,),x(),number_of_equations)
    IF det(a)=0 THEN EXIT SUB
    FOR j=1 to number_of_equations
        MAT b=a
        FOR i= 1 to number_of_equations
            LET b(i,j)=c(i,1)
        NEXT i
        LET x(j)=det(b)/det(a)
    NEXT j
END SUB

Someone told Dave Kelly that he was a programmer. They were kind, but not very accurate. His article “Hierarchical Menus & Colors Notes” [VOL. 4 NO. 6] contained more errors than accuracies. He claims that ZBasic source code must be compiled and the resources attached to make use of them. Why not use the function: “RefNum% = FN OPENRESFILE(FileName$)”?

This makes resources available during the programming phase and requires the deletion of only one command before creating the application.

The next glaring error was his slap-dash program that should have shown how to use submenus from ZBasic.[Excuse me, but I showed A way to to submenus from ZBasic, not THE only way. Actually, I like your way better now that you have shown it to us. Thanks -DK] As the following program demonstrates, submenus do not require special event handling loops, nor is it necessary to append special resources.

{2}
‘**********************************************
‘                    SubMenus from ZBasic
‘**********************************************
WINDOW OFF
COORDINATE WINDOW
WINDOW 1
TEXT 0,12,0,0
PRINT@(1,1)”MENU#”
PRINT@(1,3)”Item#”
‘----------------------Set The Menu------------------
MENU 1,0,1,”File”:MENU 1,1,1,”Quit/Q”
‘
SubMenu=150 ‘This is the number we’ll use for our SubMenu
MENU SubMenu,0,1,”I’m outa here”  ‘We’ll delete this from the menu bar 
as soon as we’ve attached it to a menu item.
MENU SubMenu,1,1,”Plain/P;Bold/B<B;Italic/I<I;Outline/O<O;Shadow/S<S”
SubMenuHndl&=FN GETMHANDLE(SubMenu)  ‘Handle to the SubMenu
‘
‘now delete the name from the menu bar
‘CALL DELETEMENU(SubMenu)  ‘(the menu itself still remains available)
‘
MENU 2,0,1,”Format”‘We’ll add the submenu here
‘
‘Create a menu item with the command key equivalent of
‘CHR$(27) and mark the item with the number of the
‘SubMenu instead of a “2” for a check mark
‘
MenuName$=”Style/”+CHR$(27)
MENU 2,1,SubMenu,MenuName$
‘
‘Use a negative insertion number(-1) and the handle to
‘our SubMenu - the “CALL INSERTMENU(SubMenuHandle,-1)”
‘should take place immediately after the root menu is created
‘
CALL INSERTMENU(SubMenuHndl&,-1)
MENU 2,2,1,”Itz Eazy With Z”  ‘Add more items and menus if you like
CALL DRAWMENUBAR ‘Redraw the bar to exclude the hidden menu
‘------------------------Events--------------------------------
ON MENU GOSUB “Handle Menu”
MENU ON ‘We’ll just track menu events
“Loop”  ‘Loop and wait
GOTO “Loop” ‘Getting dizzy?
MENU OFF
“Handle Menu”’----------------Menu Handling------------------
MenuID=MENU(0)
ItemID=MENU(1)
MENU  ‘Get results of the menu action
IF MenuID=1 AND ItemID=1 THEN END  ‘End if user selected “Quit”
PRINT@(9,1)MenuID”       “
PRINT@(9,3)ItemID”       “ ‘Else-Show menu info
RETURN  ‘Back to the “Loop”

Wake up, Dave. And try to spend a little time developing your programming skills and a little less time throwing rocks.

Regards

Chris Stasny

Well, Chris it seems you have a little chip on your shoulder about something (Do you work for Zedcor?). In my defense, there are many “programmers” out there that have had trouble getting ZBasic event processing to do everything they want it to do. It is true that some of the problems have been fixed as the users have been debugging ZBasic ever since it was released! In my opinion, there is no Basic available today for the Macintosh which is satisfactory for doing serious software development as there are glaring holes in their capabilities. I’ve had too many phone calls from disgruntled developers trying to find a solution to their problems with no solution in sight. Call it rock throwing if you like, but face it, there isn’t any such thing as LightSpeed Basic. Thank you for your letter. We encourage others to share the technology by writing for MacTutor. We are dedicated to the distribution of useful programming information without regard to race, creed or developer status. Chris, we never claim to know everything. We could use more of your good ideas. Write to MacTutor and ask for our authors kit and share some of your “expertise”.

Dave Kelly

I’m a new subscriber to MacTutor and have particularly enjoyed your column “Basic School”. I’m a BASIC programmer and frankly don’t have the time to really learn the other high level languages such as C or Pascal. It is, therefore, heartening to find a source of instruction for BASIC on the MAC.

Do you think it would be feasible to compile your articles into a separate volume? I believe such a book would sell quite well. There are many recreational and small application programmers who both love BASIC and the MAC. Keep up the great work.

Sincerely,

Julian Wan

Thank you for your kind remarks. I’ve had several people ask for a separate volume of “Basic School”. Because of the cost of publishing another compiled book and since we already offer the “Best of MacTutor” Vol 1 and 2 for a reasonable price, “Basic School” will not become a volume of its own. Have heart though, I’ve used information from C, Pascal, and assembly language columns many times and so having the other language available in “Best of MacTutor” can actually help when writing BASIC programs too. I’ve also compiled a MacTutor Index HyperCard Stack which can help when you are trying to learn about a specific subject.

Dave Kelly

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »

Price Scanner via MacPrices.net

Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more
Best Buy is clearing out iPad Airs for up to...
In advance of next week’s probably release of new and updated iPad Airs, Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices for up to $200 off Apple’s MSRP, starting at $399. Sale prices... Read more
Every version of Apple Pencil is on sale toda...
Best Buy has all Apple Pencils on sale today for $79, ranging up to 39% off MSRP for some models. Sale prices for online orders only, in-store prices may vary. Order online and choose free shipping... Read more
Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.