it says Error in result(i)=piecewise_function(x(i)); result(i)=piecew
Show older comments
% Plotting piecewise function using if else statements.
clc; clear all; close all;
% assign elements to x
x= -5:0.01:5;
%iterate over the elements in x one-by-one and calculate the value of f(x)
for i=1:length(x)
result(i)=piecewise_function(x(i));
end
% plot the values of y and x
plot(x,result)
xlabel('t-axis')
ylabel('x(t)-axis')
title('Piecewise Function f(x)')
grid on
hold off
% create a function to plot piecewise function
function result= piecewise_function(x)
if x >= 2 && x <=5
result = 3;
end
end
Answers (1)
Paul
on 7 Feb 2023
0 votes
What should result be if x < 2 or if x > 5?
2 Comments
Frishta
on 7 Feb 2023
Paul
on 7 Feb 2023
No, you want the result to be 3 then 2 < = x <= 5. But what should result be when x is not between 2 and 5?
Regardless, this approach isn't really the best way to solve the problem because it requires you, as the programmer, to basically figure out the answer before writing the code. Instead why not write a single function that takes as input t and returns the corresponding value of u(t) (or x and u(x) if you prefer x instead of t. So that function would look something like
function u = computeu(t)
% comput the value of u here based on the value of t
end
Then you can use this like
y = computeu(t-2) - computeu(t-5);
Categories
Find more on Subplots 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!