Diagonal Pattern - MATLAB Cody - MATLAB Central

Problem 44468. Diagonal Pattern

Difficulty:Rate

For a positive integer n, return an nXn matrix mat such that the value of each element in row i and column j is given according to the following rules:

  • i - j, if i > j
  • j - i, if i < j
  • 0, if i equals j

If n is not a positive integer, mat should be an empty matrix.

Examples:

Input:  n   = 4
Output: mat = [0  1  2  3
               1  0  1  2
               2  1  0  1
               3  2  1  0]
Input:  n   = -2
Output: mat = []
Input:  n   = 2.5
Output: mat = []

Solution Stats

48.9% Correct | 51.1% Incorrect
Last Solution submitted on Apr 10, 2025

Problem Comments

Solution Comments

Show comments
Registration Now Open for MathWorks AUTOMOTIVE CONFERENCE 2025
...
Hello Community, We're excited to announce that registration is now open for the...

Problem Recent Solvers148

Suggested Problems

More from this Author25

Problem Tags

Community Treasure Hunt

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

Start Hunting!
Go to top of page