Plotting of a expotential curve between an interval in MATLAB - matlab

I would like to plot an expotential curve between an interval based on a different multipler for each interval.
I have tried this:
%Plotting of h curve
function PlotQ(Time,h)
for i=2:size(Time,1)
for t=Time(i-1):0.1:Time(i)
plot([Time(i-1), Time(i)],exp(-h(i)*t))
hold on;
end
end
ymax = max();
xlim([1 max(Time)]);
ylim([-0.5 ymax+0.5]);
xlabel('Time')
ylabel('Rate')
end
The curve comes out like this:
Not sure what I am doing wrong.. Need some guidance..
New Edit:
T =[0;0.569444444444444;1.06666666666667;2.08611111111111;3.09722222222222;4.11111111111111;5.12500000000000;7.16111111111111;10.2000000000000;20.3444444444444;30.4944444444444];
%Plotting of h and Q
h = [0;0.0187;0.0194;0.0198;0.0215;0.0225;0.0241;0.0316;0.0379;0.0437;0.0452];
PlotQ(Time,h)

If I understood correctly, You are looking for something like this.
%Plotting of h curve
function PlotQ(Time,h)
for i=2:size(Time,1)
tVector=Time(i-1):0.1:Time(i);
sizetVector=length(tVector);
for t=2:sizetVector
plot([tVector(t-1), tVector(t)],[exp(-h(i)*tVector(t-1)),exp(-h(i)*tVector(t))]);
hold on
end
end
ymax = max();
xlim([1 max(Time)]);
ylim([-0.5 ymax+0.5]);
xlabel('Time')
ylabel('Rate')
end

I think, this is what you want:
function PlotQ(Time,h)
% Parameters
res = 0.1;
n = numel(h);
% Pre-allocate
y = cell(1,n);
t = cell(1,n);
% Calculate
for ii=2:n
t{ii} = Time(ii-1):res:Time(ii);
y{ii} = exp(-h(ii)*t{ii});
end
% Plot
t_ = [t{:}];
y_ = [y{:}];
figure;
plot(t_,y_);
axis([1 max(t_) -0.5 max(y_)+0.5]);
xlabel('Time');
ylabel('Rate');
end
It gives the following plot:

Related

MATLAB Update trisurf handle

