필터 지우기
필터 지우기

How to make the for loop the length as the array inside the for loop?

조회 수: 2 (최근 30일)
Matthew
Matthew 2023년 10월 10일
댓글: Star Strider 2023년 10월 10일
I am making a for loop and I want to subtract each element by each other. I was able to do this but my array is now 1x200 and my original array was 1x201. How do I make it so the for loop array is 1x201?
x1 = [1e6:20000:5e6];
L = 4e6; % in m
D_c = 5000;% in m
D1 = [0:25:5000];
x_o = 1e6; % in m
x_2 = [x_o:20000:5e6];
Tw_o = 300; % in K
LR_w = 0.004; % in K/m
LR_c = -0.007; % in K/m
pz_0 = 1000; % in mb
D_1 = D_c.*(sin((pi/L).*(x1-x_o)));
T_c2 = Tw_o-(((LR_w-LR_c).*D_1)-((LR_c.*D1)));
g = 9.81;
Rd = 287;
p1 = pz_0*(((((T_c2)-(LR_c.*D1))./(T_c2))).^((g)/(Rd*LR_c)));
for i = 1:length(p1)-1
deltap(i) = p1(i+1)-p1(i);
end

답변 (1개)

Star Strider
Star Strider 2023년 10월 10일
You do not need the loop at all. Just use the diff function —
x1 = [1e6:20000:5e6];
L = 4e6; % in m
D_c = 5000;% in m
D1 = [0:25:5000];
x_o = 1e6; % in m
x_2 = [x_o:20000:5e6];
Tw_o = 300; % in K
LR_w = 0.004; % in K/m
LR_c = -0.007; % in K/m
pz_0 = 1000; % in mb
D_1 = D_c.*(sin((pi/L).*(x1-x_o)));
T_c2 = Tw_o-(((LR_w-LR_c).*D_1)-((LR_c.*D1)));
g = 9.81;
Rd = 287;
p1 = pz_0*(((((T_c2)-(LR_c.*D1))./(T_c2))).^((g)/(Rd*LR_c)));
deltap = diff(p1)
deltap = 1×200
-2.8534 -2.8634 -2.8734 -2.8835 -2.8935 -2.9036 -2.9136 -2.9237 -2.9337 -2.9437 -2.9536 -2.9635 -2.9733 -2.9831 -2.9927 -3.0023 -3.0118 -3.0212 -3.0305 -3.0396 -3.0486 -3.0574 -3.0661 -3.0746 -3.0830 -3.0911 -3.0990 -3.1068 -3.1143 -3.1215
for i = 1:length(p1)-1
deltap(i) = p1(i+1)-p1(i);
end
deltap
deltap = 1×200
-2.8534 -2.8634 -2.8734 -2.8835 -2.8935 -2.9036 -2.9136 -2.9237 -2.9337 -2.9437 -2.9536 -2.9635 -2.9733 -2.9831 -2.9927 -3.0023 -3.0118 -3.0212 -3.0305 -3.0396 -3.0486 -3.0574 -3.0661 -3.0746 -3.0830 -3.0911 -3.0990 -3.1068 -3.1143 -3.1215
If you want to calculate the numerical derivative at eash point instead, use the gradient function —
deltap = gradient(p1)
deltap = 1×201
-2.8534 -2.8584 -2.8684 -2.8784 -2.8885 -2.8985 -2.9086 -2.9186 -2.9287 -2.9387 -2.9486 -2.9585 -2.9684 -2.9782 -2.9879 -2.9975 -3.0071 -3.0165 -3.0258 -3.0350 -3.0441 -3.0530 -3.0618 -3.0704 -3.0788 -3.0870 -3.0951 -3.1029 -3.1105 -3.1179
.
  댓글 수: 2
Matthew
Matthew 2023년 10월 10일
Is there a way to get these values positive instead of negative? Thanks.
Star Strider
Star Strider 2023년 10월 10일
One way would be to take the absolute value (the abs function), the other, since they are uniformly negative, would be to multiply them by -1 or just use a unary negative:
deltap = -gradient(p1)
Use whatever works best in your application.
.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by