Convert C++ code in Matlab code?

// C++ program to check whether given matrix
// is a Toeplitz matrix or not
#include <iostream>
using namespace std;
#define N 5
#define M 4
// Function to check if all elements present in
// descending diagonal starting from position
// (i, j) in the matrix are all same or not
bool checkDiagonal(int mat[N][M], int i, int j)
{
int res = mat[i][j];
while (++i < N && ++j < M)
{
// mismatch found
if (mat[i][j] != res)
return false;
}
// we only reach here when all elements
// in given diagonal are same
return true;
}
// Function to check whether given matrix is a
// Toeplitz matrix or not
bool isToepliz(int mat[N][M])
{
// do for each element in first row
for (int i = 0; i < M; i++)
{
// check descending diagonal starting from
// position (0, j) in the matrix
if (!checkDiagonal(mat, 0, i))
return false;
}
// do for each element in first column
for (int i = 1; i < N; i++)
{
// check descending diagonal starting from
// position (i, 0) in the matrix
if (!checkDiagonal(mat, i, 0))
return false;
}
// we only reach here when each descending
// diagonal from left to right is same
return true;
}
// Driver code
int main()
{
int mat[N][M] =
{
{ 6, 7, 8, 9 },
{ 4, 6, 7, 8 },
{ 1, 4, 6, 7 },
{ 0, 1, 4, 6 },
{ 2, 0, 1, 4 }
};
if (isToepliz(mat))
cout << "Matrix is a Toepliz ";
else
cout << "Matrix is not a Toepliz ";
return 0;
}

2 Comments

Karlyann - yes, the above code could be converted to MATLAB. Are you asking someone to do that for you? Have you checked the MATLAB File Exchange to see if there is something similar?
Yes. I am asking if someone could convert this code to Matlab.

Sign in to comment.

Answers (1)

Guillaume
Guillaume on 1 May 2019
Edited: Guillaume on 1 May 2019
The code you show is hardcoded to check only matrices of size 5x4 and hardcoded to only check one matrix. Hardly useful.
In any case, there are much better ways to do this in matlab. The code below is not at all a translation of the C++ code.
function tf = istoeplitz(M)
%returns true if M is a toeplitz matrix. False otherwise
diags = toeplitz(size(M, 1):-1:1, size(M, 1):size(M, 1)+size(M, 2)-1); %build indices of diagonals
tf = all(accummaray(diags(:), M(:), [], @(dia) all(dia == dia(1)))); %check that all elements on the same diagonals are equal
end

Edited:

on 1 May 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!