Subscript indices must either be real positive integers or logicals

The question was to Plot the functions y1(x) = 3+ exp(−x)sin(6x)and y2(x) = 4 + exp(−x)cos(6x) for 0 ≤ x ≤ 5 on a single axis using the hold command. Give the plot axis labels, a title, and a legend (y1, y2). I did
x=linspace(0,5,50);
hold on
y1(x)=@(x)3+exp(-x).*sin(6*x);
y2(x)=@(x)4+exp(-x).*cos(6*x);
y1=y1(x);
y2=y2(x)
plot(x,y1)
plot(x,y2)
hold off
title('Problem 1')
xlabel('x axis')
ylabel('y axis')
leg=legend('y1','y2');
grid on
The graph shows up, but there aren't any curves on there. And the error also says "Subscript indices must either be real positive integers or logicals.", did I do something wrong?

Risposte (2)

You didn’t write your anonymous functions correctly. I corrected them, and also renamed your plot variables so they would not conflict with your anonymous function names. Now, everything works:
x=linspace(0,5,50);
y1 = @(x) 3+exp(-x).*sin(6*x);
y2 = @(x) 4+exp(-x).*cos(6*x);
y1p = y1(x);
y2p = y2(x);
plot(x,y1p)
hold on
plot(x,y2p)
hold off
title('Problem 1')
xlabel('x axis')
ylabel('y axis')
leg=legend('y1','y2');
grid on

1 Commento

I would agree, except that James Huang’s original anonymous function syntax was incorrect, and that — rather than an actual array subscript reference problem — threw the error.

Accedi per commentare.

Richiesto:

il 28 Gen 2015

Commentato:

il 28 Gen 2015

Community Treasure Hunt

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

Start Hunting!

Translated by