MATLAB Answers

I'm trying to plot my function into a graph but it won't even run

조회 수: 3(최근 30일)
So here's my code:
function y= displacement(theta)
if theta >=0 && theta <= pi/2
y=6*(2*theta-0.5*sin(theta));
elseif theta >= pi/2 && theta <= 2*pi/3
y=6;
elseif theta >= 2*pi/3 && theta <= 4*pi/3
y=6-3*abs(1-0.5*cos(3*theta-2*pi));
elseif theta >= 4*pi/3 && theta <= 3*pi/2
y=3;
elseif theta >= 3*pi/2 && theta <= 7*pi/4
y=3-1.5*((theta-3*pi)/(pi/4))^2;
elseif theta >= 7*pi/4 && theta <= 2*pi
y=0.75-0.75*(1-((theta-(7*pi/4))/(pi/4)))^2;
end
theta=linespace(0,2*pi,500);
y=displacement(theta);
plot(theta,y,'r','Linewidth',2)
grid on;
legend({'displacement(theta)'},'fontsize',10)
xlabel('Theta (radians)','fontsize',10)
ylabel('Displacement','fontsize',10)
title('Piecwise functions','fontsize',10)
I was trying to plot a graph that follows these guidlens but I'm not even able to run anything. And then I get an error in my function saying how "the vaule assigned to variable "y" might be unused. I honestly don't know what I'm doing wrong. Please guide me.

채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 15 Mar 2021
편집: KALYAN ACHARJYA 15 Mar 2021
function y=displacement(theta)
y=zeros(1,length(theta));
for i=1:length(theta)
if theta(i)>=0 & theta(i)<= pi/2
y(i)=6*(2*theta(i)-0.5*sin(theta(i)));
elseif theta(i)>= pi/2 & theta(i)<= 2*pi/3
y(i)=6;
elseif theta(i)>= 2*pi/3 & theta(i)<= 4*pi/3
y(i)=6-3*abs(1-0.5*cos(3*theta(i)-2*pi));
elseif theta(i)>= 4*pi/3 & theta(i)<= 3*pi/2
y(i)=3;
elseif theta(i)>= 3*pi/2 & theta(i)<= 7*pi/4
y(i)=3-1.5*((theta(i)-3*pi)/(pi/4))^2;
elseif theta(i)>= 7*pi/4 && theta(i)<= 2*pi
y(i)=0.75-0.75*(1-((theta(i)-(7*pi/4))/(pi/4)))^2;
end
end
Save above code as function file named as displacement.m (MATLAB File) and call the function from another script
theta=linspace(0,2*pi,500);
y=displacement(theta);
plot(theta,y,'r','Linewidth',2)
grid on;
legend({'displacement(theta)'},'fontsize',10)
xlabel('Theta (radians)','fontsize',10)
ylabel('Displacement','fontsize',10)
title('Piecwise functions','fontsize',10)

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by