Effacer les filtres
Effacer les filtres

loop matrix to new matrix

1 vue (au cours des 30 derniers jours)
Emilia
Emilia le 24 Juil 2022
Commenté : Voss le 24 Juil 2022
Hello,
I am given a matrix A, I want to make a conditional loop if a number is over 30 then place 1 in a new matrix, if a value is less than 30 place 0. How do this.
I would appreciate help fixing my code.
Thank
A=[60 56 44 44 22 18 22 18; 60 56 44 40 8 8 8 8;56 44 12 12 8 4 8 12];
switch C
case C>30
C(x,y)=1
case C<=30
C(x,y)=0
end
I need to get a new binary matrix, like this answer
A_new=[1 1 1 1 0 0 0 0;1 1 1 1 0 0 0 0;1 1 0 0 0 0 0 0]

Réponse acceptée

Voss
Voss le 24 Juil 2022
A=[60 56 44 44 22 18 22 18; 60 56 44 40 8 8 8 8;56 44 12 12 8 4 8 12];
Here's one way to write the loop you want:
% initialize A_new to a matrix of zeros the same size as A
A_new = zeros(size(A));
for ii = 1:numel(A)
% if the ii-th element of A is greater than 30, then set the
% ii-th element of A_new to 1.
% (otherwise A_new(ii) is already 0 so there's nothing to do)
if A(ii) > 30
A_new(ii) = 1;
end
end
A_new
A_new = 3×8
1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0
However, you don't need a loop at all; you can merely perform the comparison on the entire matrix A at once:
A_new = A > 30
A_new = 3×8 logical array
1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0
And if you really need zeros and ones of class 'double' rather than falses and trues of class 'logical':
A_new = double(A > 30)
A_new = 3×8
1 1 1 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0 0 0 0 0 0
  2 commentaires
Emilia
Emilia le 24 Juil 2022
Thank you!
Voss
Voss le 24 Juil 2022
You're welcome!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by