Write a function that takes in a number, n. as an input and has one output, an a
ID: 3921965 • Letter: W
Question
Write a function that takes in a number, n. as an input and has one output, an array of length n that alternates 1's and 0's. If the length of the array is odd, start the array with a I If the length of the array is even, start the array with 0. Please use a loop to accomplish this For example: [alternating] = aaalllRecitation5Problem3(10) Would return the array: alternating = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] While [alternating] = aaalllRecitation5Problem3(11) Would return the array alternating = [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] You can use the mod function to determine whether a number is even or odd mod(n, 2) will return I if n is odd and 0 if n is even.Explanation / Answer
% matlab code implementing aaalllRecitation5Problem3 function
function alternating = aaalllRecitation5Problem3(n)
if mod(n,2) == 0
alternating(1) =0;
else
alternating(1) = 1;
end
for i=2:n
if alternating(i-1) == 0
alternating(i) = 1
else
alternating(i) = 0
end
end
end
number = input("Enter a number: ");
alt = aaalllRecitation5Problem3(number);
disp(alt);
% output:
% Enter a number: 11
% 1 0 1 0 1 0 1 0 1 0 1
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.