SlideShare a Scribd company logo
CS110: Matrix operations in C
Lecture 10
V. Kamakoti
29th January 2008
Arrays
• Matrix is
– A two dimensional array
– Array of one dimensional arrays

• Stored in memory
– Row-wise (Row Major order)
– Column-wise (Column Major order)
Storage of matrix
• A - 2X3 matrix has elements
– A[0][0],A[0][1],A[0][2];
– A[1][0],A[1][1],A[1][2];
– A[2][0],A[2][1],A[2][2];

• Assume it is an integer matrix and
A[0][0] is stored at 1000
Row-major order
• Store the first row, then, the second,
then, the third and so on…
• A - 2X3 matrix has elements
– A[0][0],A[0][1],A[0][2]; stored at 1000-1011
– A[1][0],A[1][1],A[1][2]; stored 1012 - 1023
– A[2][0],A[2][1],A[2][2]; stored 1024 - 1035
Column-major order
• Store the first column, then, the second
column, then, the third and so on..
• A - 2X3 matrix has elements
– A[0][0],A[1][0],A[2][0]; stored at 1000-1011
– A[0][1],A[1][1],A[2][1]; stored 1012 - 1023
– A[0][2],A[1][2],A[2][2]; stored 1024 - 1035

• The C compiler assumes Row major order.
Lab - 3
• Write a program that reads in the
entries of a 3 by 3 matrix, and prints it
out in the form of a matrix. The entries
could be floating point entries too.
Solution
#include<stdio.h>
main() {
int i,j, a[3][3];
for (i = 0; i <= 2; i++) {
for (j = 0; j <=2; j++) {
printf(“Enter a[%d][%d] n”,i,j);
scanf(“%d”,&a[i][j]);
}
}
}
What Happens
for (i = 0; i <= 2; i++) {
for (j = 0; j <=2; j++)
{
printf(“Enter a[%d][%d] n”,i,j);
scanf(“%d”,&a[i][j]);
}
}
For every i, 0 <= i <= 2, j repeats thrice taking values
0,1 and 2. Therefore when i = 0 and j = 0, a[0][0]
shall be read in, when i = 0 and j = 1, a[0][1] shall be
read in and so on ….
To Print
for (i = 0; i <= 2; i++) {
for (j = 0; j <=2; j++)
{
printf(“%d ”,a[i][j]);
}
printf(“n”);
}
Print all elements of a given row on the same
line with a space in between. After one row is
printed go to the next line.
You have to
• Repeat above for Floating point numbers
• The effort would be to
– Format the output properly
– Let p be a floating point number
– printf(“%16f”,..) prints a floating point with 16
spaces - if less then blanks are introduced.
– Use the tab escape sequence “t” to align.
– This would be true for integers too.
Next in Lab - 3
• Write a program that reads in orders of two
matrices and decides whether two such
matrices can be multiplied. Print out the
decision.
main() {
int row1,col1,row2,col2;
printf(“Enter number of rows and columns in
Matrix 1 n”);
scanf(“%d %d”,&row1,&col1);
//Similarly for Matrix 2
if (col1 != row2) { printf(“Not possiblen”); exit(0);
} // To use exit() we need to include <stdlib.h>
Next in Lab - 3
• Write a program that reads in two
arbitrary matrices and multiplies them.
Your output should be the two matrices
and the resulting product matrix.
Matrix Multiplication : Outline
main() {
1. declare all variables required
2. read in Matrix A
3. read in Matrix B
4. check if A and B are compatible to be multiplied
5. initialize Matrix C to have zeroes to begin with
6. multiply A and B to give C
7. print Matrix C
}

Of course, all the steps above have to
follow C language’s syntax rules
Using Matrix Operations :
Read a Matrix
main(){
int a[11][11], b[11][11], c[11][11]; / *max size 10 by 10 */
int i,j,k;
int aRows, aCols, bRows, bCols, cRows, cCols;
scanf("%d%d", &aRows, &aCols);
for(int i = 1; i <= aRows; i++)
for(int j = 1; j <= aCols; j++)
scanf("%d", &a[i][j]);
/*continued on next slide */
Read the other Matrix; Initialize the product
scanf("%d%d", &bRows, &bCols);
for(i = 1; i <= bRows; i++)
for(j = 1; j <= bCols; j++)
scanf("%d", &b[i][j]);
/* initialize entries in Matrix c to 0 */
for(i = 1; i <= aRows; i++)
for(j = 1; j <= bCols; j++)
c[i][j] = 0;
Remember
/*continued on next slide */

bRows must equal aCols
c is a aRows x bCols matrix
Matrix multiplication
bRows
Multiply two numbers

aRows

aCols
Sum of N products
Multiply Matrices and Print the
Result
/* multiply both the matrices and store in matrix c */
for(i =1; i <= aRows; i++)
for(j = 1; j <= bCols; j++)
for(k = 1; k <= aCols; k++)
c[i][j] += a[i][k]*b[k][j];
/* print matrix c */
for(i = 1; i <= aRows; i++){
for(j = 1; j <= bCols; j++) /* print a row */
printf("%d ", c[i][j]); /* notice missing n */
printf("n");
/* print a newline at the end a row */
}
}
/* End of main program */
Points to Ponder
• Some repetition in the program
– Reading in matrix A seems to be similar to reading
in matrix B
• Except for changes in the number of rows and columns

• You will learn how to write functions in C later
– Functions are written to avoid repeated actions
– Example C program would look like
readMat(A, aRows, aCols);
readMat(B, bRows, bCols);

– Function readMat( ) must perform the operations
desired
Celebrity Problem
(More efficient Solution)‫‏‬

There are n persons in a room. A person is called a celebrity
iff everyone knows him but he does not know anyone. So by
definition if at all there is a celebrity there can be only one.
The problem is to find if there is a celebrity among the people
in the room and if there is one identify him, by asking
questions. The only kind of question allowed is “Does A know
B?”.
Celebrity Problem
(Naivest Solution)‫‏‬
'Naivest' Solution:
For each pair of persons A and B,
ask the questions, does A know B and does B know A. Build
the nxn matrix {aij}. is 1 if the ith person knows the jth person
and it is 0 otherwise. Now if there is a column i, which
contains all 1s, and if row i contains all 0s except the
diagonal, then the person i is a celebrity. If there is no such i,
then there is no celebrity.
Number of questions asked = n*(n-1)‫‏‬
Celebrity Problem
(Better Solution)‫‏‬
Choose two persons A and B. Ask if
A knows B. If answer is yes, then A cannot be the celebrity. If
answer is no, then B cannot be the celebrity. So one person
gets eliminated. Now if at all there is a celebrity he will be in
the remaining n-1 persons. Keep eliminating in this fashion.
After n-1 questions, only one person X, will be left. For each
person Y ≠ X, ask if Y knows X and X knows Y. Hence we
can find if X is actually a celebrity.
Number of questions asked = n-1 + 2n-2 = 3n-3
Celebrity Problem
(Best Solution)‫‏‬
Simplifying assumption: n = 2^k
Group the persons into pairs. So we will have n/2
pairs. In each pair (A, B) eliminate one person by asking if A
knows B. Now we will be left with n/2 persons. Repeat the
process till we are left with only one person.
Number of times this process in repeated is
obviously k, since each time the number reduces by half.

(cont.)‫‏‬
Celebrity Problem
(Best Solution)‫‏‬
We can keep track of the tree thus obtained. Let us take a
case having 8 persons. The tree looks likes something below.

1

2

3

1

4

5

4

6

6

4

8

7

6

4

7

So totally 7 Qs asked.
This is a binary tree with a root,
leaves and children (at most 2).
Learn more about this later
Generalizing above
• Given N people
– N/2 Qs in level 1
– N/4 Qs in level 2
– 1 Question in level k, where, N = 2k
– So total is N(1/2 + 1/4 + …1/2k)
– N (1/2) ( 1 - 1/2k)/(1/2)
– N - N/2k = N - 1
Celebrity Problem
(Best Solution)‫‏‬
Clearly, if at all there is a celebrity, it can be only 4.
Also note that out of the 2n-2(= 6) questions asked to confirm
whether 4 is actually a celebrity, we have already asked
log2n (= 3) questions (Notice the yellow circles). So once we
maintain this tree, the number of additional questions that we
need to ask is 2n – 2 – log2n.
Therefore the total number of questions asked in this case is
n-1 + 2n – 2 – log2n = 3n – 3 – log2n.
There exists no algorithm which can do better than this, the
proof of which is beyond the scope of this lecture. Extending
it for n not a power of 2 is also interesting.
Thank You

More Related Content

What's hot

8th Alg - L6.8--Jan30
8th Alg - L6.8--Jan308th Alg - L6.8--Jan30
8th Alg - L6.8--Jan30
jdurst65
 
Module 9 Topic 1 - Adding & Subtracting polynomials
Module 9 Topic 1 - Adding & Subtracting polynomialsModule 9 Topic 1 - Adding & Subtracting polynomials
Module 9 Topic 1 - Adding & Subtracting polynomials
Lori Rapp
 
Linear algebra
Linear algebraLinear algebra
Adding Polynomials
Adding PolynomialsAdding Polynomials
Adding Polynomials
chulitt
 
Punnett squares presentation teachership academy
Punnett squares presentation teachership academyPunnett squares presentation teachership academy
Punnett squares presentation teachership academy
Beth819
 
Chapter11
Chapter11Chapter11
Chapter11
Erica McLaurin
 
Algeopordy
AlgeopordyAlgeopordy
Algeopordy
Jessica
 
AS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMS
AS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMSAS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMS
AS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMS
RACSOelimu
 
Probabilistic programming2
Probabilistic programming2Probabilistic programming2
Probabilistic programming2
bredelings
 
Graph functions
Graph functionsGraph functions
Graph functions
Shakila Safri
 
Factorisation
FactorisationFactorisation
Factorisation
yashwant kondeti
 
20100528
2010052820100528
20100528
byron zhao
 
Factoring and Box Method
Factoring and Box MethodFactoring and Box Method
Factoring and Box Method
swartzje
 
Module 2 exponential functions
Module 2   exponential functionsModule 2   exponential functions
Module 2 exponential functions
dionesioable
 
Multiplying Monomials
Multiplying MonomialsMultiplying Monomials
Multiplying Monomials
swartzje
 
Identity matrix
Identity matrixIdentity matrix
Identity matrix
phyene
 

What's hot (16)

8th Alg - L6.8--Jan30
8th Alg - L6.8--Jan308th Alg - L6.8--Jan30
8th Alg - L6.8--Jan30
 
Module 9 Topic 1 - Adding & Subtracting polynomials
Module 9 Topic 1 - Adding & Subtracting polynomialsModule 9 Topic 1 - Adding & Subtracting polynomials
Module 9 Topic 1 - Adding & Subtracting polynomials
 
Linear algebra
Linear algebraLinear algebra
Linear algebra
 
Adding Polynomials
Adding PolynomialsAdding Polynomials
Adding Polynomials
 
Punnett squares presentation teachership academy
Punnett squares presentation teachership academyPunnett squares presentation teachership academy
Punnett squares presentation teachership academy
 
Chapter11
Chapter11Chapter11
Chapter11
 
Algeopordy
AlgeopordyAlgeopordy
Algeopordy
 
AS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMS
AS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMSAS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMS
AS LEVEL Function (CIE) EXPLAINED WITH EXAMPLE AND DIAGRAMS
 
Probabilistic programming2
Probabilistic programming2Probabilistic programming2
Probabilistic programming2
 
Graph functions
Graph functionsGraph functions
Graph functions
 
Factorisation
FactorisationFactorisation
Factorisation
 
20100528
2010052820100528
20100528
 
Factoring and Box Method
Factoring and Box MethodFactoring and Box Method
Factoring and Box Method
 
Module 2 exponential functions
Module 2   exponential functionsModule 2   exponential functions
Module 2 exponential functions
 
Multiplying Monomials
Multiplying MonomialsMultiplying Monomials
Multiplying Monomials
 
Identity matrix
Identity matrixIdentity matrix
Identity matrix
 

Similar to Lec10-CS110 Computational Engineering

Matrices
MatricesMatrices
Matrices
Mike Hoad
 
Matrices & Determinants.pdf
Matrices & Determinants.pdfMatrices & Determinants.pdf
Matrices & Determinants.pdf
SUCCESSSCIENCEACADEM
 
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjekAIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
pavan402055
 
Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programming
Damian T. Gordon
 
[This sheet must be completed and attached to the last page of.docx
[This sheet must be completed and attached to the last page of.docx[This sheet must be completed and attached to the last page of.docx
[This sheet must be completed and attached to the last page of.docx
hanneloremccaffery
 
Maths Problems - Qwizdom ppt
Maths Problems - Qwizdom pptMaths Problems - Qwizdom ppt
Maths Problems - Qwizdom ppt
Qwizdom UK
 
Recursion - Computer Algorithms
Recursion - Computer AlgorithmsRecursion - Computer Algorithms
Recursion - Computer Algorithms
Alaa Al-Makhzoomy
 
matrix
matrixmatrix
2010 assessment review_homework_1-4-done
2010 assessment review_homework_1-4-done2010 assessment review_homework_1-4-done
2010 assessment review_homework_1-4-done
jendailey
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanations
Gopi Saiteja
 
Math 116 pres. 5
Math 116 pres. 5Math 116 pres. 5
Mit6 006 f11_quiz1
Mit6 006 f11_quiz1Mit6 006 f11_quiz1
Mit6 006 f11_quiz1
Sandeep Jindal
 
Discrete_Matrices
Discrete_MatricesDiscrete_Matrices
Discrete_Matrices
guest78c418
 
Real number system full
Real  number  system fullReal  number  system full
Real number system full
Aon Narinchoti
 
Real number system full
Real  number  system fullReal  number  system full
Real number system full
Aon Narinchoti
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
Puja Koch
 
ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)
CrackDSE
 
Nbhm m. a. and m.sc. scholarship test september 20, 2014 with answer key
Nbhm m. a. and m.sc. scholarship test september 20, 2014 with answer keyNbhm m. a. and m.sc. scholarship test september 20, 2014 with answer key
Nbhm m. a. and m.sc. scholarship test september 20, 2014 with answer key
MD Kutubuddin Sardar
 
Algebreviewer
AlgebreviewerAlgebreviewer
Algebreviewer
Angelina Pascua Lumbre
 
Algebreviewer
AlgebreviewerAlgebreviewer
Algebreviewer
Angelina Pascua Lumbre
 

Similar to Lec10-CS110 Computational Engineering (20)

Matrices
MatricesMatrices
Matrices
 
Matrices & Determinants.pdf
Matrices & Determinants.pdfMatrices & Determinants.pdf
Matrices & Determinants.pdf
 
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjekAIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
AIMA_ch3_L2-complement.ppt kjekfkjekjfkjefkjefkjek
 
Introduction to MatLab programming
Introduction to MatLab programmingIntroduction to MatLab programming
Introduction to MatLab programming
 
[This sheet must be completed and attached to the last page of.docx
[This sheet must be completed and attached to the last page of.docx[This sheet must be completed and attached to the last page of.docx
[This sheet must be completed and attached to the last page of.docx
 
Maths Problems - Qwizdom ppt
Maths Problems - Qwizdom pptMaths Problems - Qwizdom ppt
Maths Problems - Qwizdom ppt
 
Recursion - Computer Algorithms
Recursion - Computer AlgorithmsRecursion - Computer Algorithms
Recursion - Computer Algorithms
 
matrix
matrixmatrix
matrix
 
2010 assessment review_homework_1-4-done
2010 assessment review_homework_1-4-done2010 assessment review_homework_1-4-done
2010 assessment review_homework_1-4-done
 
Answers withexplanations
Answers withexplanationsAnswers withexplanations
Answers withexplanations
 
Math 116 pres. 5
Math 116 pres. 5Math 116 pres. 5
Math 116 pres. 5
 
Mit6 006 f11_quiz1
Mit6 006 f11_quiz1Mit6 006 f11_quiz1
Mit6 006 f11_quiz1
 
Discrete_Matrices
Discrete_MatricesDiscrete_Matrices
Discrete_Matrices
 
Real number system full
Real  number  system fullReal  number  system full
Real number system full
 
Real number system full
Real  number  system fullReal  number  system full
Real number system full
 
Dsoop (co 221) 1
Dsoop (co 221) 1Dsoop (co 221) 1
Dsoop (co 221) 1
 
ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)ISI MSQE Entrance Question Paper (2008)
ISI MSQE Entrance Question Paper (2008)
 
Nbhm m. a. and m.sc. scholarship test september 20, 2014 with answer key
Nbhm m. a. and m.sc. scholarship test september 20, 2014 with answer keyNbhm m. a. and m.sc. scholarship test september 20, 2014 with answer key
Nbhm m. a. and m.sc. scholarship test september 20, 2014 with answer key
 
Algebreviewer
AlgebreviewerAlgebreviewer
Algebreviewer
 
Algebreviewer
AlgebreviewerAlgebreviewer
Algebreviewer
 

More from Sri Harsha Pamu

Lec23-CS110 Computational Engineering
Lec23-CS110 Computational EngineeringLec23-CS110 Computational Engineering
Lec23-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec21-CS110 Computational Engineering
Lec21-CS110 Computational EngineeringLec21-CS110 Computational Engineering
Lec21-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec19-CS110 Computational Engineering
Lec19-CS110 Computational EngineeringLec19-CS110 Computational Engineering
Lec19-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec15-CS110 Computational Engineering
Lec15-CS110 Computational EngineeringLec15-CS110 Computational Engineering
Lec15-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec14-CS110 Computational Engineering
Lec14-CS110 Computational EngineeringLec14-CS110 Computational Engineering
Lec14-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec13
Lec13Lec13
Lec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringLec12-CS110 Computational Engineering
Lec12-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec09-CS110 Computational Engineering
Lec09-CS110 Computational EngineeringLec09-CS110 Computational Engineering
Lec09-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec08-CS110 Computational Engineering
Lec08-CS110 Computational EngineeringLec08-CS110 Computational Engineering
Lec08-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec07-CS110 Computational Engineering
Lec07-CS110 Computational EngineeringLec07-CS110 Computational Engineering
Lec07-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec06-CS110 Computational Engineering
Lec06-CS110 Computational EngineeringLec06-CS110 Computational Engineering
Lec06-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec04-CS110 Computational Engineering
Lec04-CS110 Computational EngineeringLec04-CS110 Computational Engineering
Lec04-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec03-CS110 Computational Engineering
Lec03-CS110 Computational EngineeringLec03-CS110 Computational Engineering
Lec03-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec02-CS110 Computational Engineering
Lec02-CS110 Computational EngineeringLec02-CS110 Computational Engineering
Lec02-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec01-CS110 Computational Engineering
Lec01-CS110 Computational EngineeringLec01-CS110 Computational Engineering
Lec01-CS110 Computational Engineering
Sri Harsha Pamu
 
Lec1- CS110 Computational Engineering
Lec1- CS110 Computational EngineeringLec1- CS110 Computational Engineering
Lec1- CS110 Computational Engineering
Sri Harsha Pamu
 
Lec25-CS110 Computational Engineering
Lec25-CS110 Computational EngineeringLec25-CS110 Computational Engineering
Lec25-CS110 Computational Engineering
Sri Harsha Pamu
 
Android..imp google
Android..imp googleAndroid..imp google
Android..imp google
Sri Harsha Pamu
 
Android vulnerability study
Android vulnerability studyAndroid vulnerability study
Android vulnerability study
Sri Harsha Pamu
 

More from Sri Harsha Pamu (20)

Lec23-CS110 Computational Engineering
Lec23-CS110 Computational EngineeringLec23-CS110 Computational Engineering
Lec23-CS110 Computational Engineering
 
Lec21-CS110 Computational Engineering
Lec21-CS110 Computational EngineeringLec21-CS110 Computational Engineering
Lec21-CS110 Computational Engineering
 
Lec19-CS110 Computational Engineering
Lec19-CS110 Computational EngineeringLec19-CS110 Computational Engineering
Lec19-CS110 Computational Engineering
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
Lec15-CS110 Computational Engineering
Lec15-CS110 Computational EngineeringLec15-CS110 Computational Engineering
Lec15-CS110 Computational Engineering
 
Lec14-CS110 Computational Engineering
Lec14-CS110 Computational EngineeringLec14-CS110 Computational Engineering
Lec14-CS110 Computational Engineering
 
Lec13
Lec13Lec13
Lec13
 
Lec12-CS110 Computational Engineering
Lec12-CS110 Computational EngineeringLec12-CS110 Computational Engineering
Lec12-CS110 Computational Engineering
 
Lec09-CS110 Computational Engineering
Lec09-CS110 Computational EngineeringLec09-CS110 Computational Engineering
Lec09-CS110 Computational Engineering
 
Lec08-CS110 Computational Engineering
Lec08-CS110 Computational EngineeringLec08-CS110 Computational Engineering
Lec08-CS110 Computational Engineering
 
Lec07-CS110 Computational Engineering
Lec07-CS110 Computational EngineeringLec07-CS110 Computational Engineering
Lec07-CS110 Computational Engineering
 
Lec06-CS110 Computational Engineering
Lec06-CS110 Computational EngineeringLec06-CS110 Computational Engineering
Lec06-CS110 Computational Engineering
 
Lec04-CS110 Computational Engineering
Lec04-CS110 Computational EngineeringLec04-CS110 Computational Engineering
Lec04-CS110 Computational Engineering
 
Lec03-CS110 Computational Engineering
Lec03-CS110 Computational EngineeringLec03-CS110 Computational Engineering
Lec03-CS110 Computational Engineering
 
Lec02-CS110 Computational Engineering
Lec02-CS110 Computational EngineeringLec02-CS110 Computational Engineering
Lec02-CS110 Computational Engineering
 
Lec01-CS110 Computational Engineering
Lec01-CS110 Computational EngineeringLec01-CS110 Computational Engineering
Lec01-CS110 Computational Engineering
 
Lec1- CS110 Computational Engineering
Lec1- CS110 Computational EngineeringLec1- CS110 Computational Engineering
Lec1- CS110 Computational Engineering
 
Lec25-CS110 Computational Engineering
Lec25-CS110 Computational EngineeringLec25-CS110 Computational Engineering
Lec25-CS110 Computational Engineering
 
Android..imp google
Android..imp googleAndroid..imp google
Android..imp google
 
Android vulnerability study
Android vulnerability studyAndroid vulnerability study
Android vulnerability study
 

Recently uploaded

How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 

Recently uploaded (20)

How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 

Lec10-CS110 Computational Engineering

  • 1. CS110: Matrix operations in C Lecture 10 V. Kamakoti 29th January 2008
  • 2. Arrays • Matrix is – A two dimensional array – Array of one dimensional arrays • Stored in memory – Row-wise (Row Major order) – Column-wise (Column Major order)
  • 3. Storage of matrix • A - 2X3 matrix has elements – A[0][0],A[0][1],A[0][2]; – A[1][0],A[1][1],A[1][2]; – A[2][0],A[2][1],A[2][2]; • Assume it is an integer matrix and A[0][0] is stored at 1000
  • 4. Row-major order • Store the first row, then, the second, then, the third and so on… • A - 2X3 matrix has elements – A[0][0],A[0][1],A[0][2]; stored at 1000-1011 – A[1][0],A[1][1],A[1][2]; stored 1012 - 1023 – A[2][0],A[2][1],A[2][2]; stored 1024 - 1035
  • 5. Column-major order • Store the first column, then, the second column, then, the third and so on.. • A - 2X3 matrix has elements – A[0][0],A[1][0],A[2][0]; stored at 1000-1011 – A[0][1],A[1][1],A[2][1]; stored 1012 - 1023 – A[0][2],A[1][2],A[2][2]; stored 1024 - 1035 • The C compiler assumes Row major order.
  • 6. Lab - 3 • Write a program that reads in the entries of a 3 by 3 matrix, and prints it out in the form of a matrix. The entries could be floating point entries too.
  • 7. Solution #include<stdio.h> main() { int i,j, a[3][3]; for (i = 0; i <= 2; i++) { for (j = 0; j <=2; j++) { printf(“Enter a[%d][%d] n”,i,j); scanf(“%d”,&a[i][j]); } } }
  • 8. What Happens for (i = 0; i <= 2; i++) { for (j = 0; j <=2; j++) { printf(“Enter a[%d][%d] n”,i,j); scanf(“%d”,&a[i][j]); } } For every i, 0 <= i <= 2, j repeats thrice taking values 0,1 and 2. Therefore when i = 0 and j = 0, a[0][0] shall be read in, when i = 0 and j = 1, a[0][1] shall be read in and so on ….
  • 9. To Print for (i = 0; i <= 2; i++) { for (j = 0; j <=2; j++) { printf(“%d ”,a[i][j]); } printf(“n”); } Print all elements of a given row on the same line with a space in between. After one row is printed go to the next line.
  • 10. You have to • Repeat above for Floating point numbers • The effort would be to – Format the output properly – Let p be a floating point number – printf(“%16f”,..) prints a floating point with 16 spaces - if less then blanks are introduced. – Use the tab escape sequence “t” to align. – This would be true for integers too.
  • 11. Next in Lab - 3 • Write a program that reads in orders of two matrices and decides whether two such matrices can be multiplied. Print out the decision. main() { int row1,col1,row2,col2; printf(“Enter number of rows and columns in Matrix 1 n”); scanf(“%d %d”,&row1,&col1); //Similarly for Matrix 2 if (col1 != row2) { printf(“Not possiblen”); exit(0); } // To use exit() we need to include <stdlib.h>
  • 12. Next in Lab - 3 • Write a program that reads in two arbitrary matrices and multiplies them. Your output should be the two matrices and the resulting product matrix.
  • 13. Matrix Multiplication : Outline main() { 1. declare all variables required 2. read in Matrix A 3. read in Matrix B 4. check if A and B are compatible to be multiplied 5. initialize Matrix C to have zeroes to begin with 6. multiply A and B to give C 7. print Matrix C } Of course, all the steps above have to follow C language’s syntax rules
  • 14. Using Matrix Operations : Read a Matrix main(){ int a[11][11], b[11][11], c[11][11]; / *max size 10 by 10 */ int i,j,k; int aRows, aCols, bRows, bCols, cRows, cCols; scanf("%d%d", &aRows, &aCols); for(int i = 1; i <= aRows; i++) for(int j = 1; j <= aCols; j++) scanf("%d", &a[i][j]); /*continued on next slide */
  • 15. Read the other Matrix; Initialize the product scanf("%d%d", &bRows, &bCols); for(i = 1; i <= bRows; i++) for(j = 1; j <= bCols; j++) scanf("%d", &b[i][j]); /* initialize entries in Matrix c to 0 */ for(i = 1; i <= aRows; i++) for(j = 1; j <= bCols; j++) c[i][j] = 0; Remember /*continued on next slide */ bRows must equal aCols c is a aRows x bCols matrix
  • 16. Matrix multiplication bRows Multiply two numbers aRows aCols Sum of N products
  • 17. Multiply Matrices and Print the Result /* multiply both the matrices and store in matrix c */ for(i =1; i <= aRows; i++) for(j = 1; j <= bCols; j++) for(k = 1; k <= aCols; k++) c[i][j] += a[i][k]*b[k][j]; /* print matrix c */ for(i = 1; i <= aRows; i++){ for(j = 1; j <= bCols; j++) /* print a row */ printf("%d ", c[i][j]); /* notice missing n */ printf("n"); /* print a newline at the end a row */ } } /* End of main program */
  • 18. Points to Ponder • Some repetition in the program – Reading in matrix A seems to be similar to reading in matrix B • Except for changes in the number of rows and columns • You will learn how to write functions in C later – Functions are written to avoid repeated actions – Example C program would look like readMat(A, aRows, aCols); readMat(B, bRows, bCols); – Function readMat( ) must perform the operations desired
  • 19. Celebrity Problem (More efficient Solution)‫‏‬ There are n persons in a room. A person is called a celebrity iff everyone knows him but he does not know anyone. So by definition if at all there is a celebrity there can be only one. The problem is to find if there is a celebrity among the people in the room and if there is one identify him, by asking questions. The only kind of question allowed is “Does A know B?”.
  • 20. Celebrity Problem (Naivest Solution)‫‏‬ 'Naivest' Solution: For each pair of persons A and B, ask the questions, does A know B and does B know A. Build the nxn matrix {aij}. is 1 if the ith person knows the jth person and it is 0 otherwise. Now if there is a column i, which contains all 1s, and if row i contains all 0s except the diagonal, then the person i is a celebrity. If there is no such i, then there is no celebrity. Number of questions asked = n*(n-1)‫‏‬
  • 21. Celebrity Problem (Better Solution)‫‏‬ Choose two persons A and B. Ask if A knows B. If answer is yes, then A cannot be the celebrity. If answer is no, then B cannot be the celebrity. So one person gets eliminated. Now if at all there is a celebrity he will be in the remaining n-1 persons. Keep eliminating in this fashion. After n-1 questions, only one person X, will be left. For each person Y ≠ X, ask if Y knows X and X knows Y. Hence we can find if X is actually a celebrity. Number of questions asked = n-1 + 2n-2 = 3n-3
  • 22. Celebrity Problem (Best Solution)‫‏‬ Simplifying assumption: n = 2^k Group the persons into pairs. So we will have n/2 pairs. In each pair (A, B) eliminate one person by asking if A knows B. Now we will be left with n/2 persons. Repeat the process till we are left with only one person. Number of times this process in repeated is obviously k, since each time the number reduces by half. (cont.)‫‏‬
  • 23. Celebrity Problem (Best Solution)‫‏‬ We can keep track of the tree thus obtained. Let us take a case having 8 persons. The tree looks likes something below. 1 2 3 1 4 5 4 6 6 4 8 7 6 4 7 So totally 7 Qs asked. This is a binary tree with a root, leaves and children (at most 2). Learn more about this later
  • 24. Generalizing above • Given N people – N/2 Qs in level 1 – N/4 Qs in level 2 – 1 Question in level k, where, N = 2k – So total is N(1/2 + 1/4 + …1/2k) – N (1/2) ( 1 - 1/2k)/(1/2) – N - N/2k = N - 1
  • 25. Celebrity Problem (Best Solution)‫‏‬ Clearly, if at all there is a celebrity, it can be only 4. Also note that out of the 2n-2(= 6) questions asked to confirm whether 4 is actually a celebrity, we have already asked log2n (= 3) questions (Notice the yellow circles). So once we maintain this tree, the number of additional questions that we need to ask is 2n – 2 – log2n. Therefore the total number of questions asked in this case is n-1 + 2n – 2 – log2n = 3n – 3 – log2n. There exists no algorithm which can do better than this, the proof of which is beyond the scope of this lecture. Extending it for n not a power of 2 is also interesting.