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

LIBRARY “Fnmlib”
DECLARE DEF Factrl

DEF Get_Equation_Count            !Read the number of equations
WHEN ERROR IN
LET Count=0
DO
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 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}
‘**********************************************
‘**********************************************
WINDOW OFF
COORDINATE WINDOW
WINDOW 1
TEXT 0,12,0,0
PRINT@(1,3)”Item#”
‘
as soon as we’ve attached it to a menu item.
‘
‘now delete the name from the menu bar
‘
‘
‘Create a menu item with the command key equivalent of
‘CHR\$(27) and mark the item with the number of the
‘
‘
‘Use a negative insertion number(-1) and the handle to
‘should take place immediately after the root menu is created
‘
‘------------------------Events--------------------------------
“Loop”  ‘Loop and wait
GOTO “Loop” ‘Getting dizzy?
IF MenuID=1 AND ItemID=1 THEN END  ‘End if user selected “Quit”
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:

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Hopper Disassembler 5.14.1 - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more
WhatsApp 24.3.78 - Desktop client for Wh...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more
War Thunder 2.33.0.135 - Multiplayer war...
In War Thunder, aircraft, attack helicopters, ground forces and naval ships collaborate in realistic competitive battles. You can choose from over 1,500 vehicles and an extensive variety of combat... Read more
Iridient Developer 4.2 - Powerful image-...
Iridient Developer (was RAW Developer) is a powerful image-conversion application designed specifically for OS X. Iridient Developer gives advanced photographers total control over every aspect of... Read more

## Latest Forum Discussions

A Legitimate Massage Parlor, I Swear – T...
In this week’s Episode of The TouchArcade Show we talk about some of the major new releases on mobile this week including Warframe, we go over all the major news that came out from the Nintendo Direct Partner Showcase on Wednesday, we read our one... | Read more »
TouchArcade Game of the Week: ‘Rainbow S...
I feel like I am in a fever dream right now. What is this game that I’m playing? It’s a Rainbow Six game? But it’s all cutesy, and cartoony, and also kind of psychedelic? How is this a real thing? Well, it’s no fever dream, it is indeed a real thing... | Read more »
Hello gentle readers, and welcome to the SwitchArcade Round-Up for February 23rd, 2024. It’s Friday, so we have to check out the remaining releases of the week. Not so many big ones today, but a healthy crop nonetheless. After summarizing all the... | Read more »
Steam Deck Weekly: Gundam Breaker 4 and...
Welcome to this week’s slightly shorter edition of the Steam Deck Weekly. I was a bit unwell this week so no reviews in this edition, but there is a lot of news and new Steam Deck Verified and Playable games to catch up on. I have something special... | Read more »
The 10 Best Run-And-Gun Games for Ninten...
The year 2024 is a rare one, because it is a year with a brand-new Contra game. Contra: Operation Galuga might be the freshest face on the block when it comes to Nintendo Switch run-and-gun action games, but it’s hardly fighting that war alone.... | Read more »
Version 1.4 of Reverse: 1999 will be lan...
Free up your diary for February 29th, as Bluepoch has announced the impending release of the award-winning Reverse: 1999s Version 1.4 update. The Prisoner in the Cave is an Ancient Greece-themed update with new recruits, gameplay modes, and plenty... | Read more »
Premium Mobile RPG ‘Ex Astris’ From ‘Ark...
Arknights developer Hypergryph’s premium RPG Ex Astris () recently had its release date confirmed, and we finally have an extended gameplay showcase. | Read more »
Following yesterday’s big Hello Kitty Island Adventure update, a few more notable game updates and events have gone live on Apple Arcade. Cypher 007 () has gotten its first content update in a few months taking you to Egypt for five new levels... | Read more »
‘Thunder Ray’ and ‘Hime’s Quest’ Are Now...
Crunchyroll has pushed two new games into the Crunchyroll Game Vault including Purple Tree Studio’s Thunder Ray which was already on iOS before as a premium release. Shaun even reviewed it last year. Read his review here. The second game is Poppy... | Read more »
Ya’ll. This October will mark the ten-year anniversary of Hit Point launching Neko Atsume, the adorable kitty collecting sim that has become a runaway success and essentially created a sub-genre of cozy pet-collecting life sim games. Sure, the... | Read more »

## Price Scanner via MacPrices.net

16-inch M3 Max MacBook Pro on sale for \$300 o...
Amazon is offering a \$300 instant discount on one of Apple’s 16″ M3 Max MacBook Pros today. Shipping is free: – 16″ M3 Max MacBook Pros (36GB/1TB/Space Black): \$3199, \$300 off MSRP Their price is the... Read more
Apple M2 Mac minis on sale for \$100 off MSRP...
B&H Photo has Apple’s M2-powered Mac minis in stock and on sale for \$100 off MSRP this weekend with prices available starting at \$499. Free 1-2 day shipping is available to most US addresses: –... Read more
Apple Watch SE on sale for \$50 off MSRP this...
Best Buy has all Apple Watch SE models on sale this weekend for \$50 off MSRP on their online store. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
Deal Alert! Apple 15-inch M2 MacBook Airs on...
Looking for the lowest sale price on a new 15″ M2 MacBook Air? Best Buy has Apple 15″ MacBook Airs with M2 CPUs in stock and on sale today for \$300 off MSRP on their online store. Prices valid for... Read more
Amazon discounts iPad mini 6 models up to \$12...
Amazon is offering Apple’s 8.3″ WiFi iPad minis for \$100-\$120 off MSRP, including free shipping, for a limited time. Prices start at \$399. Amazon’s prices are among the lowest currently available for... Read more
Apple AirPods Pro with USB-C discounted to \$1...
Walmart has Apple’s 2023 AirPods Pro with USB-C in stock and on sale for \$199.99 on their online store. Their price is \$50 off MSRP, and it’s currently one the lowest prices available for new AirPods... Read more
Apple has 14-inch M3 MacBook Pro with 16GB of...
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
Save \$318-\$432 on 16-inch M3 Max MacBook Pros...
Apple retailer Expercom has 16″ M3 Max MacBook Pros on sale for \$318-\$432 off MSRP when bundled with a 3-year AppleCare+ Protection Plan. Discounts are available for Silver models as well a Space... Read more
New today at Apple: 16-inch M3 Pro/M3 Max Mac...
Apple is now offering 16″ M3 Pro and M3 Max MacBook Pros, Certified Refurbished, starting at \$2119 and ranging up to \$530 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple is now offering \$300-\$480 discounts on...
Apple is now offering 14″ M3 Pro and M3 Max MacBook Pros, Certified Refurbished, starting at \$1699 and ranging up to \$480 off MSRP. Each model features a new outer case, shipping is free, and an... Read more

## Jobs Board

Part-time *Apple* and Peach Research Assist...
…and minimum qualifications: + Assist with planting, pruning, and harvesting of apple and peach trees + Conduct regular maintenance tasks to ensure optimal Read more
Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and offer a Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Feb 22, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Jan 24, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more