Reputation: 31
In MATLAB inorder to access the odd or even rows and columns of a matrix we use
A = M(1:2:end,1:2:end);
Is there an equivalent for this in C++? or How do i do this in C++.
Basically what i want to do is in matlab i have
A(1:2:end,1:2:end) = B(1:2:end,:);
A(2:2:end,2:2:end) = B(2:2:end,:);
I want to implement the same in C++
Upvotes: 2
Views: 873
Reputation: 1105
In C++ the for
loop is constructed as follows
for (initial state; condition for termination; increment)
So if you are looking for the odd elements, you can:
for (int i = 0; i < size; i += 2),
whereas if you are looking for the even elements:
for (int i = 1; i < size; i += 2).
Where size
depends if you are looping through the rows or columns. Take into account that because C++ arrays start at index 0, your odd elements will correspond to even indexes and your even elements will correspond to odd indexes.
Now, the answer: If you want to get the elements of a matrix, in C++ you must loop through the matrix with a for
loop. You can modify the elements you access by modifying the increment property of the for
loop.
Upvotes: 0
Reputation: 29094
for(int i= 0; i < rows/2; i++)
for(int j= 0; j < columns/2; j++)
A[i][j] = M[i*2][j*2];
Upvotes: 0
Reputation: 180145
This is available only in a fairly obscure class, std::valarray
. You need a std::gslice
(Generalized slice) with stride {2,2} to access the std::valarray
.
Upvotes: 2