MATLAB--Matrix Patterns II

例1.Problem 1636. ZigZag matrix with reflected format

ZigZag MATRIX with REFLECTED format.

We have only input x. We have to create a matrix in the following pattern.

 input n=5; 

then

     2     4     6     8    10
     1     3     5     7     9
     1     3     5     7     9
     2     4     6     8    10

Hint: meshgrid(1:n,1:n) & (2*i)-mod(j,n-1)+1

ZigZag矩阵采用反射格式。

我们只有输入x。我们需要按照以下模式创建一个矩阵。

输入 n=5; 那么

 2     4     6     8    10
 1     3     5     7     9
 1     3     5     7     9
 2     4     6     8    10

提示:使用meshgrid(1:n,1:n) & (2*i)-mod(j,n-1)+1

下面是使用MATLAB创建符合给定描述的ZigZag矩阵的代码。我们可以使用meshgrid函数生成行和列索引,然后基于描述中给出的公式计算出对应的矩阵值。

n = 5; % 矩阵的大小
[i, j] = meshgrid(1:n, 1:n); % 生成行和列的网格

% 根据公式计算矩阵中的值
zigzag_matrix = (2 * i - mod(j, n - 1) + 1);

% 显示矩阵
disp(zigzag_matrix);

 输出应该是你提到的矩阵格式:

 2     4     6     8    10
 1     3     5     7     9
 1     3     5     7     9
 2     4     6     8    10

代码使用meshgrid生成行和列索引,并应用给定的公式来计算矩阵的值。该公式的具体部分 (2 * i - mod(j, n - 1) + 1) 确保了“ZigZag”模式和相应的反射格式。

例2.Problem 2695. Toeplitz Matrix

For a given square matrix of order n-by-n check whether this is a Toeplitz matrix or not. Return true if it is.

对于给定的n阶方阵,请检查它是否是Toeplitz矩阵。如果是,返回true。

下面是一个MATLAB函数,用于检查给定的n阶方阵是否是Toeplitz矩阵,并返回true或false:

function isToeplitz = isToeplitzMatrix(matrix)
    % 获取矩阵的大小
    [rows, cols] = size(matrix);
    
    % 检查每个元素是否与其左上角元素相等
    for i = 2:rows
        for j = 2:cols
            if matrix(i, j) ~= matrix(i-1, j-1)
                isToeplitz = false;
                return;
            end
        end
    end
    
    % 如果所有元素满足Toeplitz条件,则返回true
    isToeplitz = true;
end

 可以将此函数保存在一个名为isToeplitzMatrix.m的文件中。然后,你可以调用此函数,并将要检查的矩阵作为参数传递给它。例如:

% 创建一个示例矩阵
matrix = [1, 2, 3; 4, 1, 2; 7, 4, 1];

% 调用函数检查矩阵是否是Toeplitz矩阵
result = isToeplitzMatrix(matrix);

% 显示结果
disp(result); % 如果矩阵是Toeplitz矩阵,则输出true,否则输出false

这段代码将检查所提供的矩阵是否是Toeplitz矩阵,并返回相应的布尔值。

例3.Problem 2342. Numbers spiral diagonals (Part 2)

Inspired by Project Euler n°28 and 58.

A n x n spiral matrix is obtained by starting with the number 1 and moving to the right in a clockwise direction.

For example with n=5, the spiral matrix is :

21 22 23 24 25

20 7 8 9 10

19 6 1 2 11

18 5 4 3 12

17 16 15 14 13

The sum of the numbers on the diagonals is 101 (See problem 2340) and you have 5 primes (3, 5, 7, 13, 17) out of the 9 numbers lying along both diagonals. So the prime ratio is 5/9 ≈ 55%.

With a 7x7 spiral matrix, the ratio is 62% (8 primes out of the 13 diagonal numbers).

What is the side length (always odd and greater than 1) of the square spiral for which the ratio of primes along both diagonals FIRST falls below p% ? (0<p<1)

受欧拉计划问题第28号和第58号启发。

一个n x n的螺旋矩阵是通过从数字1开始,顺时针方向向右移动而获得的。

例如,对于n=5,螺旋矩阵如下:

 
 
                       21 22 23 24 25
                       20  7  8  9 10
                       19  6  1  2 11
                       18  5  4  3 12
                       17 16 15 14 13

