How do I plot the output of a system with an impulse response in matlab? - matlab

I am very new to matlab and need to plot y1[n] = x[n] + y1[n − 1] where x[n] = [1,2,4] and an impulse response, h[n] = [1,1,1,1,1] and am not sure if I have went about it the right way
My code so far is
x = [1,2,4];
h = [1,1,1,1,1];
y = [];
for n=1:length(x)
if (n==1)
y(n) = x(n);
else
y(n) = (x(n)*h(n)) + (y(n-1)*h(n));
end
end
stem(y);
Please note that I cannot use the conv() function

I don't really know why it got so complicated,
x = [1,2,4];
h = [1,1,1,1,1];
y = [];
lh = length(h);
lx = length(x);
t = -lh - lx : lh + lx;
x(end + 1 : end + lh + 1) = 0;
h(end + 1 : end + lx + 1) = 0;
x = padarray(x,[0 max(t)],'pre');
h = padarray(h,[0 max(t)],'pre');
xinv = x(end:-1:1);
for n = 1 : length(t)
xinv = circshift(xinv,[0 1]);
y(n) = sum(xinv .* h);
end
y = circshift(y,[0 find(t == 0)]);
subplot(311)
stem(t,x);
xlim([-10 10])
subplot(312)
stem(t,h);
xlim([-10 10])
subplot(313)
stem(t,y);
xlim([-10 10])
It works fine but I believe it can be coded in a more simpler way.

Can you use fft?
lx = numel(x);
lh = numel(h);
m = max(lx, lh);
y = ifft(fft([h zeros(1,max(lx-lh,0)+m)]) .* fft([x zeros(1,max(lh-lx,0)+m)]));
y = y(1:lx+lh-1);

Related

Matlab newton method with finite differences

I would like some help with my program. I still don’t understand where my problem is, since it’s kind of a big mess. So it consists of the main program:
function x = NewtonM(funcF,JacF)
x= zeros(2,1);
x(1) = 1
x(2) = 5
k = 1;
kmax = 100;
TOL = 10^(-7);
while k < kmax
s = J(x)\(-F(x));
x= x + s
if (norm(s,2)< TOL)
break;
endif
end
and these are the fellow functions:
function y = F(x)
x1 = x(1);
x2 = x(2);
y = zeros(2,1);
y(1) = x1+x2-3;
y(2) = x1^2 + x2^2 -9;
end
function z = Z(x)
x1 = x(1);
x2 = x(2);
z = zeros(3,1);
z(1) = x1+x2-3+10^(-7);
z(2) = (x1+10^(-7))^2 + x2^2 -9;
z(3) = x1^2 + (x2+10^(-7))^2 -9;
end
function J = J(x)
x1 = x(1);
x2 = x(2);
J = zeros(2,2);
J(1,1) = (Z(1)-F(1))/(10^(-7))
J(1,2) = (Z(1)-F(1))/(10^(-7))
J(2,1) = (Z(2)-F(2))/(10^(-7))
J(2,2) = (Z(3)-F(2))/(10^(-7))
end
These are the error messages:
The problem is that you are calling both Z and F with only one input, in the function J.
Then, the first thing you do is try to interpret the input as a 2 valued array (x1,x2) but they don't exist, as you defined x as e.g. 1, by doing Z(1).
I wonder if instead of using Z(1) etc, you meant to do z=Z(x) and then use z(1), inside J.

Steepest Descent using Armijo rule

