Empty plot when using for loop - matlab

I want to use a for loop to plot a function. The code is
y = 0;
for k = 0:0.1:2
y = y + k;
plot(k, y);
hold on;
end
However, by running the code, the plot window is empty! How can I fix that in order to see a line on a 2D area?

Matlab automatically plots the linear interpolation between the points that are given to the plot function. Thus as you only give a single point, no interpolation can happen.
What you can do is to save the old y value and the old x value to ask Matlab to plot a linear interpolation between these two points. e.g.
yold = 0; %Init
kold=0; %Init
for k = 0:0.1:2
y = yold + k; %New y value
plot([kold,k], [yold,y]); %Plot a linear interpolation
kold = k; %Save the new values as old
yold = y; %Same
hold on;
end
EDIT/NOTE:
When adding new plots to the same window, MATLAB automatically changes color, thus the above will give you a rainbow, which is nice, but in case you want to keep it professional, you can add a color to the plot command, e.g.
plot([kold,k], [yold,y],'blue');

Related

LogLog plot in MATLAB is not creating a plot [duplicate]

I'm trying to plot a simple graph using for loop as shown below
x=linspace(0,2*pi,100);
for i=1:numel(x)
y=sin(x(i));
plot(x(i),y)
hold on
end
However, nothing appear on my figure. Why is that?
Why this happens...
With plot(x(i),y) you are plotting 100 single points (one in each iteration) and they are not shown by default. Therefore the plot looks empty.
Solution 1: Vectorized calculation and direct plot
I assume you meant to draw a continuous line. In that case no for-loop is needed because you can calculate and plot vectors directly in MATLAB. So the following code does probably what you want:
x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y);
Note that y is a vector as well as x and that y(n) equals to sin(x(n)) for all n. If you want to plot the points itself, use LineSpec-syntax when calling plot like this1:
plot(x,y,'*');
1) Other types of points are possible as well, see the above linked documentation.
Solution 2: Calculate values within for-loop and plot afterwards
If you want to calculate the values within a for-loop and plot it afterwards: Pre-allocate the needed variable (in this case y), calculate the values within the for-loop and finally plot it with one single command after the calculation.
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
end
plot(x,y);
Solution 3: Dynamically update plot while calculating
In case you insist on plotting within each iteration, the previous code from Solution 2 can be expanded as follows: Create a figure, add an 'empty' plot to it and store its handle. Within the for-loop calculate the values and add them to the y-vector as shown above. As a last step you can update the plot by changing its XData and YData properties and calling drawnow. Note that calling plot every time within the for-loop is unnecessarily expensive and I don't recommend it.
% create figure and plot
figure;
ph = plot(0,0);
ax = gca;
set(ax,'XLim',[0,2*pi]);
set(ax,'YLim',[-1,1]);
% calculate and update plot
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
set(ph,'XData',x(1:i));
set(ph,'YData',y(1:i));
drawnow;
end
Simple approach
If you want to draw a curve as you add data, try the following:
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
for i=1:numel(x)
y(i) = sin(x(i));
plot(x(1:i), y(1:i), 'color', 'r')
drawnow();
end
Be aware that the plot automatically tries to set x and y limits (curve is scaled to the plot window), to prevent that you have to manually set the x- and y-limits with xlimand ylim.
As Matt wrote in his answer, calling plot in each iteration is quite expensive (i.e. time consuming). Therefore I suggest using datasources:
Update graph using data sources
% Create a panel and axes object
h_panel = uipanel;
h_axes = axes( 'Parent', h_panel);
% Create data sources
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
% Create graph object, in this case stairs
% and bind the variables x and y as its data sources
h_stairs = stairs(h_axes, x, y, 'XDataSource', 'x', 'YDataSource', 'y');
for i=1:size(x)
y(i) = sin(x(i));
% Update the data of the stairs graph
refreshdata(h_stairs);
drawnow();
end
The call to drawnow isn't neccessary in each iteration, it is only used to update the visuals, so you can see the changes directly.

MATLAB - adding plot to another plot after loop, more sophisticatedly

