using trapz in a for loop

7 views (last 30 days)
gabriella biggs
gabriella biggs on 7 Dec 2022
Edited: Voss on 7 Dec 2022
I am trying to use trapz in a for loop to compute an integral with multiple bounds.
This is the code I'm trying to use:
clear;clc
mu=1.837e-5; %dynamic viscosity, Pa*s
nu=1.552e-5; %kinetmatic viscosity, m^2/s
input=readmatrix('ProjectPartCTestInput.txt');
s=input(:,1);
ue=input(:,2);
n=100;
ue6=ue.^6;
for i=1:length(n)
int=trapz(s(1:i),ue(1:i));
%delta22(i)=(0.45*nu*int)/ue6; %delta2^2
%delta2(i)=sqrt(delta22); %delta2
end
And this is the error I keep getting:
Error using permute
ORDER contains an invalid permutation index.
Error in trapz (line 51)
y = permute(y,perm);
Error in Untitled (line 14)
int=trapz(s(1:i),ue(1:i));
Any suggestions?

Answers (3)

Star Strider
Star Strider on 7 Dec 2022
The problem:
for i=1:length(n)
This returns 1 since ‘n’ is a scalar.
You probably intend:
for i=1:n
however that is still incorrect.
This:
int=trapz(s(1:n),ue(1:n));
without the loop will likely work.
If you want to partition ‘s’ and ‘ue’ into 100-element columns, consider using reshape and iterate to integrate over the columns.
.

Voss
Voss on 7 Dec 2022
Edited: Voss on 7 Dec 2022
When you call trapz with two arguments and the second argument is a scalar (like what happens in your loop when i == 1), then trapz treats the second argument as the dimension argument (which is usually the third input argument). In your case, presumably ue(1) is a value that's not a valid dimension, such as 0, and that causes the error.
To avoid this error, explicitly state the dimension argument (in this case it's 1 since s and ue are column vectors):
int=trapz(s(1:i),ue(1:i),1);
% ^^ explicitly include dimension argument

Walter Roberson
Walter Roberson on 7 Dec 2022
int=trapz(s(1:i),ue(1:i));
when i is 1, that would be trapz(scalar,scalar) . But when you trapz() and the second parameter is a scalar, the second parameter is interpreted as being a dimension index.
That is, the syntax that the help summarizes as
trapz(Y,DIM)
has priority over the syntax summarized over
trapz(X,Y)
in the case that Y is a scalar.
Note: trapz() with a scalar Y always gives a result of 0. trapz() requires at least two points to give a non-zero result.

Products

Community Treasure Hunt

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

Start Hunting!