对角线上的数字之和为101(请参见问题2340),在两条对角线上有9个数字中有5个是质数(3、5、7、13、17)。因此,质数比例是5/9 ≈ 55%。

对于一个7x7的螺旋矩阵,这个比例是62%(13个对角线数字中有8个是质数)。

对于哪个边长(始终为奇数且大于1)的正方形螺旋矩阵,两条对角线上的质数比例首次低于p%?(0<p<1)

这个问题要求你编写一个MATLAB脚本来计算螺旋矩阵中对角线上质数的比例,直到该比例首次低于给定的百分比p%。由于这个问题的复杂性,我们需要按照以下步骤进行操作:

  1. 生成螺旋矩阵:从1开始,按顺时针方向生成n x n的螺旋矩阵。

  2. 计算对角线上的数字:提取螺旋矩阵的主要对角线和次要对角线上的数字。

  3. 检测质数:检查提取出的对角线数字哪些是质数。

  4. 计算质数比例:计算对角线上质数的比例。

  5. 迭代n值:从n = 3开始(n为奇数)不断增加螺旋矩阵的边长,直到质数比例首次低于给定的百分比p%。

下面是MATLAB脚本的实现

function side_length = find_spiral_side_length_below_p(p)
    % 初始条件
    n = 3; % 起始螺旋矩阵边长
    prime_count = 0; % 对角线质数计数
    total_count = 1; % 对角线数字总数,初始为1(中心的一个数字)

    % 检查给定的百分比p的范围
    if p <= 0 || p >= 1
        error('p值必须在0和1之间。');
    end

    % 循环找到符合条件的边长
    while true
        % 计算当前螺旋矩阵的角数字
        for i = 1:4
            number = (n-2) * (n-2) + i * (n - 1);
            total_count = total_count + 1;
            if isprime(number)
                prime_count = prime_count + 1;
            end
        end

        % 计算当前螺旋矩阵的质数比例
        prime_ratio = prime_count / total_count;

        % 如果质数比例低于p%,则返回当前边长
        if prime_ratio < p
            side_length = n;
            return;
        end

        % 增加螺旋矩阵的边长
        n = n + 2;
    end
end

在此脚本中:

  • find_spiral_side_length_below_p函数接收一个参数p,它是质数比例的阈值。
  • 脚本从3开始以奇数的n进行循环,直到找到一个螺旋矩阵使得质数比例低于p。
  • 对于每个n,脚本计算螺旋矩阵对角线上的质数数量,并检查它是否低于p。

例4.Problem 1642. BULLSEYE Part 2: Reference Problem 18 BULLSEYE

Given n (always odd), return output a that has concentric rings of the 1s and 0s around the center point. Examples:

 Input  n = 3
 Output a is [ 1 1 1 
               1 0 1
               1 1 1 ]
 Input  n = 5
 Output a is [    1     1     1     1     1
                  1     0     0     0     1
                  1     0     1     0     1
                  1     0     0     0     1
                  1     1     1     1     1]
给定一个奇数n,返回一个由1和0组成的输出a,围绕中心点形成同心环。例如:

输入 n = 3
输出 a 是 [ 1 1 1
           1 0 1
           1 1 1 ]

输入 n = 5
输出 a 是 [    1     1     1     1     1
               1     0     0     0     1
               1     0     1     0     1
               1     0     0     0     1
               1     1     1     1     1]

下面是一个MATLAB函数,它接受一个奇数n,并返回一个由1和0组成的矩阵,形成围绕中心点的同心环:

function a = concentric_rings(n)
    if mod(n, 2) == 0
        error('输入必须为奇数。');
    end

    a = ones(n);

    for i = 2:2:(n-1)
        a(i, (i+1):(n-i)) = 0;
        a((i+1):(n-i), i) = 0;
        a((i+1):(n-i), (n-i+1)) = 0;
        a((n-i+1), (i+1):(n-i)) = 0;
    end
end

 可以使用这个函数来生成给定n的输出a。例如:

n = 3;
output_a = concentric_rings(n);
disp(output_a);

n = 5;
output_a = concentric_rings(n);
disp(output_a);

这将打印出相应的矩阵。

例5.Problem 1704. Triangular matrices in 3D array

Given a 3D numeric array x, return an array y of the same size in which all entries to the right of the main diagonal are zero for y(:,:,i).

