using trapz in a for loop

9 ビュー (過去 30 日間)
gabriella biggs
gabriella biggs 2022 年 12 月 7 日
編集済み: Voss 2022 年 12 月 7 日
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?

回答 (3 件)

Star Strider
Star Strider 2022 年 12 月 7 日
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 2022 年 12 月 7 日
編集済み: Voss 2022 年 12 月 7 日
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 2022 年 12 月 7 日
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.

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by