Matlab: Plotting on same figure using 2 different functions - matlab

I have written a function of the form
function myplot(x,y)
plot(x,y)
end
This function creates a plot for given values of x and y. The actual function is more complex, but it does not serve the purpose of the question to include its content here. The main point follows.
I have tried to run the following script:
x = [1:0.01:10]
y = [1:0.01:10]
figure
plot(sin([1:0.01:10]))
hold on
myplot(x,y)
The intent here is to plot 2 sets of data on the same graph. The first set of data is generated by Matlab's native plot command while the second set of data is generated by the user custom myplot function (in this case what should be a straight line). The script above wont do it....
How to get Matlab to include both sets of data on the same plot?

your script plots them both but with different x values. if you don't specify x input in plot it uses 1:length(y), while your myplot function does specify x values (which in your case are 10-fold smaller).
just do: plot(x,sin([1:0.01:10])) instead of plot(sin([1:0.01:10]))

You could save the current axes (on which you create the first plot) in a variable and pass it as an argument to your function to be sure it gets plot on the same axes no matter what happens elsewhere in your code.
So your main code could look like this:
x = [1:0.01:10];
y = [1:0.01:10];
figure
plot(sin([1:0.01:10]))
hold on
%// Save axes in variable
CurrentAxes = gca;
%// Pass it as argument to function
myplot(x,y,CurrentAxes)
and the function:
function myplot(x,y,hAxes)
plot(hAxes,x,y);
end

Related

How to convert double to object handle to graph a contour plot?

I am working with app designer in MATLAB where I have the user input a bunch of parameters and push a button and then generate a contour plot. The app first uses dlmread to save data from 3 separate files to the workspace. Then what the goal is, is to generate a corresponding contour plot on that same GUI that uses data from those 3 files (my x, y, and z parameters).
However, when I run the program, I get an error that says:
"Error setting property 'HetroTransSpec' of class 'Parameters':
Cannot convert double value 5 to a handle"
app.HetroTransSpec is the name of my contour plot. Parameters is the name of my GUI application. I will present the code:
function SetParametersButtonPushed(app, event)
spec = dlmread('/Users/******/MATLAB/SphoHetroTest/Spec3.txt'); %Load spec file
assignin('base', 'spec', spec);
pop=dlmread('/Users/******/MATLAB/SphoHetroTest/pop.txt');
assignin('base', 'pop', pop);
lambda=dlmread('/Users/******/MATLAB/SphoHetroTest/lambda.txt'); %read wavelenght axis (nm)
assignin('base', 'lambda', lambda);
Now, here is my code to take these parameters (spec, pop, lambda) to generate my contour plot. Except I am getting that error:
app.HetroTransSpec = contourf(pop,lambda,spec);
Any help would be greatly appreciated!
The result of a contour plot is not a handle, but contour data, as opposed to some other plotting functions.
Try:
[~,handle]= contourf(pop,lambda,spec);
app.HetroTransSpec =handle;

Plotting 3 vectors in Matlab GUI axes handle

