简短版本
如何在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中以一种有效的方式做到这一点呢?
发布于 2010-11-29 11:34:48
我相信您想要做的事情可以通过使用函数ROT90和SPDIAGS来完成
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),运行上面的代码,然后替换结果中的标志值:
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发布于 2010-11-29 23:28:49
公认答案的一个问题是:如果矩阵A有零,它们将被错误地从结果中删除。相反,您应该处理元素的索引:
A = [0 2 4; 3 5 7; 6 8 9]; %# Sample matrix (contains zeros)
ind = reshape(1:numel(A), size(A)); %# indices of elements
ind = fliplr( spdiags( fliplr(ind) ) ); %# get the anti-diagonals (or use ROT90)
ind(ind==0) = []; %# keep non-zero indices
result = A(ind); %# get elements in desired order这与我在前面的问题中给出的this answer非常相似(不同之处在于反数字的顺序是相反的)。
发布于 2010-11-29 11:40:18
简短版本:
如果你预先分配了你的result数组,一切都会快很多。
result = zeros(1,knownLengthOfResultsArray); %# such as "numel(block)"
ct = 1;
for i=1:N
tmp = nextPart(i);
nTmp = length(tmp);
result(ct:ct+nTmp-1) = tmp;
ct = ct + nTmp;
end长版本:
然而,重写你的算法可能更有效率。例如,请参阅this question答案(首先在您的阵列上使用fliplr )或@gnovice's answer。
https://stackoverflow.com/questions/4300606
复制相似问题