sub2ind error
6 views (last 30 days)
Show older comments
i use this to make an accumulator array but it comes error
mat=zeros(250,250);
x=linspace(0,25.1923,100);
y=linspace(-7.9089e+003,313,100);
index=sub2ind(size(mat),round(y),round(x));
i run that code but 'out of range subscript'
that's why ? explain me please
0 Comments
Accepted Answer
Image Analyst
on 28 Apr 2012
You need to convert from "real world units" into units of matrix elements. Below I used the "point-slope" formula for a line to convert your real world units into indexes. Here's one way that's fairly general for linear transforms like you used: (It's not that complicated, just try to follow the comments.)
mat=zeros(250,250);
% Create sample x and y vectors in "real world" units.
x=linspace(0,25.1923,100); % Columns
y=linspace(-7.9089e+003,313,100); % Rows.
% Figure out what indexes those are
% in terms of elements or indexes.
% These indexes will range from 1 to 100 (or the length of x or y).
slopeX = (max(x) - min(x)) / (length(x)-1)
rowIndexes = int32(1 + (x - min(x))/ slopeX)
slopeY= (max(y) - min(y)) / (length(y)-1)
columnIndexes = int32(1 + (y - min(y))/ slopeY)
% Now construct a list of all linear indices in the entire mat matrix.
% (That was wanted for some reason.)
linearIndexes = sub2ind(size(mat), rowIndexes, columnIndexes)
% Now do it for just one particular x and y
% where x and y are in "real world" units.
x0 = 13 % Let's just say you wanted this for example.
y0 = 42
rowIndex = int32(1 + x0 / slopeX)
columnIndex = int32(1 + y0 / slopeX)
% Get the linear index of that one particular point.
linearIndex = sub2ind(size(mat),round(rowIndex),round(columnIndex))
% Report the value of mat() there:
fprintf('mat(%d) = %f\n', linearIndex, mat(linearIndex));
More Answers (2)
Wayne King
on 28 Apr 2012
Your x and y vectors are not suitable for sub2ind(). You have an x vector that starts at 0 which is not a valid linear index in MATLAB and you have y-values that are negative, which are not valid linear indices in MATLAB.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!