Scan for elements of matrix, to limit them in an interval, and change them.
2 views (last 30 days)
Show older comments
Isai Fernandez
on 15 Apr 2018
Commented: Stephen23
on 15 Apr 2018
I am learning to write my programs in Matlab.
I want to limit the value of the matrix elements for some interval, and if they don't accomplish the condition, change them.
For example, for a matrix:
A = |a_11 a_12|
|a_21 a_22|
Limit the values of a_ii for an interval:
-m >= a_ii <= +m.
In my code, the values of the matrix come from other calculation, but I want to limit the values of them; in any case, if a_ii is greater of +m, so change this element of the matrix for +m, the same for -m, but if they are within the limits, let them with its value.
I don't know the size of the matrix, because it depends on preview calculation. Indeed, my matrix always will be a column matrix.
P.D. Sorry for my poor english.
0 Comments
Accepted Answer
Walter Roberson
on 15 Apr 2018
a_ii = min( +m, max( -m, a_ii) );
max(-m, a_ii) takes the maximum of -m and a_ii, which is going to be -m if a_ii < -m, but otherwise would be a_ii . So now we have put a lower bound on a_ii . Then min( +m, that result) is going to be the minimum of +m and the result, which is going to be +m if the result exceeds +m and otherwise would be unchanged. So by the end of the min() we have a value that is constrained to -m to +m
3 Comments
Walter Roberson
on 15 Apr 2018
In the above code, a_ii can be a matrix of all of the elements you wish to limit in this way. You can use this code even for the elements that might be already in range -- no need to select only the ones out of range first.
Stephen23
on 15 Apr 2018
"Do you mean, one by one?"
No, you don't need any loops or "one-by-one" operations. You can use this method with the entire array at once: simply supply the limit values as scalars (if they are the same for all array elements) or as arrays of the same size.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!