print cv::Mat element -- OpenCV(C++) - c++

I am trying to loop over a matrix and print its element, which should be a simple operation, but I experience some strange things...
I have a a null matrix :
cv::Mat accum = cv::Mat::zeros(3,5,CV_8U);
Doing this:
for(int i=0;i<accum.rows;i++)
{
for(int j=0;j<accum.cols;j++)
{
cout<<accum.at<int>(i,j) <<endl;
}
}
I get the following elements:
0
0
0
0
0
0
0
0
0
-536870912
0
0
0
2027945984
587217671
Why is there some random number at places where zero should be?
If I initialize the value of matrix at i=1,j=1 with number 1, I get the following
0
0
256
0
0
0
1
0
0
587202560
0
0
0
1931673600
587257437
I just dont understand those random values, I might do something wrong, but cant figure out what. Could you please help?

Related

Setting the number of edges in igraph_erdos_renyi_game c++

I would like to create a directed network graph using igraph c++ in which each node is randomly connected to exactly n other distinct nodes in the network (i.e. excluding connections to itself, and loops/multiple edges to the same loop). I was thinking of using the method igraph_erdos_renyi_game, but for some reason I do not get the desired degree distribution. In particular, if I set the arguments like this:
igraph_erdos_renyi_game(&g, IGRAPH_ERDOS_RENYI_GNM, n, m, true, false);
with n = 5, m = 1, I get this Adjacency Matrix (e.g.):
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0
0 0 0 0 0
If I use igraph_k_regular_game(&g, n, m, true, false) instead, I get exactly the desired outcome, namely (e.g.):
0 0 0 0 1
1 0 0 0 0
0 0 0 0 1
0 1 0 0 0
0 0 0 1 0
So to summarize, I would like for each node to have 1 edge to n randomly selected agents. Am I misinterpreting the way the Erdos-Renyi method works, or am I passing the wrong arguments?
m is the total number of edges in erdos_renyi_game(). So just use k_regular_game(), it does exactly what you want.

Breadth First Search not finding correct path

So I have a lab to implement Breadth First Search and Depth First Search using an adjacency matrix. The vertices of the graph to be searched are numbered 0-(V-1), so for example a graph with 10 vertices would have vertices numbered 0-9. Each vertex is also given a value.
In the example I am going to give, the number of each vertex is equal to it's value (for example, vertex 0 has value 0, vertex 1 has value 1, etc.). I store the values of each vertex in an array, where the position is the vertex and the item in the array is it's value, so finding the value of vertex 7 would look like:
value = matrix[7];
I am supposed to write a program that finds a certain value with Breadth First Search and reports the vertex it was found at, and how many "steps" it took to find it.
My program finds the value in each test case, but the problem is that the "steps" don't match. I think the problem must be within my BFS algorithm itself, but I can't find it.
For example, I am searching the following adjacency matrix for value 7, which is at vertex 7:
0 1 1 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 1 1 0
0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
There are 10 nodes, numbered 0-9, node 0 is connected to nodes 1 and 2, node 1 is connected to nodes 3 and 4, node 2 is connected to nodes 5 and 6, node 3 is connected to nodes 7 and 8, and node 4 is connected to node 9.
As mentioned "vertices" is the array of vertex values. "matrix" is the adjacency matrix. "visited" is an array of bool to keep track of whether or not a vertex has been visited.
I am "walking" the graph with a deque container, which I am required to use.
Here is my BFS:
steps = 1;
int cur_v = 0;
int vertexFound = 0;
bool found = false;
bool *visited = new bool[V];
for (int i = 0; i < V; i++) {
visited[i] = false;
}
deque <int> q;
q.push_back(0);
visited[0] = true;
while (!q.empty()) {
if (found == false) {
steps++;
}
cur_v = q.front();
q.pop_front();
for (int n = 0; n < V; n++) {
if (matrix[cur_v][n] == 1) {
if (visited[n] == false) {
if (vertices[n] == search) {
vertexFound = n;
found = true;
}
visited[n] = true;
q.push_back(n);
}
}
}
}
if (found == true) {
cout << steps << endl;
}
The value I am searching for is "7", located at vertex 7. It is supposed to take 7 steps for me to get there, but my program says that it takes 5.
Another problem I am having is that when I give the program input that is supposed to make it search for value 8 in a graph with 8 vertices that go from values 0-7, it tells me that it found the value at vertex 0 in 9 steps.
Any help is very appreciated!
You shouldn't be updating vertexFound after the first time you find what you're looking for. (And indeed you could just stop searching immediately.)