I want to determine the Steepest descent of the Rosenbruck function using Armijo steplength where x = [-1.2, 1]' (the initial column vector).
The problem is, that the code has been running for a long time. I think there will be an infinite loop created here. But I could not understand where the problem was.
Could anyone help me?
n=input('enter the number of variables n ');
% Armijo stepsize rule parameters
x = [-1.2 1]';
s = 10;
m = 0;
sigma = .1;
beta = .5;
obj=func(x);
g=grad(x);
k_max = 10^5;
k=0; % k = # iterations
nf=1; % nf = # function eval.
x_new = zeros([],1) ; % empty vector which can be filled if length is not known ;
[X,Y]=meshgrid(-2:0.5:2);
fx = 100*(X.^2 - Y).^2 + (X-1).^2;
contour(X, Y, fx, 20)
while (norm(g)>10^(-3)) && (k<k_max)
d = -g./abs(g); % steepest descent direction
s = 1;
newobj = func(x + beta.^m*s*d);
m = m+1;
if obj > newobj - (sigma*beta.^m*s*g'*d)
t = beta^m *s;
x = x + t*d;
m_new = m;
newobj = func(x + t*d);
nf = nf+1;
else
m = m+1;
end
obj=newobj;
g=grad(x);
k = k + 1;
x_new = [x_new, x];
end
% Output x and k
x_new, k, nf
fprintf('Optimal Solution x = [%f, %f]\n', x(1), x(2))
plot(x_new)
function y = func(x)
y = 100*(x(1)^2 - x(2))^2 + (x(1)-1)^2;
end
function y = grad(x)
y(1) = 100*(2*(x(1)^2-x(2))*2*x(1)) + 2*(x(1)-1);
end

MATLAB: Linear Poisson Solver using iterative method

I am in the process of writing a 2D non-linear Poisson's solver. One intermediate test I performed is using my non-linear solver to solve for a "linear" Poisson equation. Unfortunately, my non-linear solver is giving me incorrect results, unlike if I try to solve it directly in MATLAB using the backslash ""
non-linear solver iteratively code: "incorrect results"
clearvars; clc; close all;
Nx = 20;
Ny = 20;
Lx = 2*pi;
x = (0:Nx-1)/Nx*2*pi; % x coordinate in Fourier, equally spaced grid
kx = fftshift(-Nx/2:Nx/2-1); % wave number vector
kx(kx==0) = 1; %helps with error: matrix ill scaled because of 0s
ygl = -cos(pi*(0:Ny)/Ny)'; %Gauss-Lobatto chebyshev points
%make mesh
[X,Y] = meshgrid(x,ygl);
%Chebyshev matrix:
VGL = cos(acos(ygl(:))*(0:Ny));
dVGL = diag(1./sqrt(1-ygl.^2))*sin(acos(ygl)*(0:Ny))*diag(0:Ny);
dVGL(1,:) = (-1).^(1:Ny+1).*(0:Ny).^2;
dVGL(Ny+1,:) = (0:Ny).^2;
%Diferentiation matrix for Gauss-Lobatto points
Dgl = dVGL/VGL;
D = Dgl; %first-order derivative matrix
D2 = Dgl*Dgl;
%linear Poisson solved iteratively
Igl = speye(Ny+1);
Ig = speye(Ny);
ZNy = diag([0 ones(1,Ny-1) 0]);
div_x_act_on_grad_x = -Igl; % must be multiplied with kx(m)^2 for each Fourier mode
div_y_act_on_grad_y = D * ZNy *D;
u = Y.^2 .* sin( (2*pi / Lx) * X);
uh = fft(u,[],2);
uold = ones(size(u));
uoldk = fft(uold,[],2);
max_iter = 500;
err_max = 1e-5; %change to 1e-8;
for iterations = 1:max_iter
for m = 1:length(kx)
L = div_x_act_on_grad_x * (kx(m)^2) + div_y_act_on_grad_y;
d2xk = div_x_act_on_grad_x * (kx(m)^2) * uoldk;
d2x = real(ifft(d2xk,[],2));
d2yk = div_y_act_on_grad_y *uoldk;
d2y = real(ifft(d2yk,[],2));
ffh = d2xk + d2yk;
phikmax_old = max(max(abs(uoldk)));
unewh(:,m) = L\(ffh(:,m));
end
phikmax = max(max(abs(unewh)));
if phikmax == 0 %norm(unewh,inf) == 0
it_error = err_max /2;
else
it_error = abs( phikmax - phikmax_old) / phikmax;
end
if it_error < err_max
break;
end
end
unew = real(ifft(unewh,[],2));
DEsol = unew - u;
figure
surf(X, Y, unew);
colorbar;
title('Numerical solution of \nabla^2 u = f');
figure
surf(X, Y, u);
colorbar;
title('Exact solution of \nabla^2 u = f');
Direct solver
ubar = Y.^2 .* sin( (2*pi / Lx) * X);
uh = fft(ubar,[],2);
for m = 1:length(kx)
L = div_x_act_on_grad_x * (kx(m)^2) + div_y_act_on_grad_y;
d2xk = div_x_act_on_grad_x * (kx(m)^2) * uh;
d2x = real(ifft(d2xk,[],2));
d2yk = div_y_act_on_grad_y *uh;
d2y = real(ifft(d2yk,[],2));
ffh = d2xk + d2yk;
%----------------
unewh(:,m) = L\(ffh(:,m));
end
How can I fix code 1 to get the same results as code 2?

system of equation Runge-Kutta 4th order for system of equation using matlab [duplicate]

This question already has answers here:
Solve a system of equations with Runge Kutta 4: Matlab
(2 answers)
Closed 4 years ago.
I need to do matlab code to solve the system of equation by using Runge-Kutta method 4th order but in every try i got problem and can't solve
the derivative is
(d^2 y)/dx^(2) +dy/dx-2y=0
, h=0.1 Y(0)=1 , dy/dx (0)=-2
{clear all, close all, clc
%{
____________________TASK:______________________
Solve the system of differential equations below
in the interval 0<x<1, with stepsize h = 0.1.
y= y1 y(0)=0
y3= 2y1-y2 y2(0)=-2
_______________________________________________
%}
h = 0.1;
x = 0:h:1
N = length(x);
y = zeros(N,1);
y3 = zeros(N,1);
g = #(x, y, y1, y2) y1;
f = #(x, y, y1, y2) 2*y1-y2;
y1(1) = 0;
y2(1) =-2;
for i = 1:(N-1)
k_1 = x(i)+y(i)
k_11=g(x(i),y,y(i))
k_2 = (x(i)+h/2)+(y(i)+0.5*h*k_1)
k_22=g((x(i)+0.5*h),y,(y(i)+0.5*h*k_11))
k_3 = (x(i)+h/2)+(y(i)+0.5*h*k_2)
k_33=g((X(i)+0.5*h),y,(y(i)+0.5*h*k_22));
k_4 = (x(i)+h)+(y(i)+h*k_33)
k_44=g((x(i)+h),y,(y(i)+k_33*h));
y3(i+1) = y(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h
y3(:,i)=y;
end
Answer_Matrix = [x' y3 ];}
You used functions, that's not really necessary, but it might be easier that way to see the formula more clearly. In your functions however, you list arguments that used present in the function. That's not needed, and creates unwanted overhead.
In your initial conditions you should use y and y3, since that are the ones you use in the loop. Also in the first condition you've made a typo.
In the loop you forget to call the function f, and to update the y vector.
Making these changes in your code results in the following:
h = 0.1;
x = 0:h:1;
N = length(x);
y = zeros(N,1);
y3 = zeros(N,1);
g = #(y2) y2;
f = #(y1, y2) 2*y1-y2;
y(1) = 1;
y3(1) = -2;
for i = 1:(N-1)
k_1 = f(y(i), y3(i));
k_11 = g(y3(i));
k_2 = f(y(i)+0.5*h*k_1, y3(i) +0.5*h*k_11);
k_22 = g((y3(i)+0.5*h*k_11));
k_3 = f(y(i)+0.5*h*k_2, y3(i) +0.5*h*k_22);
k_33 = g((y3(i)+0.5*h*k_22));
k_4 = f(y(i)+h*k_3, y3(i) +h*k_33);
k_44 = g((y3(i)+h*k_33));
y3(i+1) = y3(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h ;
y(i+1) = y(i) + (1/6)*(k_11+2*k_22+2*k_33+k_44)*h ;
end
Answer_Matrix = [x' y];
% solution of DE is exp(-2x) and is plotted as reference
plot(x,y,x,exp(-2*x))
As mentioned before, you can also solve this without the use of functions:
h = .1;
x = 0:h:1;
N = length(x);
% allocate memory
y = zeros(N,1);
z = zeros(N,1);
% starting values
y(1) = 1;
z(1) = -2;
for i=1:N-1
ky1 = z(i);
kz1 = -z(i) + 2*y(i);
ky2 = z(i) + h/2*kz1;
kz2 = -z(i) - h/2*kz1 + 2*y(i) + 2*h/2*ky1;
ky3 = z(i) + h/2*kz2;
kz3 = -z(i) - h/2*kz2 + 2*y(i) + 2*h/2*ky2;
ky4 = z(i) + h*kz3;
kz4 = -z(i) - h*kz3 + 2*y(i) + 2*h*ky3;
y(i+1) = y(i) + h/6*(ky1 + 2*ky2 + 2*ky3 + ky4);
z(i+1) = z(i) + h/6*(kz1 + 2*kz2 + 2*kz3 + kz4);
end
% exp(-2*x) is solution of DE and is plotted as reference
plot(x,y,x,exp(-2*x))

Make the heart bounce in and out

I was able to make a heart in matlab as:
n=100;
x=linspace(-3,3,n);
y=linspace(-3,3,n);
z=linspace(-3,3,n);
[X,Y,Z]=ndgrid(x,y,z);
F=((-(X.^2) .* (Z.^3) -(9/80).*(Y.^2).*(Z.^3)) + ((X.^2) + (9/4).* (Y.^2) + (Z.^2)-1).^3);
isosurface(F,0)
lighting phong
axis equal
Would it be possible to make it bounce in and out? What approach might be taken?
try this
step = 0.05;
x = -1.5 : step : 1.5;
y = -1 : step : 1;
z = -1.5 : step : 1.5;
[X,Y,Z] = meshgrid(x, y, z);
f = (X.^2 + 9/4 .* Y.^2 + Z.^2 - 1).^3 - X.^2 .* Z.^3 - 9/80 .* Y.^2 .* Z.^3;
isosurface(X,Y,Z,f,0)
axis tight
axis equal
colormap flag
axis manual
ax = gca;
k=1.25;
ax.XLim = ax.XLim*k;
ax.YLim = ax.YLim*k;
ax.ZLim = ax.ZLim*k;
tempLims.XLim = ax.XLim;
tempLims.YLim = ax.YLim;
tempLims.ZLim = ax.ZLim;
t=0;
heartData = sin((1:250)/100*2*pi)/6.*hamming(250)';
heartData(251:400) = 0;
while 1
t=t+1;
t=mod(t, length(heartData))+1;
k = 1 + heartData(t);
ax.XLim = tempLims.XLim * k;
ax.YLim = tempLims.YLim * k;
ax.ZLim = tempLims.XLim * k;
pause(0.01);
end