how do i plot hysteresis using matlab? - matlab

I want to model memristor using its equation in exponential mode using Matlab . My aim is to just get the hysteresis plot(i-v plot) in Matlab. the equation is like
i=x^n*b*sinh(av)+m(exp(gv)-1)
x'=Af(x)h(v)
where f(x) is window function and h(v) is polynomial function, A is constant.
f(x)=1-(2x-1)^2
h(v)=cv+dv^3;
c and d are constant c<0 & d>0
a=2; b=0.01; g=4; n=4; A=25; m=0.001;
x is internal state of device..is it possible to get plot in matlab?
I have tried in matlab it is showing errors

This script I found on google after a very brief search:
http://webee.technion.ac.il/people/skva/Memristor%20Models/MATLAB/memristor.m
You can choose there what kind of model do you want to use (Nonlinear Ion Drift model in your case), the type of window function (yours is Jogelkar's I assume) and nonlinear voltage-current relation.
After modifying a bit their script you should get something like this:
b=0.01; g=4; n=4; a=2;A=25; m=0.001;
c=-1;d=4;%your constants
numOfPoints = 10000;
t = linspace(-1, 1,numOfPoints);
dt = t(2) - t(1);
volt = .003*sin(2*pi*t);
x = zeros(size(t));
curr = x;
for i=2:numOfPoints
x(i) = x(i-1) + A*(c*volt(i)+d*(volt(i))^3)*(1-(2*x(i-1)-1)^2)*dt;
curr(i)=x(i)^n*b*sinh(a*volt(i))+m*(exp(g*volt(i))-1);
end;
fig = figure(1);
plot(volt,curr);
xlabel('Voltage');ylabel('Current');
figure(fig);
Good luck!

Related

Ways to plot rectangular window function (u[n]-u[n-5]) in MATLAB

I am trying to plot the rectangular window function Graph in MATLAB for:-
x[n] = u[n] - u[n-5]
I have written the following MATLAB Code for the same:-
x = [ones(1,5), zeros(1,43)]
But, this works only for a specific number of points on a graph (for ex: 48 points for this graph)
I wanted to ask whether there is a better way to plot the rectangular window function plots in MATLAB for a discrete time signals? Thanks for the help:)
Calling your signal y,
x = [ones(1, 5), zeros(1, length(y) - 5)];
You may want to create a function for this:
x=#(n)double(floor(n)==ceil(n)&n>=0&n<=4);
nn=(-4:24)/4;
subplot(211);
stem(nn,x(nn));
subplot(212);
stem(nn,x(nn-1));
Notice that x() returns 0 for non-integer n, which may or may not be sensible depending on how you use the function.
Using Anonymous Functions/Function Handles
To create a discrete plot that has unit step function I usually like to declare the unit step beforehand and use that in larger function. Here I use anonymous functions/function handles which are indicated by the #() holding the input parameters. In this case the only input parameter is n. The vector N can then be passed to x() and it'll plot all the x[n] values respectively. Density can be used to play with the number of stems plotted as well as Start_Index and End_Index.
Start_Index = -10;
End_Index = 10;
Density = 1;
N = (Start_Index:Density:End_Index);
%Unit step function%
u = #(n) 1.0.*(n >= 0);
x = #(n) u(n) - u(n-5);
stem(N,x(N));
title('x[n] = u[n] - u[n-5]');
xlabel('[n]'); ylabel('x[n]');
ylim([0 1.1]);
grid on

Simulate a 2D point mass moving along y=x^2 in MATLAB

