登录论坛

查看完整版本 : 如何在MATLAB中生成以下矩阵?


poster
2019-12-10, 16:49
我想从向量生成一个“阶梯状”的矩阵。

输入向量示例: [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] 是否有比以下方法更简单(或内置)的方法?

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
回答:
我不知道有内置函数可以执行此操作,但是这是一个矢量化解决方案:

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); 编辑:我喜欢乔纳斯 (https://stackoverflow.com/questions/1903592/matlab-matrix-generation-help/1911977#1911977)必须使用BLKDIAG (http://www.mathworks.com/help/techdoc/ref/blkdiag.html)的想法。在我进一步缩短这个想法之前,我忍不住想了一下 (http://www.mathworks.com/help/techdoc/ref/mat2cell.html) (使用MAT2CELL (http://www.mathworks.com/help/techdoc/ref/mat2cell.html)而不是ARRAYFUN (http://www.mathworks.com/help/techdoc/ref/arrayfun.html) ):

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

更多&回答... (https://stackoverflow.com/questions/1903592)