Asked by D M
on 14 Nov 2019 at 0:35

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

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

D M
on 14 Nov 2019 at 2:51

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.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Daniel M (view profile)

## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/490981-calling-a-function-in-a-loop#comment_767093

## D M (view profile)

## Direct link to this comment

https://de.mathworks.com/matlabcentral/answers/490981-calling-a-function-in-a-loop#comment_767110

Sign in to comment.