Matrix multiplication with vectors - C++ - c++

I am working on making a program that can multiply matrices of user-defined size. I use vectors to store the values in the matrix.
void Multiply(vector<float> A,vector<float> B,int rA, int cA,int rB,int cB)
{
system(CLEARSCREEN);
vector<float> C; // The resulting matrix
int sizeA=rA*cA;
int sizeB=rB*cB;
int sizeC=rA*cB;
int lrA=sizeA-1;
int lrB=sizeB-1;
int writeHead=0;
A.resize(sizeA);
B.resize(sizeB);
C.resize(sizeC);
demoDisplay(rA,rB,cA,cB,lrA,lrB,sizeA,sizeB);
for(;writeHead<=lrA; writeHead++)
{
cout << "Please enter a value for \"" << alphabet[writeHead] << "\" in MATRIX A.\n";
cin >> A[writeHead];
}
cout << "\n";
writeHead=0;
for (;writeHead<=lrB; writeHead++)
{
cout << "Please enter a value for \"" << alphabet[writeHead] << "\" in MATRIX B.\n";
cin >> B[writeHead];
}
cout << "\n\n";
displayMatrices(A,B,rA,rB,cA,cB,lrA,lrB,sizeA,sizeB);
for (int colRead=0; colRead<=cA; colRead++) {
// somehow iterate through each element of the vector?
}
}
I'm relatively new to C++, and so I'm not quite sure how to do the actual multiplication of the two matrices. If anyone could help, it would be great.

Maybe you were mislead by the name of the vector container, that implies some mathematical use. The vector template doesn't provide any function to multiply matrices or even to multiply vectors. The vector in this case only provides you with a container to store a matrix. Obviously you store the matrices in some linearized way and that will make the multiplication more complicated later.
Be sure to read http://www.cplusplus.com/reference/stl/vector/
Furthermore you dont really want to iterate through the vectors, because if that was the case, you could have just used some other container. You want random access to do multiply the columns and rows by hand. For this you can use the []-operator] or the at() member function.
Then it is just a matter of doing the multiplication by hand, as for example shown here(which also includes some pseudo code).

Related

(C++)1 dimensional battleship game help? advice for improvement

