Majid
Majid

Reputation: 491

MATLAB, how to solve Index exceeds the number of array elements (1)?

Why I can't plot the following code? The error is:

Index exceeds the number of array elements (1).

What I'm trying to achive is that a user enters a scalar value f (such as 1500) anf Ht and Hr. So, I want to find value of ahr and L accondingliy and then plot L vs f. SO on f axis I shoud have 100,150,200,250,300,....,1500 and corrsponding values on L axis.

for i = 100:50:f
        cm = 0;
        ahr(i) = (1.1*log10(f(i))-0.7)*Hr-1.56*log10(f(i))-0.8;
        L(i) = 46.3+33.9*log10(f(i))-13.82*log10(Ht)-ahr+(44.9-6.55*log10(Hr))*log10(d)+cm;
        plot(f,L)
end

Upvotes: 0

Views: 1167

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4757

Using Vectorized Approach to Evaluate Plots

Assuming d, Ht and Hr are scalars the following code should work. This script uses a vectorized approach where f is a vector that is used to evaluate the equations ahr and L. The equations ahr and L will now be evaluated for every element in f resulting in the ahr and L being the same length as f. This method eliminates the need for a for-loop and works with MATLAB's strengths/capabilities.

Command Window: User Inputs

Plot L vs f Vectorized Approach

%Asking user for input values%
fmax = input("Please type in the maximum f: ");
Ht = input("Please type in the value of Ht: ");
Hr = input("Please type in the value of Hr: ");
cm = 0;
d = 1;

%Creating the vector of points to plot on%
f = (100:50:fmax);

ahr = (1.1*log10(f)-0.7)*Hr-1.56*log10(f) - 0.8;
L = 46.3 + 33.9*log10(f)-13.82*log10(Ht)-ahr+(44.9-6.55*log10(Hr))*log10(d);

clf;
plot(f,L,'Marker','.');
title("Plot L vs f");
xlabel("f"); ylabel("L");
xticks(f);
grid;

Ran using MATLAB 2019b

Upvotes: 1

Related Questions