In: Computer Science
MATLAB PROBLEM
convert the for loop to a while loop.
vec= [1 2 3 4 5]
newVec= []
for i=vec
if i>5
new vec=[newvec, i]
end
end
end
vec= [1 2 3 4 5] %vector
newVec= [] % initialize new vector 'newVec'
for i=vec % i will contain value of vector 'vec' for each iteration
if i>5 % check if value of vector 'vec' is greater than 5 (>5) or not.
new vec=[newvec, i] %if yes, then push that value in the new vector 'newVec'.
end % end of if condition.
end % end of for loop
After Convertion into While Loop
vec= [1 2 3 4 5] %vector
newVec=
[]
% initialize new vector 'newVec'
n=size(vec)(2) % size of
vec
i=1
% initialize the i=1 for iteration
while
i<=n
%while loop will run until i<=n
if(vec(i)>5) % check if value of vector 'vec' is greater than 5 (>5) or not.
newVec=[newVec,vec(i)] % %if yes, then push that value in the new vector 'newVec'.
end
%end of if condition
i=i+1
% increment the value of i.
end % end of for condition
newVec % print the values of new vector
Note: newVec will be empty as no value of vector 'vec' is greater than 5.