How can I plot a periodic function?

30 views (last 30 days)
A periodic function f of period is given by:
a) Plot the function in ;
I tried the following code but it did not had the expected output
% User-defined variables
interval_start = -4*pi; % Start of the interval
interval_end = 4*pi; % End of the interval
% Generate x-values over the defined interval
x = linspace(interval_start, interval_end, 1000);
% Evaluate the function
y = abs(mod(x, 2*pi));
% Plot the graph
plot(x, y);
xlabel('x');
ylabel('f(x)');
title('Graph of the Function f(x) = |x|');
grid on;
The exected output should be like:

Accepted Answer

Domnul G
Domnul G on 4 Jun 2023
In the first code, the issue lies in the line y = abs(mod(x, 2*pi));. Here's a breakdown of the problem:
  1. The mod(x, 2*pi) function returns the remainder when x is divided by 2*pi. This operation maps x to the interval [0, 2*pi), which means the resulting y values will be non-negative.
  2. The abs() function is then applied to the result of mod(x, 2*pi). However, since mod(x, 2*pi) is already non-negative, applying abs() has no effect on the values. Therefore, it is unnecessary in this case.
To fix the code and achieve the desired graph, we can modify the calculation of y. Here's the corrected code with explanations:
interval_start = -4*pi; % Start of the interval
interval_end = 4*pi; % End of the interval
% Generate x-values over the defined interval
x = linspace(interval_start, interval_end, 1000);
h = 2*pi; % Width of the interval you want to map the function to
y =abs(mod(x + h/2, h) - h/2 ) % Apply the shift and mod operation
y = 1×1000
0 0.0252 0.0503 0.0755 0.1006 0.1258 0.1509 0.1761 0.2013 0.2264 0.2516 0.2767 0.3019 0.3271 0.3522 0.3774 0.4025 0.4277 0.4528 0.4780 0.5032 0.5283 0.5535 0.5786 0.6038 0.6289 0.6541 0.6793 0.7044 0.7296
% Plot the graph
plot(x, y);
xlabel('x');
ylabel('f(x)');
title('Graph of the Function f(x) = |x|');
grid on;
% Set custom tick values and labels for x-axis
xticks([-4*pi:pi:4*pi]);
xticklabels({'-4\pi','-3\pi','-2\pi','-\pi','0','\pi','2\pi','3\pi','4\pi'});
% Set custom tick values and labels for y-axis
yticks([-pi:pi:pi]);
yticklabels({'-\pi', '0', '\pi'});
  1. We calculate y by adding h/2 to x to shift the values, then applying mod() with h to map them to the interval [-h/2, h/2).
  2. Finally, we subtract h/2 to center the function in the desired interval. This ensures that y will be in the range of [-π, π).
By making these changes, we correctly map the function to the desired interval and achieve the expected graph.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!