I am trying to plot this piecewise function using for loop and if statements, yet I keep receiving error message: Array indices must be positive integers or logical values.

14 views (last 30 days)
g = 0:0.1:5;
C(g) = 0*g;
for i = 1:length(g)
if g(i) < 2 && g(i) >= 0
C(g) = 25;
else g(i) >= 2
C(g) = 25 + 10*(g-2);
end
end
subplot(2,1,1)
plot(g,C(g),'b.-','Markersize', 12)
xlabel(' Cellphone Data Gigbytes [GB]')
ylabel(' Monthly Cost ')
title(' Monthly Cost for Cellphone Data usage ')
grid on
Array indices must be positive integers or logical values.

Answers (1)

Paul
Paul on 17 Jul 2022
Hi Errol,
The error message shows up because the code uses g as a subscript into C, and g takes on non-integer values. But g is is used to be determine the value of each element of C; g is not a subscript. In the corrected code below, C is subscripted with i were appropiate and not subscripted at all where appropriate. Also, the else statement didn't seem correct, so it's modified in the code below to reflect what I thought is the intent.
Note that the code could be much simplified by using logical indexing instead of the for loop and if statement.
g = 0:0.1:5;
%C(g) = 0*g;
C = 0*g;
for i = 1:length(g)
if g(i) < 2 && g(i) >= 0
% C(g) = 25;
C(i) = 25;
else % g(i) >= 2
% C(g) = 25 + 10*(g-2);
C(i) = 25 + 10*(g(i)-2);
end
end
subplot(2,1,1)
%plot(g,C(g),'b.-','Markersize', 12)
plot(g,C,'b.-','Markersize', 12)
xlabel(' Cellphone Data Gigbytes [GB]')
ylabel(' Monthly Cost ')
title(' Monthly Cost for Cellphone Data usage ')
grid on
  1 Comment
Walter Roberson
Walter Roberson on 17 Jul 2022
When you write f(x) = something then generally speaking, there are two possibilities:
  • you might be mentally defining a formula named f that relates a value temporarily named x to an outcome that depends on the input value; or,
  • you might be indexing an array named f at the specific values stored in x and assigning something to those locations
In MATLAB, assignments like that always mean indexing, except for the case where x evaluates to a symbolic variable (or vector of symbolic variables). In the case where x evaluates to symbolic variable(s), then you are defining a formula.
In your original code, at any one time, g is a specific numeric value, and in that case, c(g) = something is invoking indexing, not creating a formula. And indexing has to be at positive integers or at logical values.
Paul shows how to transform to indexing.
The symbolic case, defining a formula, would use piecewise()

Sign in to comment.

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!