创建一个“金字塔"矩阵 [英] Create a "pyramid" matrix

查看:100
本文介绍了创建一个“金字塔"矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我得到一个对称的行向量,其长度为奇数,其中每个元素小于向量前半部分的下一个,而每个元素大于后半部分的下一个,中间元素为最大的. (例如[1 2 3 2 1][10 20 50 20 10]).

Say I'm given a symmetric row vector with an odd length where each element is smaller than the next one in the first half of the vector and each element is bigger than the next one in the second half and the middle element is the biggest. (e.g [1 2 3 2 1] or [10 20 50 20 10]).

我想创建一个方阵,其中该行向量是它的中间行,等效列向量(v')是它的中间列,而每行或每一列都是给定向量的简化版本(根据中间值)此行或列中的元素.当没有更多的原始元素"时,我们放入0.

I want to create a square matrix where this row vector is its middle row and the equivalent column vector (v') is its middle column and each other row or column is a reduced version of the given vector according to the middle element in this row or column. And when there are no more "original elements" we put 0.

示例:

如果v = [1 2 3 2 1]我们得到

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

如果v = [3 5 3]我们得到

0 3 0  
3 5 3  
0 3 0  

到目前为止,我做的是:我使用编写的这段代码成功创建了一个矩阵,其中v作为中间行,v'作为中间列.

What I did so far: I managed to create a matrix with v as the middle row and v' as the middle column with this code I wrote:

s = length(vector);
matrix= zeros(s);
matrix(round(s/2),:) = vector;
matrix(:, round(s/2)) = vector';

但是卡住了分配其他值的可能性.

but got stuck with assigning the other values.

推荐答案

另一种动手方法是从hankel矩阵开始将矩阵生成为镶嵌图.为了进行性能比较,下面的版本使用与 @Divakar的解决方案相同的格式:

A more hands-on approach is to produce your matrix as a mosaic, starting from a hankel matrix. For performance comparison, here's a version using the same format as @Divakar's solution:

function out=pyramid_hankel(v)

%I suggest checking v here
%it should be odd in length and a palindrome    

i0=ceil(length(v)/2);
v2=v(i0:end);

Mtmp=hankel(v2);
out=zeros(length(v));
out(i0:end,i0:end)=Mtmp;
out(1:i0-1,i0:end)=flipud(Mtmp(2:end,:));
out(:,1:i0-1)=fliplr(out(:,i0+1:end));

>> pyramid_hankel([1 2 3 2 1])

ans =

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

对于v=[1 2 3 2 1],起始块为hankel([3 2 1]),即

ans =

     3     2     1
     2     1     0
     1     0     0

从这里应该清楚发生了什么.

From here it should be clear what's happening.

这篇关于创建一个“金字塔"矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