![]() |
如何在MATLAB中生成以下矩阵?
我想从向量生成一个“阶梯状”的矩阵。
输入向量示例: [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); [B]编辑:[/B]我喜欢[URL="https://stackoverflow.com/questions/1903592/matlab-matrix-generation-help/1911977#1911977"]乔纳斯[/URL]必须使用[URL="http://www.mathworks.com/help/techdoc/ref/blkdiag.html"]BLKDIAG[/URL]的想法。在我进一步缩短这个想法之前,我[URL="http://www.mathworks.com/help/techdoc/ref/mat2cell.html"]忍不住想了一下[/URL] (使用[URL="http://www.mathworks.com/help/techdoc/ref/mat2cell.html"]MAT2CELL[/URL]而不是[URL="http://www.mathworks.com/help/techdoc/ref/arrayfun.html"]ARRAYFUN[/URL] ): C = mat2cell(ones(1,max(v)),1,diff([0 v])); M = blkdiag(C{:}); [url=https://stackoverflow.com/questions/1903592]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 01:08。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.