Parametric Subs (Task)

advertisement
Lab 5:
Array variables with two indices (Matrices). Sub with parameters
a)
1. Product of two matrices
2 4 3
1 3 2 -1
0 -2 0 5
2
-1
0
1
4 1
0 1
5 -6
0 0
Input of matrices A and B from matrices.txt file (A and B are
„Global” for the given Module Sheet)
Writing Function Scal#(i%,j%) using the former Scalar Function
n
Using Scal for evaluating A*B
b)
c)
matrix A
1
0
skali, j    Ai, k   Bk , j 
3
-2
2
0
-1
5
-2
7
14
0
-8
-2
2
-1
0
1
4
0
5
0
1
1
-6
0
matrix B
2. Sub with parameters
Option Explicit
Dim A(5, 5) As Double, b#(5)
Dim n%, k%, t#
Sub linear()
Dim i%, j%
Open "lin.txt" For Input As #1
<reads matrix A and vector b>
Close #1
Call MyWrite (1)
For i = 1 To 2
<reads the ‘factor’ and
the number ‘which’ (row will be
multiplied by the ‘factor’), and
executes the multiplication>
Call MyWrite (i + 1)
Next i
End Sub
3
1 3 2 9
2 4 -1 -5
1 5 1 2
Results
k 1
Function Scalar(n%, x#(), y#()) As Double
Dim sum#, j%
sum = 0
For j = 1 To n
sum = sum + x(j) * y(j)
Next j
Scalar = sum
End Function
Sub MyWrite(SeqNo As Integer)
Dim which%, r%, c%
which = (SeqNo - 1) * (n + 1) + 2
Cells(which, 1) = "Step " + CStr(SeqNo)
If SeqNo = 1 Then
Cells(which, 2) = " Matrix A and vector b "
Else
Cells(which, 2) = "row=" + CStr(k)
Cells(which, 3) = "factor=" + CStr(t)
End If
For r = 1 To n
For c = 1 To n
Cells(which + r, c) = A(r, c)
Next c
Cells(which + r, n + 1) = b(r)
Next r
End Sub
Lab 5:
Homework: Solving a system of linear equations by Gauss-Jordan elimination
Input data (the augmented matrix of a linear system)
is given in the file lin.txt , the output you see right
1x + 3y + 2z = 9
2x + 4y – 1z = -5
1x + 5y + 1z = 2
Extend the previous program such that first reading by InputBox the
integers k and s, and the double t, the program does the following:
(A) if k s then it multiplies the kth row of the augmented matrix by t,
and substracts it from the sth row
(B) if k=s then it divides the kth row of the augmented matrix by t
Using the steps (A) and (B) solve the given linear system, for the
values of k, s and t (or p) considering the hints below.
For output use the Sub MyWrite
Hint: Use in the program For-Next Loops given below::
For k=1 to n
by t=a(k,k)
divide the elements of the kth row
For s=1 to n
if k <> s then
p=a(s,k)
the system
Factor=2 ; 1. row from 2. row
A
Factor=1 ; 1. row from 3. row
Factor=1 ; 2. row from 3. row
Divisor=6 ; for 3. row
Factor= -5 ; 3. row from 2. row
Factor=2 ; 3. row from 1. row
A
A
B
A
A
substract from the sth row the kth row times p
Divisor=2 ; for 2. row
B
Factor=3 ; 2. row from 1. row
A
Download