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

65 次查看(过去 30 天)
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

采纳的回答

Star Strider
Star Strider 2015-10-9
编辑:Star Strider 2015-10-9
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)')

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by