i have a problem and i hope that i will find help there.
This is my example code. Its only part of my algorithm. For imagine, how the point are moving, during the equations, i need show contour of function with two variables and into the points. Becase i have more difficult function than parabolic function, so the equations are too long than i need. For this reason i move contour ploting before the loop. But i have problem. I need show countour always and points only for i-loop and my solution doesnt work. Please help me!
[R S] = meshgrid(-5:0.1:5, -5:0.1:5);
figure
contour(R, S, R.^2 + S.^2, 5);
axis([-5,5,-5,5])
axis square
hold on
for i=1:50
a = 0;
b = 1:2
B = repmat(b,5,1)
A = unifrnd(a,B)
x = A(1:5,1);
y = A(1:5,2);
scatter(x,y,'fill')
hold off
pause(0.5)
end
You should store the handle to your scatter plot and simply update the XData and YData properties of it rather than destroying the plot objects every time
[R S] = meshgrid(-5:0.1:5, -5:0.1:5);
figure
contour(R, S, R.^2 + S.^2, 5);
axis([-5,5,-5,5])
axis square
hold on
% Create a scatter plot and store the graphics handle so we can update later
hscatter = scatter(NaN, NaN, 'fill');
for i=1:50
a = 0;
b = 1:2
B = repmat(b,5,1)
A = unifrnd(a,B)
x = A(1:5,1);
y = A(1:5,2);
% Update the X and Y positions of the scatter plot
set(hscatter, 'XData', x, 'YData', y);
pause(0.5)
end

MATLAB: Drawing atop a surface plot