Unfortunately I do not have the Instructor to aid me with this assignment over the weekend and I am stuck. I'm just learning C++ and I've taken a Logic and Design class for Programming but like I said I'm very new to C++. I'm having a hard time catching up to the rest of the students.
I'd like if someone could list improvements and maybe clarify if I've done anything wrong in comparison to the assignment statement. I do really appreciate the help!
My code is repetitive and I'm sure I could go another way into displaying the array values without all that code. An error also pops up after use of the application that says:
"Run-Time Check Failure #2 - Stack around the variable 'enemy' was corrupted.
If there is a handler for this exception, the program may be safely continued."
The assignment is:
"Create a Battleship struct containing 5 one-dimensional integer coordinates representing its location within a region (of any size). Instantiate 2 copies of the struct and have the user enter a single coordinate for each Battleship. Design your code to take this single coordinate and use it to populate the remaining 4 coordinates for each ship. Do this for both ship structs. Then, have your code calculate the numeric distance between the 2 ships based on their respective coordinates. Finally, display the resulting distance to the user with an English language sentence."
My code as for right now is :
#include <iostream>
#include <string>
using namespace std;
struct Ship
{
int x[5];
int y[5];
};
int main()
{
Ship good;
Ship enemy;
good.x[0] = 0;
enemy.y[0] = 0;
cout << "Enter a coordinate (out of 100) for good ship: "<< endl;
cin >> good.x[0];
good.x[1] = good.x[0] + 1;
good.x[2] = good.x[1] + 1;
good.x[3] = good.x[2] + 1;
good.x[4] = good.x[3] + 1;
cout << "Good ship coordinates:" << endl;
cout << good.x[0]<< "*" << endl;
cout << good.x[1]<< endl;
cout << good.x[2]<< endl;
cout << good.x[3]<< endl;
cout << good.x[4]<< endl;
cout << "Enter a coordinate (out of 100) for enemy ship: "<< endl;
cin >> enemy.y[0];
enemy.y[1] = enemy.y[0] + 1;
enemy.y[2] = enemy.y[1] + 1;
enemy.y[3] = enemy.y[2] + 1;
enemy.y[4] = enemy.y[3] + 1;
cout << "enemy ship coordinates:" << endl;
cout << enemy.y[0]<< "*" << endl;
cout << enemy.y[1]<< endl;
cout << enemy.y[2]<< endl;
cout << enemy.y[3]<< endl;
cout << enemy.y[4]<< endl;
int distance=0;
distance = good.x[1] - enemy.y[1];
cout << "The distance between good ship and enemy ship is: " << distance << endl;
system("pause");
return 0;
}
The error probably comes from having only 4 coordinates in each struct, not 5. When you declare an array with int x[4];, it will only have 4 elements, namely x[0] to x[3].
There are a number of other problems:
You do not need two structs for two ships. Use just one. That's the whole point of structs/classes: to represents classes of objects. Use only one struct (named e.g. Ship) and declare both your ships good and enemy to have that type.
Don't be afraid of both the enemy ship and the good ship having x coordinates. The compiler and the computer won't get confused at that, and neither should you.
Learn to use loops. Even if you get confused at first, remember that loops are one of the most (if not the most) important tools at a programmers disposal. Think what would happen if you had 100 ships, each with 100 coordinates...
Remember, again, that the first element of an array is at index 0, not index 1. (And the last element is at index N-1.)
Calculating the distance is a little more complex than you've written. Can the distance between two objects ever be negative? What happens if the enemy ship's coordinate is greater than the friendly ship? What's the actual formula for one-dimensional distances?
Remove unused code. What's the use of that region variable? Have you used it anywhere?
UPDATE: (For anyone reading in the future, remember that OP has updated and modified their question and code, to the point that some of my point would not apply or would apply differently.)
Do you REALLY need both xs and ys in Ship?
Not sure if the use of system("PAUSE") is something your instructor taught, but that's definitely something you could improve on, too. Explained here
So starting with
Create a Battleship struct containing 5 one-dimensional integer coordinates representing its location within a region (of any size). Instantiate 2 copies of the struct and have the user enter a single coordinate for each Battleship
You need a single struct:
struct Ship
{
int x[5];
};
Now make 2 copies
int main()
{
Ship good;
Ship bad;
...
Then the rest looks good, it compiles and runs without any issues on my computer. You can add a function to populate the ship to reduce the number of code
Ship createShip(int startPos) {
Ship newShip;
newShip[0] = startPos;
// ... <- rest of your code that you have to populate
return newShip;
}
int main()
{
int pos;
cout << "Enter a coordinate (out of 100) for good ship: "<< endl;
cin >> pos;
Ship good = createShip(pos);
//...
//... <- Get pos of bad ship
Ship bad = createShip(pos);
}
Then you can also create a simular function that prints the location of the ship

Reading the variables of another function

Let me introduce how I got this problem... Well, I know a little bit of FORTRAN, and now I'm learning C++.
While I read the beginnings, I'm (re)creating an old program that I have written in FORTRAN.
It do the calculation part of the topography surveying of a closed polygonal.
Well, I'm reading the book "Programming: Principles and Practice Using C++", and it says that in C++, we'd prefer to let each functions do the minimum number of things. For now, I have something like this (I ignored all the other functions):
int main(){
//Starting the program and reading all variables
try
{
//Program beginning
cout << "Hello. Welcome to the 'Topography Program'\n\n\n";
//Reading all the information needed
reading_is_fundamental();
//Testing the angular tolerance
ang_tolerance_test (number_of_points); } ...there's more subroutines' calls
catch (runtime_error& e)
{
cerr << "error:" << e.what()<<'\n';
return 1;
}
return 0;}
The "reading_is_fundamental()" is the call of a subroutine. There, I read all the information needed. My problem is lying on the second subroutine, "ang_tolerance_test (number_of_points)".
In FORTRAN, I abused too much of global variables, and now, in this book, says that we must avoid global variables.
End of story, I have two questions:
1 - This logic is correct or I misunderstood the book? Should I put some calculations (or at least the reading of the input variable, as they will appear in all the subroutine) in the main function or should I use it only to call my subroutines?
2 - If this is really the way that we should do in C++ (separate each action in one function), can somebody explain me how to grab variables that was written in the first subroutine and send to the others, like the "ang_tolerance_test" one?
Many thanks in advance!
EDIT
The function "reading_is_fundamental()" is where I read all the values by keyboard. I know how to read the values by a text file in FORTRAN and, in this case, it is a great advantage, as there are so many numbers to be read. But, I don't know yet how to do this in C++, so, please, ignore that I'm reading a lot of variables by keyboard, I'm studying it yet! Actually, doesn't really matter the way that I'm reading the variables, the point is that I want those doubles, int and vectors in the others soubroutines...
Well, this is "reading_is_fundamental:
//This subroutine reads all the variables
void reading_is_fundamental (){
cout << "What is the linear tolerance?\n";
double lin_tolerance;
cin >> lin_tolerance;
cout << "\nHow many points did you study?\n";
int number_of_points;
cin >> number_of_points;
cout << "\nWhat's the distance between each point?\n";
vector <double> distances;
for (double dist; cin >> dist;)
distances.push_back(dist);
if (distances.size() != number_of_points) error ("The number of distances must be equal to the number of points");
cout << "\nWhat's each horizontal degree angle?\n";
vector <double> horizontal_degrees;
for (double horizontal_degree; cin >> horizontal_degree;)
horizontal_degrees.push_back(horizontal_degree);
if (horizontal_degrees.size() != number_of_points) error ("The number of angles must be equal to the number of points");
cout << "\nWhat's each horizontal minute angle?\n";
vector <double> horizontal_minutes;
for (double horizontal_minute; cin >> horizontal_minute;)
horizontal_minutes.push_back(horizontal_minute);
if (horizontal_minutes.size() != number_of_pointsint) ("The number of angles must be equal to the number of points");
cout << "\nWhat's each horizontal second angle?\n";
vector <double> horizontal_seconds;
for (double horizontal_second; cin >> horizontal_second;)
horizontal_seconds.push_back(horizontal_second);
if (horizontal_seconds.size() != number_of_points) error ("The number of angles must be equal to the number of points");
cout << "\nWhat's the first azimuth degree?\n";
double first_az_degree;
cin >> first_az_degree;
cout << "\nWhat's the first azimuth minute?\n";
double first_az_minute;
cin >> first_az_minute;
cout << "\nWhat's the first azimuth second?\n";
double first_az_second;
cin >> first_az_second;
cin >> number_of_points;}
One thing that I din't know when I was writting this is if it's correct to put void in this function. My way of thinking is taht I don't want one return, but some variables filed.
The second function is the "ang_tolerance_test()". It is not ready yet, so, I will not copy here. The thing is that when I call this function in main(), I want to put the argument of it one value sent from "reading_is_fundamental()" (that is "number_of_points).
I hope this made my questions more clearly.
Try returning value from reading_is_fundamental function, which you could pass it to other function like:
int number_of_points = reading_is_fundamental();
//Testing the angular tolerance
ang_tolerance_test (number_of_points);
And define function like:
int reading_is_fundamental() {
....
return number;
}
Define a class like:
class Record
{
private:
double lin_tolerance;
int number_of_points;
public:
int getNumberOfPoints() { return number_of_points; }
void setNumberOfPoints(int v) { number_of_points = v; }
double getLinTolerance() { return lin_tolerance; }
void setLinTolerancedouble v) { lin_tolerance = v; }
};
And when you read the values, create an instance of Record, keep populating the values within record and at the end return that value so that you could pass it to ang_tolerance_test. Just similar to int above instead now you will get Record object from the function.

My array takes random values despite user input

Excuse me again, I'm not any genius in Programming.
First of all, a summary: array input. Two 3D vectors...ha ha, let's use vectors to calculate MORE vectors. Anyway: dot product is just and plain ridiculous (nine numerals before decimals; I mean, seriously, I didn't ever thought that 1x8+7x5+4x2 could have NINE numerals). Cross product is...even worse.
I made the...uhm...how could I call it? Well, we call it "traza". I'll translate a definition ir order to get understood: a code's "traza" tell us the sequence of instructions of its execution, and how do the variables change after every line of code. You know, the table with variables and number marks referred to code lines where we look if the code is doing something unexpected. Getting to the point: it's everything fine as far as I could see.
Then, I made an unexpectedly "pseudotraza" with a print command and every value from the vectors. Just after input and just before te dot product (in a function). Guess what:
1) it's not my input, in either of them
2) they are not even the same values
3) first values are far away from my input, but the following ones at least were more logic (less difference to the input).
I learned this morning, 12 hours ago, to use arrays/vectors/whatever. I didn't ever have any need to set as 0 as default any value before its input. But it's the only thing I have known to do when things like this happened to me before.
(Someday any of you will be my Programming teacher, you are learning me more than himself...and excuse my awful grammar, English teaching in Spain is just "take some grammar rules and no more than 50 exercises in last High School year...it's all you need to pass the University Entrance Exam!")
#include <iostream>
using namespace std;
#include <stdlib.h>
const int N = 3;
typedef int Vector[N];
void introduirVector (Vector);
float producteEscalar (const Vector, const Vector); /*Input vector and dot product*/
int main (void)
{
Vector v1, v2;
float p_esc;
cout << "Introduim les dades del vector A: "; /* Input */
introduirVector (v1);
cout << "Introduim les dades del vector B: "; /* 2x Input combo */
introduirVector (v2);
cout << v1[0] << "\n" << v1[1] << "\n" << v1[2] << "\n" << v2[0] << "\n" << v2[1] << "\n" << v2[2] << endl; /* "Puseudotraza*/
p_esc= producteEscalar (v1, v2); /*Dot product*/
cout << "El producte escalar: " << p_esc; /*Dot product is...*/
system ("PAUSE");
return 0;
}
/*3x Input combo*/
void introduirVector (Vector)
{
int i;
Vector v;
for (i = 0; i < N; i++)
{
cin >> v[i];
}
return;
}
/* Dot product (why all the Vectors are set as constants but another after this is not set? It's the hint given by the teacher, my (not) beloved teacher...they gave us the main function and the other function's prototypes, but that's all) */
float producteEscalar (const Vector, const Vector)
{
float escalar;
Vector v1, v2;
/* Pseudotrazas for all*/
cout << v1[0] << "\n" << v1[1] << "\n" << v1[2] << "\n" << v2[0] << "\n" << v2[1] << "\n" << v2[2] << endl;
/* Dot product and all that */
escalar = (v1[0]*v2[0])+(v1[1]*v2[1])+(v1[2]*v2[2]);
return escalar;
}
The problem is this:
/*3x Input combo*/
void introduirVector (Vector)
{
int i;
Vector v;
This function takes a Vector as a parameter, but the Vector has no name so it cannot be used inside the function.
Then you declare a new, local Vector v. You read your user's input into this vector.
The function then ends, at which point the vector into which you read user input goes away.
Firstly, you should be using the parameter you were called with, not a local variable. But your second problem is that you are using pass by value. When you call this function, introduirVector (v1); it is not the "v1" you know and love from main that you are working with inside introduirVector, but a local copy of it that ceases to exist when your function returns.
What you need to do is make your function accept a pointer or a reference to the Vector it is being called with:
void introduirVector(Vector& v)
{
for (size_t i = 0; i < 3; ++i) {
cin >> v[i];
}
}
This does not fully solve all of the problems with your code, but it should get you moving forward.
I'm not seeing any input, which would be why you are not receiving any input.
Try using:
string inpt;
int a, b, c;
cin >> inpt;
a = atoi( inpt.c_str());
inpt = "";
cin >> inpt;
b = atoi( inpt.c_str());
// etc...
// Make your vector in this fashion, grabbing each integer separately then loading them
// into a vector

How to add items to a 2-dimensional dynamic vector

I have so far been able to use 1-d vectors, adding or removing elements with push/pop back.
However, when trying to fill out a 2-d vector which is supposed to represent a matrix, I run into problems. I haven't been able to use these functionalities with my 2-d vector. When the code does compile and run I get the bits asking for dimension and then it asks for the first element [1,1], for any value entered IĀ get "Segmentation fault: core dumped". I have no idea what is going on and have been trying to modify bits of my code but to no great success, the internet has also been rather useless in giving an easy guide on how to fill out these damn things...
Thank you so much!
Here is my code
#include <iostream>
#include <vector>
using namespace std;
vector<vector<double> > readMatrix();
int main()
{
vector<vector<double> > matrix1 = readMatrix();
vector<vector<double> > matrix2 = readMatrix();
}
vector<vector<double> > readMatrix()
{
cout << "Entering a matrix" << endl;
cout << "Number of Lines : ";
int numberOfLines;
cin >> numberOfLines;
cout << "Number of Columns :";
int numberOfColumns;
cin >> numberOfColumns;
vector<vector<double> > matrix;
int i(0);
int j(0);
while(i<=numberOfLines && j<=numberOfColumns)
{
cout << "[" << i+1 << "," << j+1 << "] =" ;
int value;
cin >> value;
matrix[i].push_back(value);
cout << endl ;
j++;
if(j==numberOfColumns)
{
j=1;
i++;
}
}
return matrix;
}
Declare the matrix like this:
vector<vector<double> > matrix (y, vector<double> (x, 0));
Now you have an y*x matrix. If you want to use push_back you have to declare the x-vector when starting on a new row.
When you do vector<vector<double> > matrix; you initialize a vector of vectors, both of size 0 (that's the default), so when you do matrix[i].push_back(value) even when i==0 you access memory which you hasn't been allocated. it's better if you do pre-allocate memory like this:
vector<vector<double> > matrix(numberOfLines,vector<double>(numberOfColumns));
And then you don't need to push back or anything, you just do matrix[i][j]=whatever.
In C++ you can use the vector constructor to automatically define the size:
vector<vector<double> > matrix(numberOfLines, vector<double>(numberOfColumns, 0));
With vectors, for loops are better than while loops because the size is always known. I suggest you iterate over the vector rows and columns with these (and remove your push_back statements.)
you need to do something like:
matrix.resize( ... );
.
.
.
matrix[i].push_back( ... );
The problem here is that you don't have a two dimensional vector. You have a vector, of vectors, of doubles. You need to put some vectors in the first vector, calling resize() as above is one way. You could also pass an initial size to the constructor, you could push the vectors on one by one - though that could carry performance issues.

passing 2D array to another class C++

I am trying to calculate the perimeter of a rectangle. first I will prompt the user 4 times for the X and Y cords and store it into a 2D array and pass this 2D array to another class which is method class to proceed with the calculation of the perimeter. But the problem is, I don't know how to pass the 2d array to method class.
I am not asking how to calculate the perimeter, I only need to know how to pass the 2D array from main to method class and get the 2D array at method class.
Please advise.
main.cpp
Method method;
int main() {
int storeXandY[4][2];
for(int i=1;i<5;i++)
{
cout << "Please enter x-ordinate" << i<< endl;
cin>>storeXandY[i][0];
cout << "Please enter y-ordinate" << i << endl;
cin>>storeXandY[i][1];
}
//how to pass the 2D array to method class to do some calculations?
// I was thinking something like passing the 2d array to a consturctor but don't know whether it can be done
method.constructor(storeXandY);
}
method.h
//not sure of what to do
public:
constructor() {
}
method.cpp
//how to get the cords from 2d array from main
Please advise. Thanks
You can do it as :
class Method{
...
public int calcPerimeter(int vals[4][2])
{
// do your calculation here using vals array
}
...
}
From main(), you can simply do :
Method m = new Method();
int perimeter;
m.calcPerimeter(<your_array_name>);
Since you are writing C++, you should try to avoid using C-style arrays. I would do this
Method method;
int main() {
vector<vector<int> > storeXandY(4);
for(int i=0; i!=4; ++i) storeXandY[i].resize(2);
for(int i=1;i<5;i++)
{
cout << "Please enter x-ordinate" << i<< endl;
cin>>storeXandY[i-1][0]; /* you need i-1 here, not i */
cout << "Please enter y-ordinate" << i << endl;
cin>>storeXandY[i-1][1];
}
method.calcPerimeter(storeXandY);
}
where method::calcPerimeter is declared as follows
your_return_type method::calcPerimeter(const vector<vector<int> >& rectangle);
The advantage of using vectors is that you can get the number of elements they hold by invoking their size member function, so that in the above code storeXandY.size() is equal to 4 and storeXandY[0].size() is equal to 2.