I'm using a Delaunay triangularization to convert a scatter plot to a surface. To animate this plot, I want to update the trisurf handle instead of creating a new trisurf plot to reduce overhead and to increase the plotting speed.
Basically, in a for loop, I want to update the properties of the trisurf handle h to obtain the same plot that calling trisurf again would yield.
MWE
x = linspace(0,1,11);
y = x;
[X,Y] = meshgrid(x,y);
mag = hypot(X(:),Y(:)); % exemplary magnitude
T = delaunay(X(:),Y(:));
z = 0
h = trisurf(T, X(:), Y(:), z*ones(size(X(:))), mag, 'FaceColor', 'interp'); view([-90 90]);
for i = 1:10
% Compute new values for X, Y, z, and mag
% -> Update properties of handle h to redraw the trisurf plot instead
% of recalling the last line before the for loop again, e.g.,
% h.FaceVertexCData = ...
% h.Faces = ...
% h.XData = ...
end
You can change a few properties of the Patch object returned by trisurf():
for i = 1:9
% Compute new values for X, Y, z, and mag
% As an example:
x = linspace(0,1,11-i);
y = x;
[X,Y] = meshgrid(x,y);
mag = hypot(X(:),Y(:));
T = delaunay(X(:),Y(:));
z = i;
Z = z*ones(size(X)); %we could have just called `meshgrid()` with 3 arguments instead
% End recomputation
% Update trisurf() patch: option 1
set( h, 'Faces',T, 'XData',X(T).', 'YData',Y(T).', 'ZData',Z(T).', 'CData',mag(T).' );
pause(0.25); %just so we can see the result
% Update trisurf() patch: option 2
set( h, 'Faces',T, 'Vertices',[X(:) Y(:) Z(:)], 'FaceVertexCData',mag(:) );
pause(0.25); %just so we can see the result
end
where z is assumed to always be a scalar, just like in the original call to trisurf().
Q: Are these options equally fast?
A: I have run some tests (see code below) on my computer (R2019a, Linux) and found that, when the number of x/y-positions is a random number between 2 and 20, multiple set() calls using Vertices can be some 20% faster than set() calls using XData and related properties, and that these strategies are about an order of magnitude faster than multiple trisurf() calls. When the number of x/y-positions is allowed to vary from 2 to 200, however, run times are about the same for the three approaches.
Nruns=1e3;
Nxy_max=20;
for i=1:Nruns
if i==round(Nruns/10)
tic(); %discard first 10% of iterations
end
x = linspace(0,1,randi(Nxy_max-1)+1); %randi([2,Nxy_max]) can be a bit slower
[X,Y,Z] = meshgrid(x,x,randn());
mag = hypot(X(:),Y(:));
T = delaunay(X(:),Y(:));
trisurf(T, X(:), Y(:), Z(:), mag, 'FaceColor', 'interp');
view([-90 90]);
end
tmean_trisurf=1e3*toc()/(Nruns-round(Nruns/10)+1), %in [ms]
h=trisurf(T, X(:), Y(:), Z(:), mag, 'FaceColor', 'interp');
view([-90 90]);
for i=1:Nruns
if i==round(Nruns/10)
tic();
end
x = linspace(0,1,randi(Nxy_max-1)+1);
[X,Y,Z] = meshgrid(x,x,randn());
mag = hypot(X(:),Y(:));
T = delaunay(X(:),Y(:));
set( h, 'Faces',T, 'XData',X(T).', 'YData',Y(T).', 'ZData',Z(T).', 'CData',mag(T).' );
end
tmean_xyzdata=1e3*toc()/(Nruns-round(Nruns/10)+1), %in [ms]
for i=1:Nruns
if i==round(Nruns/10)
tic();
end
x = linspace(0,1,randi(Nxy_max-1)+1);
[X,Y,Z] = meshgrid(x,x,randn());
mag = hypot(X(:),Y(:));
T = delaunay(X(:),Y(:));
set( h, 'Faces',T, 'Vertices',[X(:) Y(:) Z(:)], 'FaceVertexCData',mag(:) );
end
tmean_vertices=1e3*toc()/(Nruns-round(Nruns/10)+1), %in [ms]

How to make animation in MATLAB which the curve is moving, not axes is moving?