I'm plotting an R^2 to R function in MATLAB as a surface plot, which I colormap and view from above.
surf(X, Y, data);
colormap(jet);
colobar;
view(2);
It produces (with some additional code) something like
though the true nature of the function (for the purpose of understanding this question) is better observed from an angle like:
I want to plot a circle atop my original plot (seen from above). Something like...
I can't seem to achieve this however, since plotting in-a-plane elements on plots makes them appear on the x-y axis, which is covered by my surface plot. For example, calling
circle_pos = [ +1 +1; -1 -1; -1 +1; +1 -1;]
circle_rad = 0.2 * ones(4,1);
viscircles(circle_pos, circle_rad);
after my surface plot results in no visible circles when viewed from the top. Zooming and rotating reveals these circles were plotted on the x-y plane, and so are invisible from above.
How do I plot my circles on top of the surface plot, so that they are visible from above?
A similar issue arises when plotting text atop the surface, but is remedied by specifying a z position value just above the underlying functions z value. There doesn't seem to be any way to specify the z position of these graphical elements.
There may not be a direct way to specify the z position of the objects returned by viscircles, but in general there is (most of the time) a way to modify properties and position of any graphic object afterwards.
Method 1: modifying circles after creation.
If you plan to do modifications of a graphic object, the first thing to do is always to retrieve its handle. So in your case, you would have to call viscircles by specifying a return value (which will contain the handle you want).:
hg = viscircles(circle_pos, circle_rad);
I do not have the Image Processing Toolbox so I do not have access to the viscircles function. However I read from the documentation that the handle returned is an hggroup. An hggroup is simply a container containing one or more handles of more primitive graphic objects. In this case the hggroup contains the handles of 4 lines (your 4 circles).
The easiest way to transform all the objects in an hggroup is to use a hgtransform object. We will define a Translation transformation and the hgtransform will apply it to the 4 circles (all the children of the hggroup).
To define the translation, we will use a makehgtform object.
Here we go:
ht = hgtransform ; % create the transform object
set(hg,'Parent',ht) ; % make it a "parent" of the hggroup
zc = max(max(Z)) ; % Find by how much we want to translate the circles on the Z axis
Tz = makehgtform('translate',[0 0 zc]) ; % create the TRANSLATION transform
set(ht,'Matrix',Tz) % apply the transformation (translation) to the hggroup/hgtransform
Done, your 4 circles should now be on top of your surface. Note that you can specify any other values for zc (not only the max of the surface).
Method 2: DIY
In case you do not want to be reliant on the image processing toolbox, or if you do not have it at all, it is relatively easy to create circles in a 3D space by yourself.
Here is a function which will create circles in a way comparable to viscircles but it also let you specify an optional z coordinate for the circle centre positions.
code for circles_3D.m:
function hg = circles_3d( pos , rad , varargin )
% get current axes handle and hold state
ax = gca ;
holdState = get(ax,'NextPlot') ; % save state to reinstate after function
set(ax,'NextPlot','add') ; % equivalent of "hold off"
tt = linspace(0,2*pi) ;
hg = hggroup(ax) ;
for k = 1:numel(rad)
c = pos(k,:) ;
r = rad(k) ;
x = c(1) + r.*cos(tt) ;
y = c(2) + r.*sin(tt) ;
z = zeros(size(x)) ;
if numel(c)==3 ; z = z + c(3) ; end
plot3(hg,x,y,z,varargin{:}) ;
end
set(ax,'NextPlot',holdState) ; % restore axes hold state
You can now call this function instead of viscircles. I used the varargin parameter to transfer any line property to the circles created (so you can specify the Color, LineWidth, and any other typical parameter you like.
For the sake of an example, I need to recreate a surface comparable to your, with 4x "zero" poles distributed around the maxima:
pc = 0.5 ; % pole centers
pw = 0.05 ; % pole widths
% surface definition
[X,Y] = meshgrid(-5:.1:5);
R = sqrt(X.^2 + Y.^2) + eps ;
Z = sin(R)./R;
% zero surface values around the defined poles
[idxPoles] = find(abs(X)>=pc-pw & abs(X)<=pc+pw & abs(Y)>=pc-pw & abs(Y)<=pc+pw ) ;
Z(idxPoles)= 0 ;
% display
hs = surf(X,Y,Z) ; shading interp
Which produces:
Now you can simply get your circles with the circles_3D function:
zc = max(max(Z)) ;
circle_pos = [ pc pc zc ; -pc -pc zc ; -pc +pc zc ; +pc -pc zc ] ;
circle_rad = 0.2 * ones(4,1);
h = circles_3d( circle_pos , circle_rad , 'Color','r','LineWidth',2) ;
and get:
Note that I made this function so it also return an hggroup object containing your lines (circles). So if you want to move them later, apply the same trick than in the first part of the answer.
Several options spring to mind.
The simplest will be to plot a marker in 3d using plot3:
figure;
peaks;
shading interp;
hold;
x = 0; y = 2; z = 10;
plot3(x, y, z, 'ro', 'MarkerSize', 24);
That will work, but the circle will always appear to be facing the viewer:
Alternatively, you can plot a circle in 3d:
vfTheta = linspace(0, 2*pi, 300);
figure; peaks; shading interp; hold;
x = 0; y = 2; z = 10; r = 0.2;
plot3(x + r.*cos(vfTheta), y + r.*sin(vfTheta), z .* ones(size(vfTheta)), 'r-', 'LineWidth', 2);
The result: a nice halo in 3d!

Plotting graph using for loop in MATLAB

I'm trying to plot a simple graph using for loop as shown below
x=linspace(0,2*pi,100);
for i=1:numel(x)
y=sin(x(i));
plot(x(i),y)
hold on
end
However, nothing appear on my figure. Why is that?
Why this happens...
With plot(x(i),y) you are plotting 100 single points (one in each iteration) and they are not shown by default. Therefore the plot looks empty.
Solution 1: Vectorized calculation and direct plot
I assume you meant to draw a continuous line. In that case no for-loop is needed because you can calculate and plot vectors directly in MATLAB. So the following code does probably what you want:
x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y);
Note that y is a vector as well as x and that y(n) equals to sin(x(n)) for all n. If you want to plot the points itself, use LineSpec-syntax when calling plot like this1:
plot(x,y,'*');
1) Other types of points are possible as well, see the above linked documentation.
Solution 2: Calculate values within for-loop and plot afterwards
If you want to calculate the values within a for-loop and plot it afterwards: Pre-allocate the needed variable (in this case y), calculate the values within the for-loop and finally plot it with one single command after the calculation.
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
end
plot(x,y);
Solution 3: Dynamically update plot while calculating
In case you insist on plotting within each iteration, the previous code from Solution 2 can be expanded as follows: Create a figure, add an 'empty' plot to it and store its handle. Within the for-loop calculate the values and add them to the y-vector as shown above. As a last step you can update the plot by changing its XData and YData properties and calling drawnow. Note that calling plot every time within the for-loop is unnecessarily expensive and I don't recommend it.
% create figure and plot
figure;
ph = plot(0,0);
ax = gca;
set(ax,'XLim',[0,2*pi]);
set(ax,'YLim',[-1,1]);
% calculate and update plot
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
y(i) = sin(x(i));
set(ph,'XData',x(1:i));
set(ph,'YData',y(1:i));
drawnow;
end
Simple approach
If you want to draw a curve as you add data, try the following:
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
for i=1:numel(x)
y(i) = sin(x(i));
plot(x(1:i), y(1:i), 'color', 'r')
drawnow();
end
Be aware that the plot automatically tries to set x and y limits (curve is scaled to the plot window), to prevent that you have to manually set the x- and y-limits with xlimand ylim.
As Matt wrote in his answer, calling plot in each iteration is quite expensive (i.e. time consuming). Therefore I suggest using datasources:
Update graph using data sources
% Create a panel and axes object
h_panel = uipanel;
h_axes = axes( 'Parent', h_panel);
% Create data sources
x = linspace(0,2 * pi, 100);
y = zeros(size(x));
% Create graph object, in this case stairs
% and bind the variables x and y as its data sources
h_stairs = stairs(h_axes, x, y, 'XDataSource', 'x', 'YDataSource', 'y');
for i=1:size(x)
y(i) = sin(x(i));
% Update the data of the stairs graph
refreshdata(h_stairs);
drawnow();
end
The call to drawnow isn't neccessary in each iteration, it is only used to update the visuals, so you can see the changes directly.

