Complete the code to create a vector of squares using vectorization.
x = 1:5; y = x[1]2;
In MATLAB, the element-wise power operator is .^. It raises each element of x to the power 2.
Complete the code to sum all elements of vector a using a loop.
a = [1, 2, 3, 4, 5]; sum_val = 0; for i = 1:length(a) sum_val = sum_val [1] a(i); end
To accumulate the sum, add each element to sum_val using the + operator.
Fix the error in the loop that multiplies each element by 2 and stores in b.
a = [1, 2, 3]; b = zeros(size(a)); for i = 1:length(a) b(i) = a[1] 2; end
.* causes an error because a is scalar inside the loop.^ or .^ is for power, not multiplication.Inside a loop, * is used for scalar multiplication. The dot operator is not needed here.
Fill both blanks to create a vector c with elements doubled using vectorization and then sum them.
a = [1, 2, 3, 4]; c = a[1] 2; total = sum(c[2]);
* instead of .* causes error for vectors.[] instead of parentheses for function calls.Use .* for element-wise multiplication and () to call the sum function.
Fill all three blanks to create a vector of squares using vectorization, then filter values greater than 10.
x = 1:6; y = x[1] 2; z = y(y [2] 10); result = z[3];
Use .^ for element-wise power, > to filter values greater than 10, and ' to transpose the result.