给定一个3D数值数组x,返回一个相同大小的数组y,在y(:,:,i)中,所有主对角线右侧的条目都为零。

Example

If

x(:,:,1) = 1 2 3
           4 5 6
           7 8 9
x(:,:,2) = 1 4 7
           2 5 8
           3 6 9
x(:,:,3) = 1 2 3
           1 2 3
           1 2 3

then

y(:,:,1) = 1 0 0
           4 5 0
           7 8 9
y(:,:,2) = 1 0 0
           2 5 0
           3 6 9
y(:,:,3) = 1 0 0
           1 2 0
           1 2 3

以下是MATLAB代码,实现了给定3D数值数组x,返回相同大小的数组y,在y(:,:,i)中,所有主对角线右侧的条目都为零:

function y = zero_entries_right_of_diagonal(x)
    % 获取数组的大小
    [m, n, p] = size(x);
    
    % 初始化结果数组
    y = x;
    
    % 遍历每个二维矩阵
    for k = 1:p
        % 将主对角线右侧的条目置零
        for i = 1:m
            for j = (i+1):n
                y(i, j, k) = 0;
            end
        end
    end
end

 你可以使用这个函数来得到你的示例的结果:

x(:,:,1) = [1 2 3; 4 5 6; 7 8 9];
x(:,:,2) = [1 4 7; 2 5 8; 3 6 9];
x(:,:,3) = [1 2 3; 1 2 3; 1 2 3];

y = zero_entries_right_of_diagonal(x);
for k = 1:size(y, 3)
    disp(['y(:,:,', num2str(k), ') =']);
    disp(y(:,:,k));
end

这将打印出示例中所示的y矩阵。

例6.Problem 1845. Pascal's pyramid

In Pascal's triangle each number is the sum of the two nearest numbers in the line above:

           1
         1   1
       1   2   1
     1   3   3   1
   1   4   6   4   1
A three-dimensional analog of Pascal's triangle can be defined as a square pyramid in which each number is the sum of the four nearest numbers in the layer above. Define a function pascalp(n) that returns the nth layer of this pyramid, as follows:

   pascalp(1)
      1
   pascalp(2)
      1  1
      1  1
   pascalp(3)
      1  2  1
      2  4  2
      1  2  1
   pascalp(4)
      1  3  3  1
      3  9  9  3
      3  9  9  3
      1  3  3  1
   pascalp(5)
      1  4  6  4 1
      4 16 24 16 4
      6 24 36 24 6
      4 16 24 16 4
      1  4  6  4 1
Note: Pascal's pyramid can also be defined as a tetrahedron (see http://en.wikipedia.org/wiki/Pascal%27s_pyramid), in which case the layers are triangular rather than square, and the numbers are the trinomial coefficients.
在帕斯卡三角形中,每个数字是上一行中最接近的两个数字的和:

       1
     1   1
   1   2   1
 1   3   3   1
1   4   6   4   1

帕斯卡三角形的三维类比可以定义为一个正方形金字塔,其中每个数字是上一层中最接近的四个数字的和。定义一个函数 pascalp(n),返回该金字塔的第n层,如下所示:

plaintext
   pascalp(1)
      1
   pascalp(2)
      1  1
      1  1
   pascalp(3)
      1  2  1
      2  4  2
      1  2  1
   pascalp(4)
      1  3  3  1
      3  9  9  3
      3  9  9  3
      1  3  3  1
   pascalp(5)
      1  4  6  4 1
      4 16 24 16 4
      6 24 36 24 6
      4 16 24 16 4
      1  4  6  4 1