I have a mixed set of differential and algebraic equations for which I have found the analytical solution in MATLAB. It concerns a point mass moving along a 2D curve constrained by y=x^2.
How would I go about using an ode-solver in MATLAB (or something else if it's easier) to simulate the ball rolling over the curve? The animation I can do myself, I'm more concerned with finding the velocities, xd yd, for each consecutive step. That's where I kind of get lost.
These are the equations of motion which I've derived using Lagrange multipliers. Hence the lambda. The lambda is the reaction force. I can calculate the accelerations, xdd ydd, but I also need the velocities in the state if I want to properly simulate this, I assume.
% Symbolic functions
syms y x xd yd xdd ydd
syms m g lambda
% Parameters
A = [m 0 -2*x; 0 m 1; -2*x 1 0];
X = [xdd ydd lambda].';
b = [0 -m*g -2*xd^2].';
sol = A\b % these are the states stored in X
So if you work out your problem using the lagrancian you would get the following formula seen below (see https://physics.stackexchange.com/questions/47154/ball-rolling-in-a-parabolic-bowl). The k-value comes from y=kx^2 (can be 1 for your example).
So rewrite this in the following form.
Now you just use
ddx= Formula seen above..
x = x + dx *dt
dx = dx + ddx *dt
t = t + dt
y = k*x*x
You make a loop with a sufficient small dt, and update you x-position velocity and acceleration.
Now you need
to specify the following starting values -> x0 dx0 ddx0 and dt.
I hope this helped
Cheers:)

Get the points from a MatLab fit object plot

I am a Matlab amateur so please bear with me -
I currently use Matlab to fit a complex equation to two-dimensional data. Right now I have a program which uses f = fit(xdata, ydata, function, options) to generate a fit object.
I can then use confint(f) and f.parameter etc. to get the fitted coefficients and confidence intervals, and I can use plot(f,x,y) to make a plot of the data and the fit.
From that point on the only way I know how to get the points which were plotted is to use the brush(?) tool and select all of the line, then copy the data to clipboard and paste it into excel or some such thing. I would much rather get those points directly from Matlab, perhaps into an array, but I have no idea how.
Can any MatLab veteran tell me if what I want is even possible? It would be very difficult due to the complexity of my equation to plot those points myself, but I will if need be (it can take ~30 minutes to do this fit and my computer is no slouch).
Since you have not shared any code or data, I use an example from MATLAB documentation:
load franke
f = fit([x, y],z,'poly23');
plot(f,[x,y],z)
So as you can sew, it first loads a dataset including x,y,z vectors. Then fits a surface to the data using 'poly23'. In your case it can be different sets of vectors and function and still as you said you will get the f function.
Now we can take a look at the function f
>> f
Linear model Poly23:
f(x,y) = p00 + p10*x + p01*y + p20*x^2 + p11*x*y + p02*y^2 + p21*x^2*y
+ p12*x*y^2 + p03*y^3
Coefficients (with 95% confidence bounds):
p00 = 1.118 (0.9149, 1.321)
p10 = -0.0002941 (-0.000502, -8.623e-05)
p01 = 1.533 (0.7032, 2.364)
p20 = -1.966e-08 (-7.084e-08, 3.152e-08)
p11 = 0.0003427 (-0.0001009, 0.0007863)
p02 = -6.951 (-8.421, -5.481)
p21 = 9.563e-08 (6.276e-09, 1.85e-07)
p12 = -0.0004401 (-0.0007082, -0.0001721)
p03 = 4.999 (4.082, 5.917)
It shows you the form of the function and the coefficients. So you can use it as follows:
zz = f(x,y);
To make sure you can plot the data again:
figure;
scatter3(x,y,zz,'.k');
hold on
scatter3(x,y,z,'.');
When you call f = fit(xdata, ydata, function, options), function name decides the equation. See list of official equations.
Simply iterate through data points and compute results using corresponding polynomial. So in your case lets say if function=poly2 you'll be doing computation as follows:
#Fit your data
f = fit([xdata, ydata],'poly2');
#Print name of coefficients (Just for Verification)
coeffnames(f)
#Fetch values of coefficients like p1, p2, ...
p = coeffvalues(c)
#Compute output points from min(xdata) to max(xdata) spaced at deltaX
deltaX = 0.1;
x = [min(xdata):deltaX:max(xdata)];
Y = p(1)*x^2+p(2)*x+p(3); #This is equation for function
I understand there can be alternate complex Java code to iterate through objects on a matlab figure and plot its value but using equations is a quick and valid approach.

MATLAB how do I plot my Runge-Kutta4 ODE solution on whole interval

I made this code for ODE solutions using Runge-Kutta4:
function y=myODE(f,y0,x0,h,x_final)
x=x0;
y=y0;
while x<x_final
h=min(h,x_final-x);
k1=f(x,y);
k2=f(x+h/2,y+h*k1/2);
k3=f(x+h/2,y+h*k2/2);
k4=f(x+h,y+h*k3);
y=y+(h/6)*(k1+2*k2+2*k3+k4)
x=x+h;
end
f is the function y' = f(x,y), y0 is initial value, x0 is where the function starts, h subinterval and x_final is where the function stops.
I tried my code and it solves ODEs for me correctly, but I also want to plot my function over a xy-axis on the interval x0 to x_final with h subintervals. When I try to plot it using plot(x0:h:x_final,y) I only get an empty graph. I understand (guessing) that I have to bind my y to several x in order to plot, but how can I do that without changing my code too much?
How can I plot the graph for y given y0, interval x0 to x_final and given h?
New to MATLAB, appreciate all help I can get!
Edit: To make clear what my code is for;
I need this ODE solver both for solution and graphing. I'm supposed to study the truncation error by looking at values of y on h compared to 2*h and the stability of Runge-Kutta4 by looking at graphs of y with different h.
This is not a very smart refactoring of your code (because it will slow down the solving, also will kill you graphics depending on how many steps you have in your ODE) but I'm sleepy so I go for the hack:
function y=myODE(f,y0,x0,h,x_final)
hold(axes('Parent',figure),'on');
x=x0;
y=y0;
plot(x,y, 'o');
while x<x_final
h=min(h,x_final-x);
k1=f(x,y);
k2=f(x+h/2,y+h*k1/2);
k3=f(x+h/2,y+h*k2/2);
k4=f(x+h,y+h*k3);
y=y+(h/6)*(k1+2*k2+2*k3+k4);
x=x+h;
plot(x,y,'o');
end;
end
Maybe tomorrow I'll re-write this answer to something proper, but—for now—good-night! :-)
function y=myode(f,y0,x0,h,x_final)
x=x0;
y=y0;
plot(x0,y0,'.')
hold on
while x<x_final
h=min(h,x_final-x);
k1=f(x,y);
k2=f(x+h/2,y+h*k1/2);
k3=f(x+h/2,y+h*k2/2);
k4=f(x+h,y+h*k3);
y=y+(h/6)*(k1+2*k2+2*k3+k4);
x=x+h;
plot(x,y,'.')
disp([x,y])
end
The comment box didn't let me to put my fixed-code in "code-format" so post it as an answer.
I would suggest you store the x and y values to vectors and plot them outside the loop. You may want to also output bigX and bigY in order to compare with the exact solution.
function y=myODE(f,y0,x0,h,x_final)
% Example:
% f = #(x,y) (x.^2+cos(y));
% y_final = myODE(f,0,0,0.1,2);
x=x0;
y=y0;
bigX = x0:h:x_final;
if bigX(end)<x_final
% Doesn't occur when x_final = n*h for some integer n
bigX = [bigX,x_final];
end
bigY = zeros(size(bigX));
count = 1;
bigY(1) = y0;
while x<x_final
h=min(h,x_final-x);
k1=f(x,y);
k2=f(x+h/2,y+h*k1/2);
k3=f(x+h/2,y+h*k2/2);
k4=f(x+h,y+h*k3);
y=y+(h/6)*(k1+2*k2+2*k3+k4);
x=x+h;
count = count+1;
bigY(count) = y;
end
plot(bigX,bigY,'b-o')
xlabel('x')
ylabel('y')

Exponential Curve Fitting in Matlab

I have a data-set which is loaded into matlab. I need to do exponential fitting for the plotted curve without using the curve fitting tool cftool.
I want to do this manually through executing a code/function that will output the values of a and b corresponding to the equation:
y = a*exp(b*x)
Then be using those values, I will do error optimization and create the best fit for the data I have.
Any help please?
Thanks in advance.
Try this...
f = fit(x,y,'exp1');
I think the typical objective in this type of assignment is to recognize that by taking the log of both sides, various methods of polynomial fit approaches can be used.
ln(y) = ln(a) + ln( exp(x).^b )
ln(y) = ln(a) + b * ln( exp(x) )
There can be difficulties with this approach when errors such as noise are involved due to the behavior of ln as it approaches zero.
In this exercise I have a set of data that present an exponential curve and I want to fit them exponentially and get the values of a and b. I used the following code and it worked with the data I have.
"trail.m" file:
%defining the data used
load trialforfitting.txt;
xdata= trialforfitting(:,1);
ydata= trialforfitting(:,2);
%calling the "fitcurvedemo" function
[estimates, model] = fitcurvedemo(xdata,ydata)
disp(sse);
plot(xdata, ydata, 'o'); %Data curve
hold on
[sse, FittedCurve] = model(estimates);
plot(xdata, FittedCurve, 'r')%Fitted curve
xlabel('Voltage (V)')
ylabel('Current (A)')
title('Exponential Fitting to IV curves');
legend('data', ['Fitting'])
hold off
"fitcurvedemo.m" file:
function [estimates, model] = fitcurvedemo(xdata, ydata)
%Call fminsearch with a random starting point.
start_point = rand(1, 2);
model = #expfun;
estimates = fminsearch(model, start_point);
%"expfun" accepts curve parameters as inputs, and outputs
%the sum of squares error [sse] expfun is a function handle;
%a value that contains a matlab object methods and the constructor
%"FMINSEARCH" only needs sse
%estimate returns the value of A and lambda
%model computes the exponential function
function [sse, FittedCurve] = expfun(params)
A = params(1);
lambda = params(2);
%exponential function model to fit
FittedCurve = A .* exp(lambda * xdata);
ErrorVector = FittedCurve - ydata;
%output of the expfun function [sum of squares of error]
sse = sum(ErrorVector .^ 2);
end
end
I have a new set of data that doesn't work with this code and give the appropriate exponential fit for the data curve plotted.