I want to plot y=omega*x^2, which omega is -3 into 3 with step size 0.25, x from -4 into 4 with step size 0.001. But this code give me the curve is cannot moving and axes is moving. I want the curve is moving, like this.
x=-4:0.001:4;
for omega=-3:0.25:3
for i=1:length(x)
y(i)=omega*x(i)^2;
end
plot(x,y);
pause(0.1);
end
How to do that?
As another answer has indicated, you need to set the axis limits.
(Also note that there is no reason to calculate y using a loop.)
But instead of using plot every time through the loop it's more efficient to create the line only once, and then replace the x and y data of the line each time through the loop.
x=-4:0.001:4;
all_omega=-3:0.25:3;
for idx = 1:numel(all_omega)
omega = all_omega(idx);
y=omega*(x.^2);
if idx == 1
% create line
hl = plot(x,y);
axis([-4,4,-40,40]);
box on
grid on
else
% replace line data
set(hl,'XData',x,'YData',y);
end
title(sprintf('\\Omega = %.2f',omega));
pause(0.1);
end
Or you might want to use animatedline,
x=-4:0.001:4;
all_omega=-3:0.25:3;
for idx = 1:numel(all_omega)
omega = all_omega(idx);
y=omega*(x.^2);
if idx == 1
% create animated line
am = animatedline(x,y);
axis([-4,4,-40,40]);
box on
grid on
else
% replace the line
clearpoints(am)
addpoints(am,x,y);
end
title(sprintf('\\Omega = %.2f',omega));
pause(0.1);
end
A quick method is setting the x- and y-axes limits in the loop after each plot, using the axis([xmin, xmax, ymin, ymax]) command. This method isn't foolproof, in the case that the script gets help up after plotting but before setting the axes limits, but in most cases it should work.
figure(1)
x=-4:0.001:4;
for omega=-3:0.25:3
for i=1:length(x)
y(i)=omega*x(i)^2;
end
plot(x,y);
axis([-4 4 -50 50])
pause(0.1);
end
This is the same as #phil-goddard's answer, but makes more efficient use of handles to the animated YData and title string.
x = -4 : 0.001 : 4;
y = zeros(1, numel(x));
omega_range = -3 : 0.25 : 3;
% Create line and title, and obtain handles to them.
h_plot = plot(x, y);
axis([-4, 4, -40, 40]);
box on;
grid on;
h_title = title(sprintf('\\omega = %.2f', 0));
for idx = 1:numel(omega_range)
omega = omega_range(idx);
y = omega * (x.^2);
% Replace y data.
h_plot.YData = y;
% Replace title string.
h_title.String = sprintf('\\omega = %.2f', omega);
pause(0.1);
end

Creat 3d plot- equation (2 paramenters) time dependent ? matlab

