如何在MATLAB中生成以下矩阵? [英] How can I generate the following matrix in MATLAB?

查看:94
本文介绍了如何在MATLAB中生成以下矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从矢量生成一个阶梯状"的矩阵.

I want to generate a matrix that is "stairsteppy" from a vector.

输入向量示例:[8 12 17]

示例输出矩阵:

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

是否有比以下方法更简单(或内置)的方法?

Is there an easier (or built-in) way to do this than the following?:

function M = stairstep(v)
M = zeros(length(v),max(v));
v2 = [0 v];
for i = 1:length(v)
   M(i,(v2(i)+1):v2(i+1)) = 1;
end

推荐答案

我不知道有内置函数可以执行此操作,但这是一个矢量化解决方案:

There's no built-in function I know of to do this, but here's one vectorized solution:

v = [8 12 17];
N = numel(v);
M = zeros(N,max(v));
M([0 v(1:N-1)]*N+(1:N)) = 1;
M(v(1:N-1)*N+(1:N-1)) = -1;
M = cumsum(M,2);

编辑:我喜欢 Jonas 必须使用 BLKDIAG .在我进一步缩短这个想法之前,我忍不住想了一下(使用 MAT2CELL 代替 ARRAYFUN ):

I like the idea that Jonas had to use BLKDIAG. I couldn't help playing with the idea a bit until I shortened it further (using MAT2CELL instead of ARRAYFUN):

C = mat2cell(ones(1,max(v)),1,diff([0 v]));
M = blkdiag(C{:});

这篇关于如何在MATLAB中生成以下矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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