PDA

查看完整版本 : 如何获得矩阵的对角线并将其连接起来?


poster
2019-12-10, 20:48
简洁版本

如何在MATLAB中做concatMap ?我正在尝试从一系列较小的,大小不同的向量构建单个向量。我知道我可以做:

result = []; for i=1:N result = [result nextPart(i)]; end 但这会严重影响速度,因此必须有一种更聪明的方法来concatMap 。

长版

我正在尝试编写一个MATLAB函数来返回块的反对角线。例如,如果您有块:

1 2 4 3 5 7 6 8 9 然后counterDiagonals(block)应该返回[1 2 3 4 5 6 7 8 9] 。

我有一个函数,可以找到一个块的单个计数器对角线。即counterDiagonal(x, 3)将返回[4 5 6] 。

因此, counterDiagonals应该和concatMap counterDiagonal(x, i) (1:N)一样简单,其中N是(2*length(block)-1) 。如何在MATLAB中高效地做到这一点?



回答:

我相信您可以使用ROT90 (http://www.mathworks.com/help/techdoc/ref/rot90.html)和SPDIAGS (http://www.mathworks.com/help/techdoc/ref/spdiags.html)功能来完成:

A = [1 2 4; 3 5 7; 6 8 9]; %# Sample matrix result = rot90(A); %# Rotate the matrix counter-clockwise result = spdiags(result); %# Find all the diagonals result = result(result ~= 0).'; %'# Remove zero padding and format the results %# into a row vector 并且您应该最终得到result = [1 2 3 4 5 6 7 8 9] 。

编辑:正如Amro在评论中提到的那样,以上代码假定原始矩阵A中没有零。如果原始矩阵中存在零,一种解决方案是用您知道原始矩阵中未出现的非零标志值(例如NaN (http://www.mathworks.com/help/techdoc/ref/nan.html) )替换它们,运行上面的代码,然后替换在结果中标记值:

A = [0 2 4; 3 0 7; 6 8 0]; %# Sample matrix result = rot90(A); %# Rotate the matrix counter-clockwise result(result == 0) = nan; %# Replace zeroes with NaN result = spdiags(result); %# Find all the diagonals result = result(result ~= 0).'; %'# Remove zero padding and format the results %# into a row vector result(isnan(result)) = 0; %# Put the original zeroes back

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