## Explanation of question on (past) test, but do not understand please help

Asked by Tanner Schmitt

### Tanner Schmitt (view profile)

on 14 May 2019
Latest activity Answered by Raj

### Raj (view profile)

on 14 May 2019
Accepted Answer by Raj

### Raj (view profile)

Hello there, so I am having some trouble understanding this exam question I had on my most recent exam. The question asks us to determine what the matrix "v" will store after follwing the MATLAB code executed (this is handwritten). The code is:
clear
clc
v=[-9 3 2 10 4 -12 14 -1];
t=2;
b=-4;
for i=2:2:7
if v(i)>t
v(i) = 1;
elseif v(i)<b
v(i)=10;
else
v(i)=2;
end
end
disp (v)
After the test, I just wanted to see what the answer was, and it displays:
-9 1 2 1 4 10 14 -1
Would someone mind explaining the process of how this answer was reached? Any help is greatly appreciated

### Raj (view profile)

on 14 May 2019

Its quite straightforward. See the array 'v' elementwise like this:
v=[-9 3 2 10 4 -12 14 -1];
1) First element is -9. The for loop starts with index 2 so there should be no change in first element.
2) Second element is 3. As per the for loop since the element is >t (i.e. greater than 2), you change the element to 1. Thus second element becomes 1.
3) Third element is 2. However the for loop increment order is 2 (start at 2 then 4 then 6). so execution will not enter the for loop. So no change in element and it stays as 2.
4) Fourth element is 10. As per for loop, since it is >t (i.e. greater than 2), you change the element to 1. Thus fourth element becomes 1.
5) Fifth element is 4. Again the for loop increment order is 2. so execution will not enter the for loop. So no change in element and it stays as 4.
6) Sixth element is -12. Elexution will skip the first if condition as it is not getting satisfied. The elseif condition is getting satisfied as -12<b which is -4. So you change the element to 10.
7) Seventh element is 14. Now the for loop last index is 7 but since the increment step is 2 the for loop stops at i=6. So no change in the element and it stays as 14.
8) Eighth and last element is -1 which stays as it is.
so you get your final v=[-9 1 2 1 4 10 14 -1]
Hope this explanation helps!