In this problem you will perform various tasks on a 1-by-n array V , whose eleme
ID: 3542767 • Letter: I
Question
In this problem you will perform various tasks on a 1-by-n array V, whose elements are either 1 or 0. For example, in Matlab:
begin code
For each of the following tasks test your code for many different values and lengths of V.
(a) Write code using a for loop that will flip every third entry of V (i.e. make the entry 0 if it is 1 or make it 1 if it is 0). This loop should modify V directly. For example V = [1, 1, 0, 1, 0, 1, 1, 0, 1] would become V = [1, 1, 1, 1, 0, 0, 1, 0, 0].
(b) Write code using a for loop that will flip every third instance of the number 1 in V. This loop should modify V directly. For example V = [1, 1, 0, 1, 0, 1, 1, 0, 1] would become V = [1, 1, 0, 0, 0, 1, 1, 0, 0].
(c) Write code using a for loop that will assign to the variable numChanges the number of times that successive elements of V change from 0 to 1 or from 1 to 0. For example if V = [0, 0, 1, 1] then numChanges would equal 1 and if V = [0, 1, 0, 1] thennumChanges would equal 3.
(d) Write code using a for loop that assigns to a variable numOccurs the number of times a certain pattern of 0
Explanation / Answer
%define the matrix
V = [1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1];
%flip every 3rd elemnent
for i=3:3:length(V)
if V(i) == 1
V(i) = 0;
else
V(i) = 1;
end
end
%count number of changes
numChanges = 0;
for i=1:length(V)-1
if(V(i) ~= V(i+1))
numChanges = numChanges + 1;
end
end
%count occurences of pattern
pattern = [1 0 0 0 1];
flag = true;
numOccurs = 0;
for i=1:length(V)-length(pattern)+1
flag = true;
for j=1:length(pattern)
if V(i+j-1) ~= pattern(j)
flag = false;
break;
end
end
if flag == true
numOccurs = numOccurs + 1;
end
end
%calculate the separated pattern occurences
numOccursSep = 0;
i = 1;
while i <= length(V)-length(pattern)+1
flag = true;
for j=1:length(pattern)
if V(i+j-1) ~= pattern(j)
flag = false;
break;
end
end
if flag == true
numOccursSep = numOccursSep + 1;
i = i + length(pattern);
else
i = i+1;
end
end
%define seqRemove and seqNew
seqRemove = [1 0 1];
seqNew = [0 1 1];
i = 1;
while i <= length(V)-length(seqRemove)+1
flag = true;
for j=1:length(seqRemove)
if V(i+j-1) ~= seqRemove(j)
flag = false;
break;
end
end
if flag == true
for j =1:length(seqRemove)
V(i+j-1) = seqNew(j);
end
i = i + length(pattern);
else
i = i+1;
end
end
display(V);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.