注意:帕斯卡的金字塔也可以被定义为一个四面体(参见 http://en.wikipedia.org/wiki/Pascal's_pyramid ),在这种情况下,层是三角形而不是正方形,并且数字是三项式系数。

以下是MATLAB中实现帕斯卡金字塔的函数 pascalp(n)

function layer = pascalp(n)
    % 初始化金字塔层为全零矩阵
    layer = zeros(n);
    
    % 将第一行和最后一行的边界设置为1
    layer(1, :) = 1;
    layer(n, :) = 1;
    
    % 填充金字塔内部
    for row = 2:n-1
        for col = 2:n-1
            % 每个数字是上一层中最接近的四个数字的和
            layer(row, col) = layer(row-1, col-1) + layer(row-1, col) + layer(row-1, col+1) + layer(row, col-1);
        end
    end
end

 你可以通过调用 pascalp(n) 函数来获取帕斯卡金字塔的第 n 层。

例7.Problem 2064. Generate this matrix

Generate the following matrix.

n = 2;
out = [-4    -3    -2    -1     0
       -3    -2    -1     0     1
       -2    -1     0     1     2
       -1     0     1     2     3
        0     1     2     3     4];
n = 5;
out = [-10    -9    -8    -7    -6    -5    -4    -3    -2    -1     0
        -9    -8    -7    -6    -5    -4    -3    -2    -1     0     1
        -8    -7    -6    -5    -4    -3    -2    -1     0     1     2
        -7    -6    -5    -4    -3    -2    -1     0     1     2     3
        -6    -5    -4    -3    -2    -1     0     1     2     3     4
        -5    -4    -3    -2    -1     0     1     2     3     4     5
        -4    -3    -2    -1     0     1     2     3     4     5     6
        -3    -2    -1     0     1     2     3     4     5     6     7
        -2    -1     0     1     2     3     4     5     6     7     8
        -1     0     1     2     3     4     5     6     7     8     9
         0     1     2     3     4     5     6     7     8     9    10];

可以使用以下 MATLAB 代码生成所需的矩阵:

function out = generateMatrix(n)
    % 计算矩阵大小
    rows = 2*n + 1;
    cols = 2*n + 1;

    % 初始化矩阵为全零矩阵
    out = zeros(rows, cols);

    % 填充矩阵
    for i = 1:rows
        for j = 1:cols
            % 计算每个元素的值
            out(i, j) = (i - 1) - n + (j - 1);
        end
    end
end

 然后,你可以调用 generateMatrix(n) 函数来生成所需的矩阵,其中 n 是你想要的矩阵的维度大小。

例7.Problem 2177. Rainbow matrix

Create a "rainbow matrix" as described in the following examples

 Input = 3
 Output = [ 1 2 3
            2 3 2 
            3 2 1 ]
 Input = 5
 Output = [ 1 2 3 4 5
            2 3 4 5 4
            3 4 5 4 3
            4 5 4 3 2
            5 4 3 2 1 ]

可以使用以下 MATLAB 代码生成所需的“彩虹矩阵”:

function rainbow = createRainbowMatrix(n)
    % 初始化彩虹矩阵
    rainbow = zeros(n);

    % 填充上半部分
    for i = 1:n
        for j = 1:n
            if j <= i
                rainbow(i, j) = j;
            else
                rainbow(i, j) = n - j + 1;
            end
        end
    end

    % 填充下半部分
    for i = n+1:2*n-1
        for j = 1:n
            if j <= 2*n - i
                rainbow(i, j) = j;
            else
                rainbow(i, j) = 2*n - i;
            end
        end
    end
end

然后,你可以调用 createRainbowMatrix(n) 函数来生成所需的彩虹矩阵,其中 n 是矩阵的维度大小。

例8.Problem 2336. Calendar Matrix

Return a calendar matrix for the given values of month and year. Assume that Sunday is the first day of the week. The resulting calendar month will have seven columns and only as many rows (weeks) as needed to display all days of the month. Thus it might have either 4, 5, or 6 rows. Days preceding the first of the month or following the last of the month are given by zeros.

Examples

 >> mo = 1
 >> yr = 2014
 >> momat = makeCalendar(mo,yr)
     0     0     0     1     2     3     4
     5     6     7     8     9    10    11
    12    13    14    15    16    17    18
    19    20    21    22    23    24    25
    26    27    28    29    30    31     0
 >> mo = 2
 >> yr = 2015
 >> momat = makeCalendar(mo,yr)
     1     2     3     4     5     6     7
     8     9    10    11    12    13    14
    15    16    17    18    19    20    21
    22    23    24    25    26    27    28
 >> mo = 10
 >> yr = 2010
 >> momat = makeCalendar(mo,yr)
     0     0     0     0     0     1     2
     3     4     5     6     7     8     9
    10    11    12    13    14    15    16
    17    18    19    20    21    22    23
    24    25    26    27    28    29    30
    31     0     0     0     0     0     0

以下是生成所需日历矩阵的 MATLAB 代码:

function calendar = makeCalendar(month, year)
    % 获取月份的天数
    daysInMonth = eomday(year, month);

    % 获取月份第一天是星期几
    firstDayOfWeek = weekday(datetime(year, month, 1));

    % 计算日历矩阵的大小
    numRows = ceil((daysInMonth + firstDayOfWeek - 1) / 7);
    calendar = zeros(numRows, 7);

    % 填充日历矩阵
    currentDay = 1;
    for i = 1:numRows
        for j = 1:7
            % 如果当前位置在月份的有效日期范围内,则填充日期;否则填充为零
            if currentDay <= daysInMonth && (i > 1 || j >= firstDayOfWeek)
                calendar(i, j) = currentDay;
                currentDay = currentDay + 1;
            end
        end
    end
end

 然后,你可以调用 makeCalendar(month, year) 函数来生成所需的日历矩阵,其中 month 是月份,year 是年份。

例9.Problem 2340. Numbers spiral diagonals (Part 1)

Inspired by Project Euler n°28 et 58.

A n x n spiral matrix is obtained by starting with the number 1 and moving to the right in a clockwise direction.

For exemple with n=5, the spiral matrix is :

                       21 22 23 24 25
                       20  7  8  9 10
                       19  6  1  2 11
                       18  5  4  3 12
                       17 16 15 14 13

In this example, the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in any n by n spiral (n always odd) ?

HINTS: You want the diagonals, not the whole matrix.

受到欧拉计划第28和第58题的启发。

一个 n x n 的螺旋矩阵是通过从数字1开始,按顺时针方向向右移动而获得的。

例如,当 n=5 时,螺旋矩阵是:

                   21 22 23 24 25
                   20  7  8  9 10
                   19  6  1  2 11
                   18  5  4  3 12
                   17 16 15 14 13

在这个例子中,对角线上数字的总和是101。

在任何 n x n 的螺旋矩阵中(n 总是奇数),对角线上数字的总和是多少?

提示:你需要对角线上的数字,而不是整个矩阵。

以下是MATLAB代码,用于计算任何 n x n 螺旋矩阵中对角线上数字的总和:

function diagonalSum = spiralDiagonalSum(n)
    % 初始化对角线总和为1,因为第一个数字1是螺旋矩阵的中心
    diagonalSum = 1;
    
    % 从3开始,每次增加2,直到n
    for i = 3:2:n
        % 计算当前圈的四个角的数字,每个角的数字都是当前圈的最大数字减去适当的偏移量
        topRight = i^2;
        topLeft = topRight - (i - 1);
        bottomLeft = topLeft - (i - 1);
        bottomRight = bottomLeft - (i - 1);
        
        % 将当前圈的四个角的数字添加到对角线总和中
        diagonalSum = diagonalSum + topRight + topLeft + bottomLeft + bottomRight;
    end
end

 你可以调用 spiralDiagonalSum(n) 函数来计算任何给定奇数 n 的螺旋矩阵中对角线上数字的总和。

例10.Problem 2342. Numbers spiral diagonals (Part 2)

Inspired by Project Euler n°28 and 58.

A n x n spiral matrix is obtained by starting with the number 1 and moving to the right in a clockwise direction.

For example with n=5, the spiral matrix is :

21 22 23 24 25

20 7 8 9 10

19 6 1 2 11

18 5 4 3 12

17 16 15 14 13

The sum of the numbers on the diagonals is 101 (See problem 2340) and you have 5 primes (3, 5, 7, 13, 17) out of the 9 numbers lying along both diagonals. So the prime ratio is 5/9 ≈ 55%.

With a 7x7 spiral matrix, the ratio is 62% (8 primes out of the 13 diagonal numbers).

What is the side length (always odd and greater than 1) of the square spiral for which the ratio of primes along both diagonals FIRST falls below p% ? (0<p<1)

受欧拉计划第28和第58题的启发。 一个 n x n 的螺旋矩阵是通过从数字1开始,按顺时针方向向右移动而获得的。 例如,当 n=5 时,螺旋矩阵是: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 对角线上数字的总和是101(参见问题2340),而这9个对角线上的数字中有5个是素数(3、5、7、13、17),因此素数比率为5/9 ≈ 55%。 对于7x7的螺旋矩阵,素数比率为62%(13个对角线数字中有8个是素数)。 求螺旋矩阵的边长(必须是奇数且大于1),使得对角线上素数的比率首次低于 p%?(0<p<1)

以下是求解螺旋矩阵边长的MATLAB代码,以使得对角线上素数的比率首次低于给定的阈值 p:

function sideLength = primeRatioThreshold(p)
    % 初始化边长为3,因为第一个螺旋矩阵是3x3
    sideLength = 3;
    primesCount = 0;
    totalDiagonalCount = 1; % 初始情况下只有中心的数字1
    
    while true
        % 计算当前螺旋矩阵的四个角的数字
        topRight = sideLength^2;
        topLeft = topRight - (sideLength - 1);
        bottomLeft = topLeft - (sideLength - 1);
        bottomRight = bottomLeft - (sideLength - 1);
        
        % 更新对角线上素数的计数
        primesCount = primesCount + isprime(topRight) + isprime(topLeft) + isprime(bottomLeft) + isprime(bottomRight);
        
        % 更新对角线上数字的总数
        totalDiagonalCount = totalDiagonalCount + 4;
        
        % 计算当前素数比率
        primeRatio = primesCount / totalDiagonalCount;
        
        % 如果素数比率首次低于给定阈值,则返回当前边长
        if primeRatio < p
            break;
        end
        
        % 更新边长,由于螺旋矩阵的边长总是奇数,因此每次增加2
        sideLength = sideLength + 2;
    end
end

 可以调用 primeRatioThreshold(p) 函数,并传入你想要的素数比率阈值,以获取螺旋矩阵的边长。

例11.Problem 2365. Generate this matrix

For a given odd integer n, generate a matrix as follows:

Input: n = 5; Output:

 [  2     1     0     0     0
    1     1     1     0     0
    0     1     0     1     0
    0     0     1     1     1
    0     0     0     1     2  ]

Input: n=7; Output:

 [  3     1     0     0     0     0     0
    1     2     1     0     0     0     0
    0     1     1     1     0     0     0
    0     0     1     0     1     0     0
    0     0     0     1     1     1     0
    0     0     0     0     1     2     1
    0     0     0     0     0     1     3 ]

For further understanding of the pattern, please check the test suite.

给定一个奇整数 n,生成如下矩阵:

输入:n = 5;输出:

[ 2 1 0 0 0 1 1 1 0 0 0 1 0 1 0 0 0 1 1 1 0 0 0 1 2 ] 输入:n = 7;输出:

[ 3 1 0 0 0 0 0 1 2 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 0 0 0 0 0 1 2 1 0 0 0 0 0 1 3 ]

为了进一步理解规律,请查看测试套件。

以下是生成给定奇整数 n 对应矩阵的 MATLAB 代码:

function matrix = generateMatrix(n)
    if mod(n, 2) == 0
        error('输入必须为奇整数');
    end
    
    matrix = zeros(n);
    
    % 填充主对角线和次对角线
    for i = 1:n
        matrix(i, i) = ceil(i/2);
        if i < n
            matrix(i, i+1) = 1;
            matrix(i+1, i) = 1;
        end
    end
end

可以使用 generateMatrix(n) 函数来生成给定奇整数 n 对应的矩阵。例如:

n = 5;
output = generateMatrix(n);
disp(output);

n = 7;
output = generateMatrix(n);
disp(output);

这将输出给定 n 对应的矩阵。

例12.Problem 2455. Diagonal of a Spiral Matrix

Write a function that will return same output as diag(spiral(n)). The only exception is that spiral and diag functions are not allowed in your function. Also, loops are not allowed.

编写一个函数,其返回值与 diag(spiral(n)) 相同。唯一的例外是在你的函数中不允许使用 spiral 和 diag 函数,也不允许使用循环。

 你可以使用以下递归方法来实现这个功能:

function result = spiral_diag(n)
    if n == 1
        result = 1;
    else
        result = (n^2 - (n-2)^2) + spiral_diag(n-2);
    end
end

该函数递归地计算对角线上的元素值,避免了直接使用 spiraldiag 函数,也没有使用循环。然后,你可以使用该函数来生成对角线矩阵,如下所示:

n = 5;
matrix = zeros(n);
for i = 1:n
    matrix(i, i) = spiral_diag(i);
end
disp(matrix);

这将生成一个与 diag(spiral(n)) 相同的矩阵。

例13.Problem 2694. The Matrix Construction

Given two input ,first one is CN (Column Number), Second one is Dim Can you produce such a matrix for example

给定两个输入,第一个是 CN(列数),第二个是 Dim。你能生成这样的矩阵吗?例如:

当 CN=6,Dim=2 时,

CN=6; Dim=2

 K = [1     1     0     0     0     0
      0     0     1     1     0     0
      0     0     0     0     1     1]

CN=7; Dim=2

   K =[  1     1     0     0     0     0     0
         0     0     1     1     0     0     0
         0     0     0     0     1     1     0
         1     0     0     0     0     0     1]

可以使用 MATLAB 编写一个函数来生成这样的矩阵。以下是一个示例函数:

function K = generate_matrix(CN, Dim)
    if CN <= Dim
        error('CN 必须大于 Dim。');
    end

    % 计算矩阵的行数
    num_rows = CN - Dim + 1;
    
    % 初始化矩阵
    K = zeros(num_rows, CN);
    
    % 填充矩阵的非零值
    for i = 1:num_rows
        K(i, i:i+Dim-1) = 1;
    end
end

 可以调用这个函数来生成指定 CN 和 Dim 的矩阵,例如:

CN = 6;
Dim = 2;
K = generate_matrix(CN, Dim);
disp(K);

CN = 7;
Dim = 2;
K = generate_matrix(CN, Dim);
disp(K);

这将分别生成 CN=6,Dim=2 和 CN=7,Dim=2 时的矩阵。

例14.Problem 2813. Create a block diagonal matrix

A block diagonal matrix is a square matrix that can be written as

   A = [a  0  0  0
        0  b  0  0
        0  0  c  0
        0  0  0 ...]

where a, b, c etc. are all square matrices.

Construct A such that

   A = [a  0  0  0
        0  a  0  0
        0  0  a  0
        0  0  0 ...]

where a is allowed to be non-square or empty and occurs n times. n is always an integer greater than or equal to 0.

Examples:

   a = [1 2 3], n = 3

gives

   A = [1 2 3 0 0 0 0 0 0
        0 0 0 1 2 3 0 0 0
        0 0 0 0 0 0 1 2 3]

一个块对角矩阵是一个方阵,可以写成

A = [a 0 0 0 0 b 0 0 0 0 c 0 0 0 0 ...] 其中a、b、c等都是方阵。

构造矩阵A,使得

A = [a 0 0 0 0 a 0 0 0 0 a 0 0 0 0 ...] 其中a可以是非方阵或空,且出现n次。n始终为大于或等于0的整数。

例子:

a = [1 2 3], n = 3 得到

A = [1 2 3 0 0 0 0 0 0 0 0 0 1 2 3 0 0 0 0 0 0 0 0 0 1 2 3]

function A = block_diagonal(a, n)
    % 确定矩阵的维度
    dim_a = size(a);
    dim_a = dim_a(2);
    dim_A = dim_a * n;
    
    % 初始化矩阵A
    A = zeros(dim_A);
    
    % 填充矩阵A
    for i = 1:n
        start_row = (i - 1) * dim_a + 1;
        end_row = i * dim_a;
        A(start_row:end_row, start_row:end_row) = a;
    end
end

 可以调用这个函数来生成矩阵A,例如:

a = [1 2 3];
n = 3;
A = block_diagonal(a, n);
disp(A);

这将生成你所需的矩阵A。

例15,Problem 8073. Matrix Construction I

Given n, construct a matrix as shown in the example below.

Example

For n=8, the output should look like this:

问题 8073. 矩阵构造 I

给定 n,按照下面的例子构造一个矩阵。

例子

当 n=8 时,输出应该如下所示:

 1 2 3 4 0 0 0 0
 1 2 3 4 0 0 0 0
 1 2 3 4 0 0 0 0
 1 2 3 4 0 0 0 0
 0 0 0 0 4 3 2 1
 0 0 0 0 4 3 2 1
 0 0 0 0 4 3 2 1
 0 0 0 0 4 3 2 1

以下是 MATLAB 代码实现:

function A = construct_matrix(n)
    % 构造上半部分矩阵
    upper_half = repmat(1:n, n, 1);
    
    % 构造下半部分矩阵
    lower_half = fliplr(upper_half);
    
    % 构造完整矩阵
    A = [upper_half, zeros(n, n); zeros(n, n), lower_half];
end

可以调用这个函数来生成矩阵,例如:

n = 8;
A = construct_matrix(n);
disp(A);

 这将生成你所需的矩阵。

 

  • 12
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值