include a for loop instead of x=a:h:b (h=step size)?

12 views (last 30 days)
a=1;
b=2;
n=10;
h=(b-a)/n;
x=a:h:b;
y=x.^3;
ya=a.^3;
yb=b.^3;
area = h/2*(ya+yb+2*(sum(y)-ya-yb));
disp(area)
end
I wrote this code to solve an integral with the trapezium rule. We are suposed to use the for loop but i came up with the x=a:h:b idea. the answer is correct but i'm interested on how would the for loop be used here. Thanks in advance.

Answers (1)

Walter Roberson
Walter Roberson on 29 May 2015
When you have a vector X and you want to run a for loop over the values, then
xvals = a:h:b; %create a vector of the values to be processed
for K = 1 : length(xvals) %loop over indices
x = xvals(K); %pick out the one of interest now
.... do whatever with it
result(K) = .... %store the result
end

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!