conway game error with 2d array manipulation

So I'm working on the life game, and so far I have come up with this http://ideone.com/QG4tsS I'm not sure exactly if I am on the right track or not. Basically I have a function putting out random values to try and test my code. But nothing seems to happen. I suspect my problem lies with the following code
int sum = 0;
for (int k = (i - 1); k <= (i + 1); k++) {
for (int l = (j - 1); l <= (j + 1); l++) {
sum += currentGen[k][l];
}
}
return sum;
So my result gives me a 2d array with all 0's but shouldn't I start to see some changes and patterns starting to form? I get one 1 and the rest are 0.
Output
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 1
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
I provide this answer based on the code you posted at http://ideone.com/QG4tsS . You really should consider adding that code to your original question, so that future folks who find this on StackOverflow have the full context.
Your RandomCells function only sets cells to 1 if they meet the RANDOM threshold. It doesn't clear them to 0 otherwise. Once you fix that, you'll be all set. ie.
void RandomCells(int currentGen[][CELLY]) {
for (int i = 0; i < CELLX; i++) {
for (int j = 0; j < CELLY; j++) {
if (rand() % 100 + 1 < RANDOM) {
currentGen[i][j] = 1;
} else
{
currentGen[i][j] = 0;
}
}
}
}
Without that else clause, I was seeing initial generations that looked like this:
0 0 4196155 1
1813657216 1 4197653 0
-870503576 1 4197584 1
Clearly, most of those cells were non-zero, and so Conway's Life algorithm would map them to 0 in the next generation because of "crowding".
The reason currentGen was filled with such 'random' values is that it was allocated as an automatic variable to main. Automatic variables do not get initialized to any particular value. You need to initialize them yourself. You can do that by modifying your algorithm (as I did above), or by adding an explicit bit of code to initialize the structure.
This differs from file-scope variables, which C and C++ define as initialized-to-zero on program start if they don't have initializers or default constructors. (Pedants will point out that even that has caveats.)
Once you make the required fixes, to truly see Conway's Life, you'll need to set CELLX and CELLY to larger values...

Matlab: how to work with sparse keys to access sparse data?

