Reputation:
I am starting to work with MATLAB and I still don't know how to do a lot of things. I have to create a simple plot function, let's supose it is:
f(x)=3x+1, defined for example from -5 < x < 5
What I need to do is to create a function that transforms the independent variable (it's an input parameter). For example, if my function is named plotFunction
, if execute the command plotFunction(2x+3)
the final plotted graphic is the function:
f(x)=6x+10
Upvotes: 2
Views: 134
Reputation: 18172
Functions can be defined by the function
environment. You want a function that has no output variable, just the plot apparently.
function [] = plotFunction(f,minRange,maxRange)
range = minRange:0.01:maxRange; % Create plot range, change 0.01 to w/e precision you want to attain
figure; % Create figure
PlotFunc = 3.*f(range)+1; % Your function
plot(range,PlotFunc)
end
There's two things you need to know when trying to use other functions as 'base function': I have now set it to take steps of 0.01
this might need to be set smaller (e.g. when plotting on [-1e-4,1e-4]). You can do this by hand or use a precision switch as @efirvida used. The other thing: I call 3*f(range)+1
as PlotFunc
. If you want to use other functions, do it there, e.g. if you want to use cos(x)+1/3*sin(pi*x)*e^(-x))
set all the x
to f(x)
: PlotFunc = cos(f(x))+1/3.*sin(pi.*f(x))*exp(-f(x)))
Now you have to take care to call x
as a function handle
, like so: f = @(x)(2*x+3)
. The @
makes it a function handle, the argument directly behind it defines the variable in the defined function, here that's (x)
. The second set of brackets contains the actual function. Then define your range, i.e. minRange = -5
maxRange = 5
and call your function:
plotFunction(f,minRange,maxRange)
resulting in:
Upvotes: 4
Reputation: 4855
My solution
file plotFunction.m
function plotFunction(f, lb, ub, precision)
f = str2func(['@(x) ', f]);
plot(lb:precision:ub, f(lb:precision:ub))
end
where f
is string representation of function, and lb
,ub
the bound of the independent variable, and precision
the precision of the plot
run function
>>> plotFunction('2*x+3', -5, 5, 0.01)
>>> plotFunction('6*x+10 ', -5, 5, 0.01)
Upvotes: 2