calling a function in a loop
조회 수: 6 (최근 30일)
이전 댓글 표시
I am writing a program in MATLAB to solve for the efficiency of a diesel engine based off of it's cutoff ratio.
I also need to plot efficiency vs cutoff ratio for a varying cutoff ratio from 1.3 to 2.8.
T1, P1, and r are user input and cp and k are constants.
The error message I keep getting says that the index is invalid. "Array indices must be positive integers or logical values."
for rc = 1.3:0.01:2.8
[P2, N, qin, T3, T4, P3, P4, wnet] = part_1(P1, k, cp, rc, r, T1);
i = i + 1;
y(i, :) = rc
x1(:,i) = N
end
%Plots
plot(x1,y)
xlabel('Efficiency')
ylabel('Cutoff Ratio')
title('Efficiency vs Cutoff Ratio')
Here is my function:
function [P2, N, qin, T3, T4, P3, P4, wnet] = part_1(P1, k, cp, rc, r, T1)
N = 1 - (1/r^(k-1))*((rc^k-1)/(k*(rc-1)));
T2 = T1*r^(k-1);
P2 = P1*r^k;
P3 = P2;
T3 = T2*rc;
T4 = T3*(rc/r)^(k-1);
P4 = P2*T2*(1/r);
qin = cp*(T3-T2);
wnet = N*qin;
end
댓글 수: 2
Daniel M
2019년 11월 14일
Unless you have initialized the variable i somewhere unseen, i believe this to be a case where overwriting the imaginary number i() is causing an error. That's because the letter i (as well as j) are the names of functions. See for yourself by copying this into your command window:
clear all
open i
You should change all instances of i to something else, like ii. Your new error message should say "unrecognized function or variable ii".
답변 (1개)
David Hill
2019년 11월 14일
Easier without for-loop. I agree with the comment above, without setting i=0 (initially), I believe it was causing your problem.
function Efficiency(T1,P1,r)
rc = 1.3:0.01:2.8;
k= %whatever the constant is
cp= %whatever the constant is
N = 1 - (1/r^(k-1))*((rc.^k-1)./(k*(rc-1)));%vector
T2 = T1*r^(k-1);%scalor
P2 = P1*r^k;%scalor
P3 = P2;%scalor
T3 = T2*rc;%vector
T4 = T3.*(rc/r).^(k-1);%vector
P4 = P2*T2*(1/r);%scalor
qin = cp*(T3-T2);%vector
wnet = N.*qin;%vector
plot(N,rc)
xlabel('Efficiency')
ylabel('Cutoff Ratio')
title('Efficiency vs Cutoff Ratio')
end
댓글 수: 2
Rik
2019년 11월 14일
It is more efficient to aim for a vectorized solution. That is almost always faster, especially for larger amounts of data.
More on the topic of this issue: I always suggest to avoid i, j, o and l as variable names. The first two cause strange errors that can be hard to track down, and the latter two look too much like numbers.
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!