plotting scatter3 and surf plots from loop in matlab

I want to plot scatter3 and surf plots from a loop. Below is my code but it isn't working...not sure where I'm going wrong but clearly something is wrong with the z matrix?
for e = 1:10;
x = rand(1,3);
y = rand(1,3);
A = x+y;
subplot(2,2,1)
p = find(A(:,1) > 1.1 & A(:,1) < 1.6);
Result = A(p,:);
scatter3(Result(:,1), Result(:,2), Result(:,3))
hold on
z(e,:) = [Result(1) Result(2) Result(3)];
end
subplot(2,2,2)
surf(z)
I will reiterate what I said in my comment to you. I got this error message when trying to run your code: Attempted to access Result(1); index out of bounds because numel(Result)=0. This is because your p condition isn't satisfied - MATLAB could not find any elements in the first column that are between 1.1 and 1.6.
As such, what I would suggest you do is check to see if Result is empty before trying to access the value itself. However, I would suggest you don't write a loop and generate all of the random values at once, then do the filtering with the Boolean conditions. Therefore, the equivalent code without using a loop would be this:
x = rand(10,3);
y = rand(10,3);
A = x+y;
p = A(:,1) > 1.1 & A(:,1) < 1.6;
z = A(p,:);
figure;
subplot(2,1,1);
scatter3(z(:,1), z(:,2), z(:,3));
subplot(2,1,2);
surf(z);
We generate 10 3D points for x and y at the beginning, then add these and store this into A. Next, we find the rows in A that are between 1.1 and 1.6 in the first column and store this as a logical array. We then use this array to index into A and store the results into z. This is the recommended approach if you want to extract certain elements into an array rather than using find.
Once we obtain z, we plot these points with scatter, then also find a surface plot with surf for the same matrix. BTW, I've fixed your subplot as you are only creating two plots, yet you are allocating space for 4 plots.
If you're absolutely bent on using your code, you would simply do this:
z = []; %// Change
for e = 1:10
x = rand(1,3);
y = rand(1,3);
A = x+y;
subplot(2,1,1)
p = find(A(:,1) > 1.1 & A(:,1) < 1.6);
Result = A(p,:);
scatter3(Result(:,1), Result(:,2), Result(:,3))
hold on
if ~isempty(Result) %// Change here
z = [z; Result(1) Result(2) Result(3)]; %// Change
end
end
subplot(2,1,2)
surf(z)
What's important is the initialization of z. I made this empty, and we only add to z if Result is not empty - this will happen if you generate a number that is not between 1.1 and 1.6.