I have an equation
Z=aexp(kt)
Is there any way to "plot" the result "Z" in function of variation on the parameters "k" and "a" AND along time??
or to make a surface..Or I´ll always have to fixate on of the parameters?
cheers
Here is a basic example with color coding the time axis
clear;close all;clc;
t=0:0.02:0.2;
k = 0:10;
a = 0:100;
[x, y] = meshgrid(k, a);
figure;
colorList = colormap(jet);
hold on;
for ii=1:numel(t)
z=y.*exp(x.*t(ii));
h = surf(x, y, z);
set(h,'edgecolor','none','FaceColor',colorList(5*ii,:),'FaceAlpha',0.5);
end
hold off;
legend(cellstr(num2str(t', 't=%.2f')), 'location', 'northwest')
view([45 30]);
xlabel('k');
ylabel('a');
zlabel('Z');
and the result

Draw log graph curve on Matlab by clicking?

I'd like to draw a curve on an empty (semilog-y) graph by clicking the points I want it to run through, on the X-Y plane.
Is there a function for this?
edit: I'm trying to do this by obtaining the position of last pointer click -
axis([0 3000 0 1000]);
co=get(gcf, 'CurrentPoint');
It seems to return the cursor position at the time of execution, but it does not change later.
edit2: Here's what works for me. The actual drawing I can do by using the arrays of points collected.
clear
clc
h=plot(0);
grid on;
xlim([0 3000]);
ylim([0 1000]);
datacursormode on;
% Enlarge figure to full screen.
screenSize = get(0,'ScreenSize');
set(gcf, 'units','pixels','outerposition', screenSize);
hold on;
% Print the x,y coordinates - will be in plot coordinates
x=zeros(1,10); y=zeros(1,10);
for p=1:10;
[x(p),y(p)] = ginput(1) ;
% Mark where they clicked with a cross.
plot(x(p),y(p), 'r+', 'MarkerSize', 20, 'LineWidth', 3);
% Print coordinates on the plot.
label = sprintf('(%.1f, %.1f)', x(p), y(p));
text(x(p)+20, y(p), label);
end
Not really, but now there is:
function topLevel
%// parameters
xrange = [0 100];
yrange = [1e-4 1e4];
%// initialize figure, plot
figure, clf, hold on
plot(NaN, NaN);
axis([xrange yrange]);
set(gca, 'YScale', 'log')
t = text(sum(xrange)/2, sum(yrange)/2, ...
'<< Need at least 3 points >>',...
'HorizontalAlignment', 'center');
%// Main loop
xs = []; p = [];
ys = []; P = [];
while true
%// Get new user-input, and collect all of them in a list
[x,y] = ginput(1);
xs = [xs; x]; %#ok<AGROW>
ys = [ys; y]; %#ok<AGROW>
%// Plot the selected points
if ishandle(p)
delete(p); end
p = plot(xs, ys, 'rx');
axis([xrange yrange]);
%// Fit curve through user-injected points
if numel(xs) >= 3
if ishandle(t)
delete(t); end
%// Get parameters of best-fit in a least-squares sense
[A,B,C] = fitExponential(xs,ys);
%// Plot the new curve
xp = linspace(xrange(1), xrange(end), 100);
yp = A + B*exp(C*xp);
if ishandle(P)
delete(P); end
P = plot(xp,yp, 'b');
end
end
%// Fit a model of the form y = A + B·exp(C·x) to data [x,y]
function [A, B, C] = fitExponential(x,y)
options = optimset(...
'maxfunevals', inf);
A = fminsearch(#lsq, 0, options);
[~,B,C] = lsq(A);
function [val, B,C] = lsq(A)
params = [ones(size(x(:))) x(:)] \ log(abs(y-A));
B = exp(params(1));
C = params(2);
val = sum((y - A - B*exp(C*x)).^2);
end
end
end
Note that as always, fitting an exponential curve can be tricky; the square of the difference between model and data is exponentially much greater for higher data values than for lower data values, so there will be a strong bias to fit the higher values better than the lower ones.
I just assumed a simple model and used a simple solution, but this gives a biased curve which might not be "optimal" in the sense that you need it to be. Any decent solution really depends on what you want specifically, and I'll leave that up to you ^_^

Matlab vertical line keeps appearing while using hold on and area()

It is beginning to annoy me that I can't get rid of this vertical line that keeps appearing when I plot the area;
[x y] = ginputExtra(4)
x = 0.1947 0.6118 0.8329 0.4136
y = 0.5746 0.8173 0.4225 0.3553
area([x x(1)],[y y(1)])
[x y] = ginputExtra(4,true)
x = 0.5087 0.6881 0.4954 0.3204
y = 0.4961 0.2382 0.1566 0.3566
hold on;
area([x x(1)],[y y(1)],'FaceColor',[1 0 0])
Is there any way to avoid this line?
BTW: the ginputExtra method call I use..
function [x y] = ginputExtra(n,booText)
% INPUT
% n: Number of points to plot
% booText: Boolean (default false) command to display point number in
% the plot.
% Author: Lasse Nørfeldt (Norfeldt)
% Date: 2012-04-09
if nargin ==2
bText = booText;
else
bText = false;
end
H = gca;
set(H, 'YLimMode', 'manual'); set(H, 'XLimMode', 'manual');
set(H, 'YLim', get(H,'YLim')); set(H, 'XLim', get(H,'XLim'));
numPoints = n; xg = []; yg = [];
for i=1:numPoints
[xi yi] = ginput(1);
xg = [xg xi]; yg = [yg yi];
if i == 1
hold on;
plot(H, xg(i),yg(i),'ro');
if bText text(xg(i),yg(i),num2str(i),'FontSize',14); end
else
plot(xg([i-1:i]),yg([i-1:i]),'r');
if bText text(xg(i),yg(i),num2str(i),'FontSize',14); end
end
end
hold off;
x = xg; y = yg;
Your issue might be in plotting by area(), as it seems to be primarily for stacking several vecotrs. If you zoom out a bit and see a similar vertical line from the first point in the blue area, the area function is most likely the issue.
The function:
fill([x x(1)],[y y(1)],COLOR)
Might do the trick for you, as it plots a filled polygon.
/Thomas