Change the zeros to ones and the ones to zeros.

조회 수: 100 (최근 30일)
Julen Vicente Pipaon
Julen Vicente Pipaon 2021년 2월 25일
편집: emjey 2023년 1월 10일
I don´t know why my code to change the ones for zeros and the zeros to ones doesn´t work.
This is my code:
V = [ 1, 1, 1, 1, 0, 1, 0, 1]
V(V==0) = 1;
V(V==1) = 0;
C1 = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, V(2:8)]

채택된 답변

Steven Lord
Steven Lord 2021년 2월 25일
Let's look at V after the second and third steps:
V = [ 1, 1, 1, 1, 0, 1, 0, 1]
V = 1×8
1 1 1 1 0 1 0 1
V(V==0) = 1
V = 1×8
1 1 1 1 1 1 1 1
V(V==1) = 0
V = 1×8
0 0 0 0 0 0 0 0
You want to record which elements of V were equal to 1 before replacing all the 0 values with 1.
V = [ 1, 1, 1, 1, 0, 1, 0, 1];
previousOnes = V == 1;
V(V == 0) = 1;
V(previousOnes) = 0
V = 1×8
0 0 0 0 1 0 1 0
Or since you want to change 0 to 1 and vice versa, just subtract V from 1.
V = [ 1, 1, 1, 1, 0, 1, 0, 1];
newV = 1-V
newV = 1×8
0 0 0 0 1 0 1 0
Or use the not operator. Depending on what you want to do with it afterward you may need to convert it back to double by calling double() on it.
V = [ 1, 1, 1, 1, 0, 1, 0, 1]
V = 1×8
1 1 1 1 0 1 0 1
newV2 = ~V
newV2 = 1x8 logical array
0 0 0 0 1 0 1 0
newV2D = double(newV2)
newV2D = 1×8
0 0 0 0 1 0 1 0

추가 답변 (1개)

emjey
emjey 2023년 1월 6일
편집: emjey 2023년 1월 10일
you can do it in one line like this
>> V = [ 1, 1, 1, 1, 0, 1, 0, 1];
>> abs(V-1)
ans =
0 0 0 0 1 0 1 0

카테고리

Help CenterFile Exchange에서 Migrate GUIDE Apps에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by