I have matrix A = [1 2 3 4 5 6 7 8];
I try to limit the matrix to numbers greater than 3 and less than 6 how do I do it ?
I use this line but it assigns numbers less then 3 to 3 and numbers greater then six to six. Instead i want to eliminate those numbers in matrix which dont belong in this range.
max(min(A,3),6)

 Réponse acceptée

Karim
Karim le 26 Déc 2022
Modifié(e) : Karim le 26 Déc 2022
You can use logical indexing to obtain such a result, see below for a demonstration
A = [1 2 3 4 5 6 7 8];
% define the limits
maxValue = 6;
minValue = 3;
% use logic to find the indexes
idx = A >= maxValue | A <= minValue;
% set the values we don't want to zero
A(idx) = 0
A = 1×8
0 0 0 4 5 0 0 0
it is off course also possible to do this in a single line:
A = [1 2 3 4 5 6 7 8];
A(A>=6 | A<=3) = 0
A = 1×8
0 0 0 4 5 0 0 0

7 commentaires

Kamil Kacer
Kamil Kacer le 26 Déc 2022
Thank you but also how do I put zeros instead of numbers there are out of range ?
Karim
Karim le 26 Déc 2022
ah that is not a problem, i will adjust the answer
Kamil Kacer
Kamil Kacer le 26 Déc 2022
Thank you so much <3
Kamil Kacer
Kamil Kacer le 26 Déc 2022
Modifié(e) : Kamil Kacer le 26 Déc 2022
But it doesnt really work for my array c I tried this code but it gives me some weird matrix
cl{m} = c{m}(c{m}>=0.5 | c{m} <= 0.05) ==0;
c{m}(c{m}>=0.5 | c{m} <= 0.05) = 0;
Voss
Voss le 26 Déc 2022
Modifié(e) : Voss le 26 Déc 2022
cl{m} = c{m}(c{m}>=0.5 | c{m} <= 0.05) ==0;
That's not assigning elements of c{m} to 0; it's comparing certain elements of c{m} to 0, then storing the result (of class logical, i.e., true/false) in cl{m}.
That's a very different operation than what you asked about and got answers for.
DGM
DGM le 26 Déc 2022
Note that zero is also an out-of-range value, so filling the elements with zero doesn't solve the problem of limiting the range of the array.
When someone asks "I want to arbitrarily remove elements from an array" one has to ask what "remove" means, because it's not obvious. You can't just remove any element from an array and retain the shape of the array. If you want to fill the missing elements with some value, the value that you use depends entirely on your needs and the class of the array. So what exactly are your expectations?

Connectez-vous pour commenter.

Plus de réponses (1)

Torsten
Torsten le 26 Déc 2022
A = [1 2 3 4 5 6 7 8];
A(A<3) = 3;
A(A>6) = 6;
A
A = 1×8
3 3 3 4 5 6 6 6

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by