do anyone know how to put all iteration of a for loop into a matrix?

1 view (last 30 days)
as the title said, this is what i have:
clear all
clc
a=0; b=8;
n=2;
run=input('Input your number of iteration:');
i=(1:run);
for ii=1:length(i)
n=2*n;
h=(b-a)./n;
fprintf('n= %4.0f and h= %5.3f\n',n, h)
integral = 0;
si=(1:h:b);
for i = 1:length(si)-1
x_left=a+(i-1)*h; x_right=a+i*h;
x_half=(x_left+x_right)/2.0;
f_half=0.0041.*(x_half.^6)-0.1383.*(x_half.^5)+1.6963.*(x_half.^4)-8.915.*(x_half.^3)+13.961.*(x_half.^2)+40.96.*(x_half);
integral=integral+f_half*h;
end
fprintf('The distance travel is %5.5f miles\n', integral)

Accepted Answer

Stephan
Stephan on 23 Oct 2019
Edited: Stephan on 23 Oct 2019
clear all
clc
a=0; b=8;
n=2;
run=input('Input your number of iteration:');
i=(1:run);
integral_matrix = zeros(numel(i),1);
for ii=1:length(i)
n=2*n;
h=(b-a)./n;
fprintf('n= %4.0f and h= %5.3f\n',n, h)
integral = 0;
si=(1:h:b);
for i = 1:length(si)-1
x_left=a+(i-1)*h; x_right=a+i*h;
x_half=(x_left+x_right)/2.0;
f_half=0.0041.*(x_half.^6)-0.1383.*(x_half.^5)+1.6963.*(x_half.^4)-8.915.*(x_half.^3)+13.961.*(x_half.^2)+40.96.*(x_half);
integral=integral+f_half*h;
integral_matrix(ii) = integral;
end
fprintf('The distance travel is %5.5f miles\n', integral)
end
fprintf('\nMatrix:\n\n')
fprintf('%5.5f\n', integral_matrix)
results in:
Input your number of iteration:5
n= 4 and h= 2.000
The distance travel is 587.37380 miles
n= 8 and h= 1.000
The distance travel is 722.49008 miles
n= 16 and h= 0.500
The distance travel is 721.35683 miles
n= 32 and h= 0.250
The distance travel is 721.08343 miles
n= 64 and h= 0.125
The distance travel is 721.01571 miles
Matrix:
587.37380
722.49008
721.35683
721.08343
721.01571

More Answers (0)

Categories

Find more on Get Started with MATLAB 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!