How to make MATLAB ignore indices that are out of bounds for a matrix
16 views (last 30 days)
Show older comments
I am working on a problem that involves the matrix A of size m,n.
if an element of A changes value, i want to make the elements next to it (left, top, right, and below) change value too if they have a certain value of their own.
when i now try to check the elements next to for example A(2,1), it will give me an error message because there exists no element A(2,0),
currently i can only think of a solution that uses many individual if statements for the outer regions of the matrix. which looks something like this:
if mi == 1
if ni == 1 %the element in the upper left corner
if A(1,1) == 2
if A(1,2) == value %the element to the right of the upper left corner
%change value of A(1,2)
if A(2,1) == value
%change value of A(2,1) %the element below the upper left corner
and so on for all the elements that face the outside of the matrix...
0 Comments
Accepted Answer
Sean de Wolski
on 14 Nov 2013
One way (of many):
Use min() and max() to figure out when the range is outside:
idx = -2:12; %indices outside of range 1:10
x = randperm(10); %10 values
Inside the range is less than or equal to the max of the size and greater than or equal to 1:
x(max(min(idx,size(x,2)),1))
2 Comments
Sean de Wolski
on 14 Nov 2013
Looks good!
Just to point out size(x,2) is looking at the end of a row. If you're doing this for columns as well, use size(x,1) when identifying the max of a column.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!