Reputation: 11
Essentially what I am trying to do is to get my for loop to run for iterations when n = 4,8,16,32,...,512. I tried earlier multiplying my the iteration variable within the for loop but MatLab wouldn't allow it. I tried searching for generating an exponentially spaced vector to use but there was no command. It seems like a pretty simple task, I could use a conditional statement before it but that seems like bad coding.
Is there a simple and elegant way to setup my loop conditons?
%% Analysis - Trapezoidal Rule
for n = 4:k:512
h = (b-a)/n;
changing_a = a+h;
for j = 1:n-1
sum = function_q4_a(changing_a);
changing_a = changing_a + h;
end
integral_value = ((b-a)/(2*n)) * (function_q4_a(a) + 2*sum + function_q4_a(changing_a));
disp('Current n = ');
disp(n);
disp('Integral value is: ');
disp(integral_value);
k = k*2;end
Upvotes: 1
Views: 73
Reputation: 583
You can simply do something like
for n = 2.^(2:9)
% Some code here
end
To be more precise,
2.^(2:9)
builds a vector [2^2, 2^3, 2^4, 2^5, 2^6, 2^7, 2^8, 2^9] - using the .^ element-wise operator - and then you just iterate over the values of this vector.
Upvotes: 4