0
0
MATLABdata~10 mins

Vectorization vs loops in MATLAB - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a vector of squares using vectorization.

MATLAB
x = 1:5;
y = x[1]2;
Drag options to blanks, or click blank then click option'
A.^
B^
C*
D.*
Attempts:
3 left
💡 Hint
Common Mistakes
Using ^ instead of .^ causes an error because ^ is matrix power.
Using * or .* does multiplication, not power.
2fill in blank
medium

Complete the code to sum all elements of vector a using a loop.

MATLAB
a = [1, 2, 3, 4, 5];
sum_val = 0;
for i = 1:length(a)
    sum_val = sum_val [1] a(i);
end
Drag options to blanks, or click blank then click option'
A+
B-
C*
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using - subtracts elements instead of adding.
Using * or / does multiplication or division, which is incorrect here.
3fill in blank
hard

Fix the error in the loop that multiplies each element by 2 and stores in b.

MATLAB
a = [1, 2, 3];
b = zeros(size(a));
for i = 1:length(a)
    b(i) = a[1] 2;
end
Drag options to blanks, or click blank then click option'
A.^
B.*
C^
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using .* causes an error because a is scalar inside the loop.
Using ^ or .^ is for power, not multiplication.
4fill in blank
hard

Fill both blanks to create a vector c with elements doubled using vectorization and then sum them.

MATLAB
a = [1, 2, 3, 4];
c = a[1] 2;
total = sum(c[2]);
Drag options to blanks, or click blank then click option'
A.*
B()
C[]
D+
Attempts:
3 left
💡 Hint
Common Mistakes
Using * instead of .* causes error for vectors.
Using square brackets [] instead of parentheses for function calls.
5fill in blank
hard

Fill all three blanks to create a vector of squares using vectorization, then filter values greater than 10.

MATLAB
x = 1:6;
y = x[1] 2;
z = y(y [2] 10);
result = z[3];
Drag options to blanks, or click blank then click option'
A.^
B>
C'
D.+
Attempts:
3 left
💡 Hint
Common Mistakes
Using ^ instead of .^ causes matrix power error.
Using < or <= instead of > changes the filter condition.
Forgetting to transpose if needed for output shape.