#討論 昨日詢問MATLAB斜線相加取平均,有更好的解法

昨日詢問MATLAB hankel matrix如何斜線相加取平均,我有找到參考資料:
其透過idx製作右上-左下同類別,再使用accumarray可累加。而你想要的是取平均,可以在後面加上想要的fuction(@mean)即可。 結果:
megapx
附上程式碼:
megapx
clear; rng(0); Hq = randi([0,10],7,6) [m,n] = size(Hq); idx = hankel(1:m, m:m+n-1) out = accumarray(idx(:),Hq(:),[],@mean) hankel(out(1:m),out(m:m+n-1)) _____ PS. 我實測之後,上次自製的zeropadding速度比此方法快,哈
megapx
rng(0); % create random Hq with seed Hq = randi([0 10], 7,6); % ([range], matrixsize) [~, ~, Hz] = SVDhankelZeropadding(Hq) function [HzRow, HzCol, Hz] = SVDhankelZeropadding(Hq) [nrow, ncol] = size(Hq); % get Hq size Hqzeropadding = NaN(nrow, nrow+ncol-1); % initial size for k = 1:nrow % zero padding each row (NaN padding) Hqzeropadding(k, (0:ncol-1)+k) = Hq(k, :); end % sum each column / count each column HqDiagAvg = sum(Hqzeropadding, 'omitnan')./sum(~isnan(Hqzeropadding)); % outputs HzCol = HqDiagAvg(1:nrow); % named "Col" to mach hankel example HzRow = HqDiagAvg(nrow:end); % named "Row" to mach hankel example Hz = hankel(HzCol, HzRow); end
留言
官方的說明圖,可能會更了解 The following graphic illustrates the behavior of accumarray on a vector of temperature data taken over a 12-month period. To find the maximum temperature reading for each month, accumarray applies the max function to each group of values in temperature that have identical subscripts in month.
megapx
No values in month point to the 5, 6, 7, or 10 positions of the output. These elements are 0 in the output by default, but you can specify a value to fill in using fillval.