I want to pass a particular column of the matrix that I have in my program to a function.
If I use the call <function_name>(<matrix_name>[][<index>]); as the call
then I get the error
error: expected expression before ‘]’
token
So please help me in finding the suitable way
Thanks
The syntax you used doesn't exist.
Matrices are stored in memory by row (or better, by the second dimension, to which you give the semantics of rows), so you cannot natively. You could copy all your column elements in a vector (a single dimension array) and pass it.
If you need to work only by column (and never by row) you could change the semantics you give to the first and to the second dimension: think of your matrix as matrix[row][column] instead of matrix[column][row].
Otherwise, if you need to do this often, look for a better data structure, instead of a simple array.
Because of the way addressing works, you can't simply pass the 'column' since, the 'column' values are actually stored in your 'rows'. This is why your compiler will not allow you to pass no value in your 'row' reference, ie: '[]'.
An easy solution would be to pass the entire matrix, and pass the column index as a seperate integer, and the number of rows. Your function can then iterate through every row to access all members of that column.
ie:
functionName(matrixType** matrixRef, int colIndex, int numRows)
{
for(int i=0; i< numRows; ++i)
matrixType value = matrixRef[i][colIndex]; //Do something
}
You are going to have to reformat the data. The column is not contiguous in memory. If for example you have an array:
arr[5][4]
Then trying to pass a 'column' would be like trying to pass every 5th element in the array. Think of it as one giant array.
There's a few things you need to keep in mind about C here.
I'm assuming your matrix is stored as a 2D array, like this:
float mat[4][4];
What you need to remember is that this is just 16 floats stored in memory consecutively; the fact that you can access mat[3][2] is just a shortcut that the compiler gives you. Unfortunately, it doesn't actually pass any of that metadata on to other function calls. Accessing mat[3][2] is actually a shortcut for:
mat[ (3*4 + 2) ]
When you pass this into a function, you need to specify the bounds of the matrix you're passing in, and then the column number:
void do_processing(float* mat, int columns, int rows, int column_idx)
Inside this function, you'll have to calculate the specific entries yourself, using the formula:
mat[ (column_idx * rows) + row_idx ]
Related
I have a recursive function that goes through the elements of a matrix by a specific rule. Every time I go through an element I am calculating a result based on the element I am in the matrix at that moment, and when all the calls of the function end I am back to the first element I started at I have the result I need in that result I mentioned before.
Now the problem is that I have to replace every element of the matrix that I went through with this result. From what I am thinking i have 3 options :
Use the same algorithm to call the function again from the starting element and go through it again, basically going through the same path and replacing the elements with the result (this would be the most inefficient as the algorithm and the size of the matrix are pretty big )
Memorizing the addresses of the elements I am arriving at in the matrix on every callout, then I would have a vector of addresses and after the function finishes I am just going through
that vector and replacing the values with the one I calculating.
This is quite a longshot for me to implement but I was thinking that I could synchronize all the variables in the positions that I have arrived in the matrix with one external variable. When the function finishes and I have my result I just change the value of this external variable with the result and all the other elements in the matrix that I have linked this variable to would automatically change.
My question is how could I implement something like "3."? is there any way you can synchronize a variable(or multiple ones) to always have the same value as another one that is constantly updating ?
From a definition of a Matrix like:
struct Matrix {
int N, M;
int *Mat;
};
Type Values[];
Where the value at (i,j) is Values[G->Mat[G->M * i + j]]; that is Mat just holds indexes into Values[] which can be dynamically extended. At the beginning if a path traversal, you could allocate a new Values[t], and change each visited node (i,j) to be t: G->Mat[G->M * i + j] = t. When you assign Values[t], all of the nodes linked to it will be automatically updated.
While you are making your traversal, you would use their value, then change their index as you moved to the next node. Serendipitously, if you encountered a node already with an index of t, you would know that you are caught in a cycle.
Although I might have misread your requirement terribly.
I am writing a method which accepts a two dimensional array of doubles and an int row number as parameters and returns the highest value of the elements in the given row.
it looks like this:
function getHighestInRow(A, i)
return(maximum(A[:i,:]))
end
the issue i am having is when i slice the array with
A[:i,:]
I get an argument error because the :i makes i get treated differently.
the code works in the other direction with
A[:,i,:]
Is there a way to escape the colon? so that i gets treated as a variable after a colon?
You're doing something strange with the colon. In this case you're using the symbol :i not the value of i. Just getHighestInRow(A,i) = maximum(A[i,:]) should work.
Edit: As Dan Getz said in the comment on the question, getHighestInRow(A,i) = maximum(#view A[i,:]) is more efficient, though, as the slicing will allocate a temporary unnecessary array.
I am talking about a zero-indexed matrix of integers denoted by a pointer to pointer, i.e.
int **mat;
Then what is the correct way to represent the mat[m][n] element? Is it
*(*(mat+m)+n)
or is it
*(*(mat+n)+m)
Also, visually speaking, between m and n, which one is the row index or which one is the column index? Or do terms like row and column make any sense here? I am sure I have some conceptual gap here, and some help will be great.
The expression
mat[m][n]
is parsed as
(mat[m])[n]
which is equivalent to
(*(mat + m))[n]
which is in turn equivalent to
*(*(mat + m) + n)
so your initial guess is correct.
As for which of these mean rows and which of these mean columns - in some sense, this is up to you to decide. You're the one creating the array and you can assign it any semantics that you'd like.
On the other hand, if you create a 2D array like this:
int mat[A][B];
then in memory this will be laid out as
[0, 0][0, 1][0, 2]...[0, B-1][1, 0][1, 1][1, 2]... ... [A-1][B-1]
Because of locality of reference, if you read across this in the order shown above (do all of mat[0], then all of mat[1], etc.) than it is to iterate in the reverse order (do mat[0][0], then mat[1][0], then mat[2][0], etc.). In that sense, it's common to treat 2D arrays as having the first component select a row and the second select a column, since that more naturally aligns with how the memory is laid out.
How do I solve, Two string arrays J=(nx1) and K=(mx1), with same values, if some of the values are missing in J then I need to create a new array for those missing values L=(ix1) ; for example:
J={Two_Headlights
one_engine
four_wheels
two_seats
two_seatbelts}
K={Two_Headlights
one_engine
one_gear
one_break
one_clutch
four_wheels
two_seats
two_seatbelts}
then I would like to create a new array for those missing values in J;
L={one_gear
one_break
one_clutch}
I have tried using the for loop by using setdiff and aswell as using strcmp, but I dont know where I am going wrong, I am not able to get the result.
I guess you missed putting the single quotation for the strings when writing your question.
The setdiff(A,B) function will return the data in A that is not in B. So your first argument must be K.
J={'Two_Headlights','one_engine','four_wheels','two_seats','two_seatbelts'};
K={'Two_Headlights','one_engine','one_gear','one_break','one_clutch','four_wheels','two_seats','two_seatbelts'};
L = setdiff(K,J);
Im beginner in programming. My question is how to count number sequences in input array? For example:
input array = [0,0,1,1,1,1,1,1,0,1,0,1,1,1]
output integer = 3 (count one-sequences)
And how to calculate number sequences first and last indexes in input array? For example:
input array = [0,0,1,1,1,1,1,1,0,1,0,1,1,1]
output array = [3-8,10-10,12-14] (one first and last place in a sequence)
I tried to solve this problem in C with arrays. Thank you!
Your task is a good exercise to familiarize you with the 0-based array indexes used in C, iterating arrays, and adjusting the array indexes to 1-based when the output requires.
Taking the first two together, 0-based arrays in C, and iterating over the elements, you must first determine how many elements are in your array. This is something that gives new C programmers trouble. The reason being is for general arrays (as opposed to null-terminated strings), you must either know the number of elements in the array, or determine the number of elements within the scope where the array was declared.
What does that mean? It means, the only time you can use the sizeof operator to determine the size of an array is inside the same scope (i.e. inside the same block of code {...} where the array is declared. If the array is passed to a function, the parameter passing the array is converted (you may see it referred to as decays) to a pointer. When that occurs, the sizeof operator simply returns the size of a pointer (generally 8-bytes on x86_64 and 4-bytes on x86), not the size of the array.
So now you know the first part of your task. (1) declare the array; and (2) save the size of the array to use in iterating over the elements. The first you can do with int array[] = {0,0,1,1,1,1,1,1,0,1,0,1,1,1}; and the second with sizeof array;
Your next job is to iterate over each element in the array and test whether it is '0' or '1' and respond appropriately. To iterate over each element in the array (as opposed to a string), you will typically use a for loop coupled with an index variable ( 'i' below) that will allow you to access each element of the array. You may have something similar to:
size_t i = 0;
...
for (i = 0; i< sizeof array; i++) {
... /* elements accessed as array[i] */
}
(note: you are free to use int as the type for 'i' as well, but for your choice of type, you generally want to ask can 'i' ever be negative here? If not, a choice of a type that handles only positive number will help the compiler warn if you are misusing the variable later in your code)
To build the complete logic you will need to test for all changes from '0' to '1' you may have to use nested if ... else ... statements. (You may have to check if you are dealing with array[0] specifically as part of your test logic) You have 2 tasks here. (1) determine if the last element was '0' and the current element '1', then update your sequence_count++; and (2) test if the current element is '1', then store the adjusted index in a second array and update the count or index for the second array so you can keep track of where to store the next adjusted index value. I will let you work on the test logic and will help if you get stuck.
Finally, you need only print out your final sequence_count and then iterate over your second array (where you stored the adjusted index values for each time array was '1'.
This will get you started. Edit your question and add your current code when you get stuck and people can help further.