In: Computer Science
Mathlab
Q1. Instruction Text
% For loop code:
vec = [45, -1, 7, 0, -37, 4, -3];
newvec = zeros(1,numel(vec)); % pre-allocate newvec with zeros
for idx = 1:numel(vec)
if vec(idx) > 1 & vec(idx) < 0
numerator = 3*vec(idx)^3;
denominator = 9*vec(idx)^2 + 3;
else
numerator = 2*vec(idx)^3 - 2*vec(idx);
denominator = 2*vec(idx)^2 - 2/vec(idx);
end
newvec(idx) = numerator/denominator;
end
clc;
vec = [45, -1, 7, 0, -37, 4, -3]; %Initialize vector with values
newvec = zeros(1,numel(vec)); % pre-allocate newvec with zeros
% For loop code:
for idx = 1:numel(vec) %iterate through each value in vec
if vec(idx) > 1 & vec(idx) < 0
numerator = 3*vec(idx)^3;
denominator = 9*vec(idx)^2 + 3;
else
numerator = 2*vec(idx)^3 - 2*vec(idx);
denominator = 2*vec(idx)^2 - 2/vec(idx);
end
newvec(idx) = numerator/denominator;
end