Hi everyone:

I have written C++ code for populating a matrix/2D array with calculation results. Each column of the array represents results for a distinct time step.

My problem arises because the rows of my results vector do NOT correspond to the rows of the matrix. The matrix includes extra rows (I need these to store other information), so the matrix rows do NOT correspond to the vector rows.

I have written code to specify where in the matrix to store each vector element, but it is generating incorrect results. Instead of putting each vector element in the right place in the matrix for each time step (column), my code is taking the LAST element of each vector and filling an entire matrix column with it.

I would very much appreciate any help in figuring out where I'm going wrong! My code is below:

``````for (int j = 1; j <= someTime; j++)   // Each j is a single time step
{
// Do calculation and get results vector (not included here)

for (int i = 0; i < (d_x * d_x); i++)  // Each i is an element in the results vector
{
for (int k = 0; k < (((d_x + 2) * (d_x + 2)) - (d_x + 2)); k++)
{ // the code for k specifies where in the matrix each vector element should go.
if ( k % (d_x + 2) != 0 && k > (d_x + 1))
{
if ( (k - d_x - 1) % (d_x + 2) != 0 )
{
solutionMatrix(k,j) = temperatureNew[i];  // Put each element of results vector (temperatureNew) in the appropriate place in the matrix.
}
}
}
}
}``````

Edited by Annettest: n/a

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Annettest

It's because your variable/iterator "i" doesn't change until after your third loop completes everything it does. You need to find a way to change "i" more often.

Hint: It is possible to have more than 1 iterator and/or exit condition in a particular for loop. Have a look at the little program below. Before you compile and run it, try to guess what it does and what the output is. There is nothing tricky in it, I'm not doing anything you shouldn't already be familiar with.

``````#include <iostream>

using namespace std;

int main()
{
for (int it1 = 0, it2 = 10; (it1 < it2) && (it2 < 15); it1+=2, it2++) {
cout << "it1 = " << it1 << " it2 = " << it2 << endl;
}
cin.get();
return 0;
}``````

Edited by Fbody: n/a