Given the following matrix: A=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] Create a
ID: 3670867 • Letter: G
Question
Given the following matrix:
A=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
Create a for loop that will square every term in A and accumulate it in a vector called “squares”
Create a for loop that will extract every odd element from “squares” and store it in a vector called “odds”. Display the odds array. Hints: (1) change the step size of the for loop; (2) use the for loop iterator to extract elements of “squares”; (3) assign values to odds using a new/different index; (4) initialize this new index to 1 above the loop; and increase this new index by 1 each time through the loop, e.g., newIndex = newIndex + 1; %inside the loop
Explanation / Answer
A=[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
for i = 1:length(A)
squares(i) = A(i)^2;
end
%disp(squares);
newIndex =1
for i = 1:2:length(A) %for loop with a step increment of 2
odds(newIndex) = squares(i); %extracts only odd elements
newIndex = newIndex+1; %incrementing odds index
end
disp(odds);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.