MATLAB Answers

D M
0

calling a function in a loop

Asked by D M
on 14 Nov 2019 at 0:35
Latest activity Commented on by Rik
on 14 Nov 2019 at 6:57
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 Comments

Daniel M
on 14 Nov 2019 at 0:41
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
on 14 Nov 2019 at 2:52
Thank you, setting i = 0 seems to have fixed my code

Sign in to comment.

Products

1 Answer

Answer by David Hill on 14 Nov 2019 at 2:02

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 Comments

D M
on 14 Nov 2019 at 2:51
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
on 14 Nov 2019 at 6:57
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.

Sign in to comment.