Fixing Error using plot Invalid first data argument - new to matlab

85 views (last 30 days)
I am trying to plot the function y=cos(x)*sin(x^2) and its derivative from -pi to pi. Here is my code. Why do I keep getting errors? At first I tried linespace but that didn't work. What do I do? I am new to matlab.
x=-pi:100:pi;
y=cos(x)*sin(x^2);
dy=2*x*cos(x^2)*(cos(x))-sin(x^2)*sin(x);
clf
hold on
plot(x,y, 'r', 'LineWidth', 3);
xlabel('x');
ylabel('y');
hold on
grid on
plot(x,dy, 'b', 'o--', 'LineWidth', 1);
title(['Graph of y=sin(x^2)cos(x) and y' by Jay Gersten'])
legend('cos(x)*sin(x.^2)','2*x*cos(x.^2)*cos(x)-sin(x.^2)*sin(x)')
dbstop if error

Accepted Answer

Star Strider
Star Strider on 9 Oct 2015
Edited: Star Strider on 9 Oct 2015
The first problem was how you defined ‘x’. The colon operator began with -pi, then incremented by 100, and since that was greater than +pi, stopped with only one value for ‘x’, that being -pi. I don’t know what you had problems with in your linspace call, but the one I used seems to work.
The second is that you need to vectorise your functions. See Array vs. Matrix Operations for details.
Third, you need to combine the line type and colour designations in your plot calls, so I corrected that in your second plot call.
And last, you had a glitch in your title call that I corrected substituting an acute accent char(188) for a single quote that MATLAB uses to define the ends of strings. Substitute something else if you wish, just so long as it’s not a single quote (').
This works:
x = linspace(-pi, pi, 100);
y=cos(x).*sin(x.^2);
dy=2*x.*cos(x.^2).*(cos(x))-sin(x.^2).*sin(x);
% clf
hold on
plot(x,y, 'r', 'LineWidth', 3);
xlabel('x');
ylabel('y');
hold on
grid on
plot(x,dy, 'o--b', 'LineWidth', 1);
title(['Graph of y=sin(x^2)cos(x) and y´ by Jay Gersten'])
legend('cos(x)*sin(x.^2)','2*x*cos(x.^2)*cos(x)-sin(x.^2)*sin(x)')

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!