calling a function in a loop

조회 수: 6 (최근 30일)
D M
D M 2019년 11월 14일
댓글: Rik 2019년 11월 14일
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
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".
D M
D M 2019년 11월 14일
Thank you, setting i = 0 seems to have fixed my code

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

답변 (1개)

David Hill
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
D M
D M 2019년 11월 14일
Thank you that is very helpful, not setting i = 0 was my initial problem. I did not include the entire project, but it will be easier for me to write a for loop in the long run.
Rik
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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by