I am trying to plot 3 vectors onto matlab GUI in a serial object's callback.
I want to plot this on axes handle but the problem is it only plot last vector;
plot(handles.axes1,sensor1,'r');
plot(handles.axes1,sensor2,'b');
plot(handles.axes1,sensor3,'g');
I searched on internet and find that this issue can be solved with hold on and hold of feature so I tried this
plot(handles.axes1,sensor1,'r');
hold on ;
plot(handles.axes1,sensor2,'b');
plot(handles.axes1,sensor3,'g');
hold off;
but in this case a new figure is opened(dont know why) and again only the last plot is drawn.
I am stucked. If any one have idea of what would be the issue?
Thanks
I'm not sure why your first try using "hold" didn't work. Seems like it should have.
But in any case, you can get the desired behavior in a single command:
plot(handles.axes1,length(sensor1),sensor1,'r',...
length(sensor2),sensor2,'b',...
length(sensor3),sensor3,'g');
This specifies both an X = length(sensor_) and a Y = sensor_ to the plot command. When you only give plot a Y input, it assumes an X of length(Y). But you can't combine multiple traces in a single plot command by giving only the Y input for each, because it will try to treat the inputs as X,Y pairs.
As the vectors are the same length we can simply combine them as the columns of a matrix and then plot the matrix
plot(handles.axes1,[sensor1',sensor2',sensor3'])
However these will have the default colour order. Without specifying x values setting colors within the plot command is tricky. However (luckily) the default order starts:
blue,green,red...
so swapping the column order will plot the lines with the colours requested
plot(handles.axes1,[sensor2',sensor3',sensor1'])
(this assumes the vectors are rows, if they are columns don't transpose them)

MATLAB : identifying the parameters corresponding to the loop variable

I have trying to plot solutions to coupled ODEs.I solve them using ODE15s solver and pass arguments using a for loop.
MATLAB code then returns a set of plots to me(using hold on).Now only one of the given graphs is appropriate to my theory.So,how do I identify the argument(that I had passed through the for loop) which corresponds to my chosen graph(I can pick out the graph visually)
Just use 'text' function to mark the arguments nearby the each graph.There is a very simple demo(a is the argument):
x=0:100;
figure;
hold on;
for a=1:10
plot(x,a*x);
text(100,a*100,sprintf('a=%s',num2str(a)));
end
Sorry for not pasting picture here because my reputation is not enough.

How to plot a graph by using looping in time?

I want to plot a graph of position, velocity and acceleration of a robot joint, but I don't know how to plot it. This is my equation:
(position)
for 0<=t<=tblend,
y = theta1s+((0.5.*acc1).*(t^2));
for tblend<t<tf-tblend,
y = -195.21+(52.08.*t);
for tf-tblend<t<=tf,
y = 20-15.*((5-a)^2);
What command must I use to plot this graph? If possible, I want to display the equation of y too.
First create the grid of t values assuming a stepsize (here I picked 0.1) and the final value you mention called tf:
t = 0:0.1:tf;
Then use logical indexing to apply different functions to different regions of this grid of values:
y = ( theta1s+((0.5.*acc1).*(t^2)) ).*(0 <= t).*(t<=tblend) + ...
( -195.21+(52.08.*t)).*( tblend<t).*(t<tf-tblend) + ...
( 20-15.*((5-a)^2) ).*(tf-tblend<t).*(t<=tf);
This will apply the piecewise definitions of the function y by multiplying each difference piece by a logical that is 1 only on the region where it applies and 0 elsewhere. Then a simple
plot(t,y)
will show you the plot. For printing this functions, you'll need to format the title of your plot figure window using Matlab's native LaTeX syntax. Look up and use the LaTeX command \begin{cases} ... \end{cases} for the piecewise function stuff. You can pass most of this straight to the title() command.
For another solution, if you have the signal processing toolbox, you can just use the built-in
heaviside(t)
function. Suitably change the value of t for each left endpoint of a new segment of the piecewise function and then subtract and corresponding heaviside() term for each right endpoint of a segment. If you don't have the built-in heaviside() function, you can easily find third-party implementations at the Matlab central file exchange.

Real time plot in MATLAB

I'm very new to MATLAB and I was trying to display a real time plot of some calculations. I have an N sized vector and I work with m values at a time (say m = N/4), so I want to plot the first m values and then as soon as the second m values are calculated have them replace the first plot.
My approach was as follows:
for i=1:N,
...
//compute m
...
plot(m);
end;
but it fails to update the plot in every loop and waits for all the loops to finish to plot the data. My question is: Should I use another function instead of plot or could I add some delay in each loop?
I think there must be a way I'm not aware of for updating the plot instead of re-plotting it every time.
As Edric mentioned, you'll definitely want to include a drawnow command after the call to plot to force an update of the graphics. However, there is a much more efficient and smoother method to animate plots that doesn't involve recreating the entire plot each time. You can simply initialize your plot, capture a handle to the plot object, then modify the properties of that object in your loop using the set command. Here's an example:
hLine = plot(nan); % Initialize a plot line (which isn't displayed yet
% because the values are NaN)
for i = 1:N % Loop N times
...
% Compute m here
...
set(hLine, 'YData', m); % Update the y data of the line
drawnow % Force the graphics to update immediately
end
In addition, before your loop and after the call to plot you can set a number of axes properties, like the axes limits, etc., if you want the axes to stay fixed and not change their appearance with each new vector m that is plotted.
You can add a call to DRAWNOW to force the plot to update. See the reference page. Note that DRAWNOW causes the graphics event queue to be flushed, which may cause callbacks etc. to be executed.