I am trying to access the sparse mlf with the keys such as BEpos and BEneg where one key per line. Now the problem is that most commands are not meant to deal with too large input: bin2dec requires clean binary numbers without spaces but the regexp hack fails to too many rows -- and so on.
How to work with sparse keys to access sparse data?
Example
K>> mlf=sparse([],[],[],2^31,1);
BEpos=Cg(pos,:)
BEpos =
(1,1) 1
(2,3) 1
(2,4) 1
K>> mlf(bin2dec(num2str(BEpos)))=1
Error using bin2dec (line 36)
Binary string must be 52 bits or less.
K>> num2str(BEpos)
ans =
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
K>> bin2dec(num2str('1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0'))
Error using bin2dec (line 36)
Binary string must be 52 bits or less.
K>> regexprep(num2str(BEpos),'[^\w'']','')
Error using regexprep
The 'STRING' input must be a one-dimensional array
of char or cell arrays of strings.
Manually works
K>> mlf(bin2dec('1000000000000000000000000000000'))
ans =
All zero sparse: 1-by-1
Consider a different approach using manual binary to decimal conversions:
pows = pow2(size(BEpos,2)-1 : -1 : 0);
inds = uint32(BEpos*pows.')
I haven't benchmarked this, but it might work faster than bin2dec and cell arrays.
How it works
This is pretty simple: the powers of 2 are calculated and stored in pows (assuming the MSB is in the leftmost position). Then they are multiplied by the bits in the matching positions and summed to produce the corresponding decimal values.
Try to index with this:
inds = uint32( bin2dec(cellstr(num2str(BEpos,'%d'))) );

Loading Data from File to Data Structure in C++ and Interpreting It

Okay so this code is killing me.
My goal is to read data from a file where the data is separated by commas, then load that data into an array of structures that is supposed to be a list of "theater seats". The theater seats have certain characteristics, such as "location", "price", and "status". Price is self-explanatory. Location deals with the row and seat number of the "Seat". And status pertains to whether or not it's sold. After that, I have to interpret the data that I pulled from the data file to make a display THAT CAN be easily manipulated by the user if they input a certain choice. But that's not what I'm getting at in this question.
My question is, what would be the best method to load my data structures from the data file?
Let me show you a bit of the data file that I'm reading from.
1, 1, 50, 0
1, 2, 50, 0
1, 3, 50, 0
1, 4, 50, 0
To explain the data file, the first number is the "row", second number is the seat number in that row, the third number is the price, and the final number ("0") stands for the seat being unsold. Had the seat been purchased, the final number would be 1.
Now, here's my code.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <cstdio>
#include <conio.h>
using namespace std;
enum seatDimensions{ROWS = 10, SEATS_PER = 16};
//Structures
struct Location
{
int row;
int seatNumber;
};
struct Seat
{
Location seat_location[160];
double ticketPrice;
int status;
int patronID;
};
//GLOBALS
const int MAX = 16;
int main()
{
//arrays for our data
Seat seatList[160];
//INDEX
int index = 1;
//filestream
fstream dataIn;
dataIn.open("huntington_data.dat",ios::in);
if(dataIn.fail()) //same as if(dataIn.fail())
{
cout << "Unable to access the data file." << endl;
return 999;
}
string temp;
getline(dataIn,temp,',');
seatList[index].seat_location[index].row = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].seat_location[index].seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[index].status = atoi(temp.c_str());
while(!dataIn.eof() && index < MAX)
{
index++;
getline(dataIn,temp,',');
seatList[index].seat_location[index].row = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].seat_location[index].seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
seatList[index].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[index].status = atoi(temp.c_str());
}
getch ();
return 0;
}
Now from here, I have to display whether or not the seats are TAKEN or not.
The display should look like this, since none of the seats are taken yet.
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // 16 across
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
// 10 deep
I know I'm not inputting my data in correctly, because I cannot seem to get this display no matter how I try to cout it. If you can tell where I'm going wrong, please tell me. Any suggestions would be amazing.
Also, if you have any questions for me, just ask. I tried to be as specific as possible considering the question, but I know that it's still pretty vague.
Please help.
EDIT: Thanks to those who answered my question. I ended up going a very different route with my data structure, but pulled a lot from the answers.
You have the problem that each seat has a position in an array and then has an array of positions:
You need:
Location seat_location[160];
changed to:
int seat_row;
int seal_num;
then:
seatList[index].seat_location[index].row = atoi(temp.c_str());
becomes:
seatList[index].seat_row = index / COLS ;
seatList[index].seat_num = index % COLS ;
You may also like to consider actually arranging your data into a 2D array of the same dimensions as your seating.
BTW From my C background I would suggest reading the whole line and using sscanf, e.g.:
char temp[255]; // Use an appropriate maximum line length +3 for \r\n\0
fgets(dataIn, &temp);
sscanf(temp, "%d, %d, %d, %d", &.....
You could also consider implementing this with a regular expression.
Write a function that gets string of input and splits it into items:
std::vector<std::string> splitLine( const std::string &str );
Implement and debug it with string like "1, 1, 50, 0", make sure it returns vector of string with each number as separate element. Then read input line by line, split and convert each string to number separately. You will simplify the code and it will be much easier to make it work.
is it an assignment?
i guess the way you are organizing your data in structure needs to be changed.
Take a structure maybe like this
struct Seat{
double ticketPrice;
int status;
int patronId;
}
and have a two dimensional array like this
Seat seatList[10][16];
first dimension is (row number-1), second dimension is (seat number-1)
and read your data from file like this
string temp;
getline(dataIn,temp,',');
int row = atoi(temp.c_str());
getline(dataIn,temp,',');
int seatNumber = atoi(temp.c_str());
getline(dataIn,temp,',');
//check row and seatnumber > 0
seatList[row-1][seatNumber-1].ticketPrice = atof(temp.c_str());
getline(dataIn,temp,'\n');
seatList[row-1][seatNumber-1].status = atoi(temp.c_str());
Use two simple for loops to print your output from these structures.