// 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

Geoff Hayes
Geoff Hayes 2019년 5월 1일
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?
Karlyann Laboy Rivera
Karlyann Laboy Rivera 2019년 5월 1일
Yes. I am asking if someone could convert this code to Matlab.

댓글을 달려면 로그인하십시오.

답변 (1개)

Guillaume
Guillaume 2019년 5월 1일
편집: Guillaume 2019년 5월 1일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

질문:

2019년 5월 1일

편집:

2019년 5월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by