Find the number of scalar multiplications in this code x 10
Find the number of scalar multiplications in this code. x = 1:0.5:n; x = 3 * x; for k = 2:length(x) x(2:k) = x(2:k) * x(1:k-1); end
Solution
x=1:0.5:n
This means x=[1.0 1.5 2.0 .....n]
So there will be 2n-1 elements in x
x=3*x
This means every elements in x is multiplied by 3
So there will be 2n-1 scalar multiplications -------- A
for k=2:length(x)
x(2:k)=x(2:x).*x(1:k-1)
end
length(x) is 2n-1
so k goes from 2 to 2n-1
length of x(2:k) goes from 1 to 2n-2
Therefore there are k-1 multiplications in each step
Number of scalar multiplications = 1 + 2 + ....+ 2n-2 = (2n-2)*(2n-2+1)/2 = (n-1)*(2n-1) --------- B
From A and B
total number of scalar multiplications= 2n-1 + (n-1)*(2n-1) = n*(2n-1)
