I am confused as to how incorporate a value from another function in a different script, into this one where the y variable is now the input. The actual problem is below. Please show me how to solve this, and why.

2 views (last 30 days)
  1. Initialize a variable x that ranges from –π to +π, with an interval of 0.01.
  2. . Create a square wave variable by using the equation: ?(?) = (2 ∗ ?(?)) − 1 where x is the variable created in part 1.
  3. Create a new figure, and plot S(x) vs x. Change the color of this line plot to red, adjust the y axis to have the limits of [-3, 3], correctly label all axes for the plot and add a title
where H(x) is from a script where a function for heaviside step equation is shown. That H(x) = 0 when x < 0; 1 when x > 0; 0.5 when x = 0. My script for this equation is also said to be wrong. I used the following for this function script, and was told this is not the proper way to represent this. So how do I change this one, and then incorperate it into another script with the problem above?
function [y] = HeavisideFunct(x)
for
if x < 0
y = 0;
disp(y);
elseif x > 0
y = 1;
disp(y);
elseif x == 0
y = 0.5;
disp(y);
end
end
end
I know a certain vector is suppose to be used, but im not sure what kind or what it means.
  1 Comment
madhan ravi
madhan ravi on 4 Dec 2018
@Ann why do you edit it back even when your code was edited properly by another person? Format your code properly by selecting the code and pressing the code button so that its easy to read

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 4 Dec 2018
Edited: Stephen23 on 4 Dec 2018
The proper MATLAB solution would be to vectorize your code, which efficiently allows for the input to be an array of any size. For example, here as an anonymous function:
>> H = @(x) 0.5*(x==0) + (x>0);
>> H([-1,0,1])
ans =
0.00000 0.50000 1.00000
If you really want to write it in a file:
function y = H(x)
y = 0.5*(x==0) + (x>0);
end
And here is your requested plot (I am sure you can add the title and axes labels):
>> x = -pi:0.1:pi;
>> y = 2*H(x)-1;
>> plot(x,y,'r')
>> ylim([-3,3])
temp9.png

More Answers (1)

Geoff Hayes
Geoff Hayes on 4 Dec 2018
Ann - wouldn't your Heaviside function be simply
function [y] = heaviside(x)
if x < 0
y = 0;
elseif x > 0
y = 1;
else
y = 0.5;
end
Then, in your other function (or script) you would simply call this function for each element in your x array where
x = -pi:0.01:pi;
  4 Comments
Geoff Hayes
Geoff Hayes on 4 Dec 2018
True but that wasn't a clear requirement for this assignment and since Ann had initially added a for in the code, I continued with that approach.

Sign in to comment.

Categories

Find more on Labels and Annotations 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!