How to find subscripts of each element inside many rectangular regions of a matrix?

2 次查看(过去 30 天)
rowStart = [2; 4; 7]; % a column, may be of more than thousand element
rowEnd = [3; 4; 9]; % a column, may be of more than thousand element
colStart = [1; 1; 2]; % a column, may be of more than thousand element
colEnd = [3; 1; 3]; % a column, may be of more than thousand element
% for obvious reason size of all above vectors would be same
function [subRow subCol] = elementwisesubscript(rowStart, rowEnd, colStart, colEnd)
%% interesested function
% I tried 'arrayfun', its working but is slow
% I tried for loop, 1.5x faster than arrayfun. But thinking there could be a smart optimized way
% needed a code, that is matlab coder compatible.
end
Thanks a lot for consideration.
Attached image further examplifies.

回答(1 个)

JAI PRAKASH
JAI PRAKASH 2018-11-25
This is 10x times than arrayfun, still i think can be optimsed.
Because no pre-allocation in below code and many other potential improvements.
function [subRow, subCol] = elementwisesubscript(rowStart, rowEnd, colStart, colEnd)
%% subRow identification
rowLength = rowEnd-rowStart+1;
maxRowLength = max(rowLength);
subRow = repmat(rowStart, 1, maxRowLength) + repmat(0:maxRowLength-1, length(rowStart),1);
colLength = colEnd-colStart+1;
for i =2:maxRowLength
subRow(rowLength<i, i) = 0;
end
subRow = subRow';
subRow = subRow(:);
subRow = repelem(subRow, repelem(colLength, maxRowLength));
subRow(subRow==0)=[];
%% subCol identification
maxColLength = max(colLength);
subCol = repmat(colStart, 1, maxColLength) + repmat(0:maxColLength-1, length(colStart),1);
for i =2:maxColLength
subCol(colLength<i, i) = 0;
end
subCol = subCol(:);
colLengthMat = repmat(rowLength,1,maxColLength);
colLengthMat = colLengthMat(:);
subCol = repelem(subCol, colLengthMat);
subCol = reshape(subCol, [], maxColLength);
subCol = subCol';
subCol = subCol(:);
subCol(subCol==0)=[];
end

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by