![]() |
如何获得矩阵的对角线并将其连接起来?
[B]简洁版本[/B]
如何在MATLAB中做concatMap ?我正在尝试从一系列较小的,大小不同的向量构建单个向量。我知道我可以做: result = []; for i=1:N result = [result nextPart(i)]; end 但这会严重影响速度,因此必须有一种更聪明的方法来concatMap 。 [B]长版[/B] 我正在尝试编写一个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中高效地做到这一点? [B]回答:[/B] 我相信您可以使用[URL="http://www.mathworks.com/help/techdoc/ref/rot90.html"]ROT90[/URL]和[URL="http://www.mathworks.com/help/techdoc/ref/spdiags.html"]SPDIAGS[/URL]功能来完成: 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] 。 [B]编辑:[/B]正如Amro在评论中提到的那样,以上代码假定原始矩阵A中没有零。如果原始矩阵中存在零,一种解决方案是用您知道原始矩阵中未出现的非零标志值(例如[URL="http://www.mathworks.com/help/techdoc/ref/nan.html"]NaN[/URL] )替换它们,运行上面的代码,然后替换在结果中标记值: 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 [url=https://stackoverflow.com/questions/4300606]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 11:02。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.