Tag Archives: matlab
interpreting xcorr for time series plots
i’m using xcorr to work out the lag between two time series.
When I plot the results of xcorr, and ask it to return the maximum lag, the result I get is -58.3.
This is the maximum positive c value, but the spike at 0 into negative c values is the largest overall – is this the result i should be using instead?i’m using xcorr to work out the lag between two time series.
When I plot the results of xcorr, and ask it to return the maximum lag, the result I get is -58.3.
This is the maximum positive c value, but the spike at 0 into negative c values is the largest overall – is this the result i should be using instead? i’m using xcorr to work out the lag between two time series.
When I plot the results of xcorr, and ask it to return the maximum lag, the result I get is -58.3.
This is the maximum positive c value, but the spike at 0 into negative c values is the largest overall – is this the result i should be using instead? xcorr, correlation, lag MATLAB Answers — New Questions
What is the duration of Mathworks Matlab Online student license?
Hello, I use Matlab online for programming. I have run out on my 20 hours per month limit and would like to purchase a basic student version which is USD 115. Please advise me upon the duration of this license – month, year or perpetual? And does it have a limit ont he number of hours per month or unlimited?Hello, I use Matlab online for programming. I have run out on my 20 hours per month limit and would like to purchase a basic student version which is USD 115. Please advise me upon the duration of this license – month, year or perpetual? And does it have a limit ont he number of hours per month or unlimited? Hello, I use Matlab online for programming. I have run out on my 20 hours per month limit and would like to purchase a basic student version which is USD 115. Please advise me upon the duration of this license – month, year or perpetual? And does it have a limit ont he number of hours per month or unlimited? mathworks, matlab online, license duration MATLAB Answers — New Questions
How do I manually configure my network license file for the Network License Manager?
How do I manually configure my network license file for the Network License Manager? How do I manually configure my network license file for the Network License Manager? How do I manually configure my network license file for the Network License Manager? MATLAB Answers — New Questions
Model_X has multiple sample times error
I am getting the following error
‘MyTopLevelModel/SubsystemA/Model’ has multiple sample times. Only constant (inf) or inherited (-1) sample times are allowed in function call subsystem ‘MyTopLevelModel/SubsystemA’.
More info of my setup
SubsystemA has a function call which has a trigger port connected to a port set as "output function call with sample time of 0.001. All my other blocks have sample time -1 (inheritet).
If I go to the model explorer the compiled sample time are not [-1 0] some of the have set the [0.001 0]
Any idea what could be causing this error ?I am getting the following error
‘MyTopLevelModel/SubsystemA/Model’ has multiple sample times. Only constant (inf) or inherited (-1) sample times are allowed in function call subsystem ‘MyTopLevelModel/SubsystemA’.
More info of my setup
SubsystemA has a function call which has a trigger port connected to a port set as "output function call with sample time of 0.001. All my other blocks have sample time -1 (inheritet).
If I go to the model explorer the compiled sample time are not [-1 0] some of the have set the [0.001 0]
Any idea what could be causing this error ? I am getting the following error
‘MyTopLevelModel/SubsystemA/Model’ has multiple sample times. Only constant (inf) or inherited (-1) sample times are allowed in function call subsystem ‘MyTopLevelModel/SubsystemA’.
More info of my setup
SubsystemA has a function call which has a trigger port connected to a port set as "output function call with sample time of 0.001. All my other blocks have sample time -1 (inheritet).
If I go to the model explorer the compiled sample time are not [-1 0] some of the have set the [0.001 0]
Any idea what could be causing this error ? error, time MATLAB Answers — New Questions
Error displayed when starting MATLAB on Linux systems using NVIDIA OR AMD graphics hardware
I’m using Dell precision 7510 with preinstalled Ubuntu 14.04(I have the driver the NVIDIA). I just downloaded the MATLAB R2017a and I run into the following error. I just searched and found it’s not just me who have the same problem. I wonder if this problem is fixable? To put it in another way, could I use all the features provided by MATALB with this error? Additionally, the error also occurs when I use a Linux Ubuntu 17.10 or 18.04 system that has AMD graphics hardware.
Thank you in advance, attached is the error information:
com.jogamp.opengl.GLException: X11GLXDrawableFactory – Could not initialize shared resources for X11GraphicsDevice[type .x11, connection :0, unitID 0, handle 0x0, owner false, ResourceToolkitLock[obj 0x413b9df1, isOwner false, [count 0, qsz 0, owner ]]] at jogamp.opengl.x11.glx.X11GLXDrawableFactory$SharedResourceImplementation.createSharedResource(X11GLXDrawableFactory.java:326) at jogamp.opengl.SharedResourceRunner.run(SharedResourceRunner.java:297) at java.lang.Thread.run(Unknown Source) Caused by: com.jogamp.opengl.GLException: glXGetConfig(0x1) failed: error code Unknown error code 6 at jogamp.opengl.x11.glx.X11GLXGraphicsConfiguration.glXGetConfig(X11GLXGraphicsConfiguration.java:570) at jogamp.opengl.x11.glx.X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(X11GLXGraphicsConfiguration.java:500) at jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationXVisual(X11GLXGraphicsConfigurationFactory.java:434) at jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(X11GLXGraphicsConfigurationFactory.java:240) at jogamp.opengl.x11.glx.X11GLXDrawableFactory.createMutableSurfaceImpl(X11GLXDrawableFactory.java:524) at jogamp.opengl.x11.glx.X11GLXDrawableFactory.createDummySurfaceImpl(X11GLXDrawableFactory.java:535) at jogamp.opengl.x11.glx.X11GLXDrawableFactory$SharedResourceImplementation.createSharedResource(X11GLXDrawableFactory.java:283) … 2 moreI’m using Dell precision 7510 with preinstalled Ubuntu 14.04(I have the driver the NVIDIA). I just downloaded the MATLAB R2017a and I run into the following error. I just searched and found it’s not just me who have the same problem. I wonder if this problem is fixable? To put it in another way, could I use all the features provided by MATALB with this error? Additionally, the error also occurs when I use a Linux Ubuntu 17.10 or 18.04 system that has AMD graphics hardware.
Thank you in advance, attached is the error information:
com.jogamp.opengl.GLException: X11GLXDrawableFactory – Could not initialize shared resources for X11GraphicsDevice[type .x11, connection :0, unitID 0, handle 0x0, owner false, ResourceToolkitLock[obj 0x413b9df1, isOwner false, [count 0, qsz 0, owner ]]] at jogamp.opengl.x11.glx.X11GLXDrawableFactory$SharedResourceImplementation.createSharedResource(X11GLXDrawableFactory.java:326) at jogamp.opengl.SharedResourceRunner.run(SharedResourceRunner.java:297) at java.lang.Thread.run(Unknown Source) Caused by: com.jogamp.opengl.GLException: glXGetConfig(0x1) failed: error code Unknown error code 6 at jogamp.opengl.x11.glx.X11GLXGraphicsConfiguration.glXGetConfig(X11GLXGraphicsConfiguration.java:570) at jogamp.opengl.x11.glx.X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(X11GLXGraphicsConfiguration.java:500) at jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationXVisual(X11GLXGraphicsConfigurationFactory.java:434) at jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(X11GLXGraphicsConfigurationFactory.java:240) at jogamp.opengl.x11.glx.X11GLXDrawableFactory.createMutableSurfaceImpl(X11GLXDrawableFactory.java:524) at jogamp.opengl.x11.glx.X11GLXDrawableFactory.createDummySurfaceImpl(X11GLXDrawableFactory.java:535) at jogamp.opengl.x11.glx.X11GLXDrawableFactory$SharedResourceImplementation.createSharedResource(X11GLXDrawableFactory.java:283) … 2 more I’m using Dell precision 7510 with preinstalled Ubuntu 14.04(I have the driver the NVIDIA). I just downloaded the MATLAB R2017a and I run into the following error. I just searched and found it’s not just me who have the same problem. I wonder if this problem is fixable? To put it in another way, could I use all the features provided by MATALB with this error? Additionally, the error also occurs when I use a Linux Ubuntu 17.10 or 18.04 system that has AMD graphics hardware.
Thank you in advance, attached is the error information:
com.jogamp.opengl.GLException: X11GLXDrawableFactory – Could not initialize shared resources for X11GraphicsDevice[type .x11, connection :0, unitID 0, handle 0x0, owner false, ResourceToolkitLock[obj 0x413b9df1, isOwner false, [count 0, qsz 0, owner ]]] at jogamp.opengl.x11.glx.X11GLXDrawableFactory$SharedResourceImplementation.createSharedResource(X11GLXDrawableFactory.java:326) at jogamp.opengl.SharedResourceRunner.run(SharedResourceRunner.java:297) at java.lang.Thread.run(Unknown Source) Caused by: com.jogamp.opengl.GLException: glXGetConfig(0x1) failed: error code Unknown error code 6 at jogamp.opengl.x11.glx.X11GLXGraphicsConfiguration.glXGetConfig(X11GLXGraphicsConfiguration.java:570) at jogamp.opengl.x11.glx.X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(X11GLXGraphicsConfiguration.java:500) at jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationXVisual(X11GLXGraphicsConfigurationFactory.java:434) at jogamp.opengl.x11.glx.X11GLXGraphicsConfigurationFactory.chooseGraphicsConfigurationStatic(X11GLXGraphicsConfigurationFactory.java:240) at jogamp.opengl.x11.glx.X11GLXDrawableFactory.createMutableSurfaceImpl(X11GLXDrawableFactory.java:524) at jogamp.opengl.x11.glx.X11GLXDrawableFactory.createDummySurfaceImpl(X11GLXDrawableFactory.java:535) at jogamp.opengl.x11.glx.X11GLXDrawableFactory$SharedResourceImplementation.createSharedResource(X11GLXDrawableFactory.java:283) … 2 more linux, ubuntu, amd, graphics, hardware, nvidia MATLAB Answers — New Questions
Change format of field contour labels that have been manually added in a tiled layout
Hi,
Trying to manually add contour labels over a filled contour plot over a narrow range of values.
Matlab returns the error:
Error using hgconvertunits
The reference object is invalid.
Any ideas how I can manually add labels to a tiledlayout?
I also assume there is no workaround for avoiding the contours from striking through the labels when added manually?
Thank you
a = 0.98;
b = 1.02;
Z = round(((b-a).*rand(99,99) + a),2);
XY = [-0.375:.125:.375];
no_levels = 8;
npoints = [99 99]; % define improved resolution
Xfine = linspace(XY(1),XY(end),npoints(1)); % y coords
Yfine = linspace(XY(1),XY(end),npoints(2)); % z coords
[Xfine Yfine] = meshgrid(Xfine,Yfine); % create mesh
tiledlayout(1,2)
for i = 1:2
nexttile(1)
[C,H] = contourf(Xfine,Yfine,Z,no_levels,’-‘);
% clabel(C,H,’interpreter’,’latex’,’FontSize’,14);
% H.LevelList = round(H.LevelList,1); % rounds levels to 1st decimal place
clabel(C,H,"manual",’FontSize’, 22)
hold on
ylim([-0.5 0.5]);
y = ylim;
yticks([y(1):.25:y(2)])
xticks([-.5:.25:.5])
xlim([-.55 .55])
axis square
endHi,
Trying to manually add contour labels over a filled contour plot over a narrow range of values.
Matlab returns the error:
Error using hgconvertunits
The reference object is invalid.
Any ideas how I can manually add labels to a tiledlayout?
I also assume there is no workaround for avoiding the contours from striking through the labels when added manually?
Thank you
a = 0.98;
b = 1.02;
Z = round(((b-a).*rand(99,99) + a),2);
XY = [-0.375:.125:.375];
no_levels = 8;
npoints = [99 99]; % define improved resolution
Xfine = linspace(XY(1),XY(end),npoints(1)); % y coords
Yfine = linspace(XY(1),XY(end),npoints(2)); % z coords
[Xfine Yfine] = meshgrid(Xfine,Yfine); % create mesh
tiledlayout(1,2)
for i = 1:2
nexttile(1)
[C,H] = contourf(Xfine,Yfine,Z,no_levels,’-‘);
% clabel(C,H,’interpreter’,’latex’,’FontSize’,14);
% H.LevelList = round(H.LevelList,1); % rounds levels to 1st decimal place
clabel(C,H,"manual",’FontSize’, 22)
hold on
ylim([-0.5 0.5]);
y = ylim;
yticks([y(1):.25:y(2)])
xticks([-.5:.25:.5])
xlim([-.55 .55])
axis square
end Hi,
Trying to manually add contour labels over a filled contour plot over a narrow range of values.
Matlab returns the error:
Error using hgconvertunits
The reference object is invalid.
Any ideas how I can manually add labels to a tiledlayout?
I also assume there is no workaround for avoiding the contours from striking through the labels when added manually?
Thank you
a = 0.98;
b = 1.02;
Z = round(((b-a).*rand(99,99) + a),2);
XY = [-0.375:.125:.375];
no_levels = 8;
npoints = [99 99]; % define improved resolution
Xfine = linspace(XY(1),XY(end),npoints(1)); % y coords
Yfine = linspace(XY(1),XY(end),npoints(2)); % z coords
[Xfine Yfine] = meshgrid(Xfine,Yfine); % create mesh
tiledlayout(1,2)
for i = 1:2
nexttile(1)
[C,H] = contourf(Xfine,Yfine,Z,no_levels,’-‘);
% clabel(C,H,’interpreter’,’latex’,’FontSize’,14);
% H.LevelList = round(H.LevelList,1); % rounds levels to 1st decimal place
clabel(C,H,"manual",’FontSize’, 22)
hold on
ylim([-0.5 0.5]);
y = ylim;
yticks([y(1):.25:y(2)])
xticks([-.5:.25:.5])
xlim([-.55 .55])
axis square
end contour labels, tiledlayout MATLAB Answers — New Questions
how to reduce ripple
these are the current and voltage values of sepic converter( standalone).
these are the same current and voltages of sepic when connected to the input of grid connected inverter. how can reduce these ripples?these are the current and voltage values of sepic converter( standalone).
these are the same current and voltages of sepic when connected to the input of grid connected inverter. how can reduce these ripples? these are the current and voltage values of sepic converter( standalone).
these are the same current and voltages of sepic when connected to the input of grid connected inverter. how can reduce these ripples? how to reduc ripple in waveform MATLAB Answers — New Questions
How to perform Bonferroni correction on ttest2 comparison of two independent samples?
Hi all!
My question may be simple but I don’t get to perform Bonferroni correction on ttest2 comparison of two random independent samples with equal column number but different row number.
I want to perform ttest2 comparison between each column of my two samples, therefore getting 10 p-values (see example below). But i get the following error "Index in position 1 is invalid. Array indices must be positive integers or logical values".
Once I overcome this error, I would like to perform Bonferroni correction on ttest2 comparison.
So many thanks!!! I’m using Matlab R2022b
% Note that r1 and r2 differ in row number, not column number
r1 = randi(125,200,10); % Random sample 1
r2 = randi(155,100,10); % Random sample 2
% Perform ttest2 comparison, getting 10-pvalues by comparing the 10 columns of r1 and r2
[h,p,ci,stats] = ttest2(r1(i,:),r2(i,:)); % ttest2 comparison of two random, independent samples
results = multcompare(stats,"CriticalValueType","bonferroni") % Bonferroni correction on ttest2Hi all!
My question may be simple but I don’t get to perform Bonferroni correction on ttest2 comparison of two random independent samples with equal column number but different row number.
I want to perform ttest2 comparison between each column of my two samples, therefore getting 10 p-values (see example below). But i get the following error "Index in position 1 is invalid. Array indices must be positive integers or logical values".
Once I overcome this error, I would like to perform Bonferroni correction on ttest2 comparison.
So many thanks!!! I’m using Matlab R2022b
% Note that r1 and r2 differ in row number, not column number
r1 = randi(125,200,10); % Random sample 1
r2 = randi(155,100,10); % Random sample 2
% Perform ttest2 comparison, getting 10-pvalues by comparing the 10 columns of r1 and r2
[h,p,ci,stats] = ttest2(r1(i,:),r2(i,:)); % ttest2 comparison of two random, independent samples
results = multcompare(stats,"CriticalValueType","bonferroni") % Bonferroni correction on ttest2 Hi all!
My question may be simple but I don’t get to perform Bonferroni correction on ttest2 comparison of two random independent samples with equal column number but different row number.
I want to perform ttest2 comparison between each column of my two samples, therefore getting 10 p-values (see example below). But i get the following error "Index in position 1 is invalid. Array indices must be positive integers or logical values".
Once I overcome this error, I would like to perform Bonferroni correction on ttest2 comparison.
So many thanks!!! I’m using Matlab R2022b
% Note that r1 and r2 differ in row number, not column number
r1 = randi(125,200,10); % Random sample 1
r2 = randi(155,100,10); % Random sample 2
% Perform ttest2 comparison, getting 10-pvalues by comparing the 10 columns of r1 and r2
[h,p,ci,stats] = ttest2(r1(i,:),r2(i,:)); % ttest2 comparison of two random, independent samples
results = multcompare(stats,"CriticalValueType","bonferroni") % Bonferroni correction on ttest2 multcompare, bonferroni, ttest2, two independent samples MATLAB Answers — New Questions
When I close the figure or eeglab, the program becomes unresponsive
After updating MacOS to Sonoma 14.1, I noticed that the program becomes unresponsive when I close a figure or eeglab.
I tried reinstalling Matlab, but I still encountered the same issue. I suspect it might be related to the recent update.
Has anyone else experienced this situation?
More information:
Macbook Air M1, 512GB, 8G RAM
Matlab R2023b (Apple silicon)After updating MacOS to Sonoma 14.1, I noticed that the program becomes unresponsive when I close a figure or eeglab.
I tried reinstalling Matlab, but I still encountered the same issue. I suspect it might be related to the recent update.
Has anyone else experienced this situation?
More information:
Macbook Air M1, 512GB, 8G RAM
Matlab R2023b (Apple silicon) After updating MacOS to Sonoma 14.1, I noticed that the program becomes unresponsive when I close a figure or eeglab.
I tried reinstalling Matlab, but I still encountered the same issue. I suspect it might be related to the recent update.
Has anyone else experienced this situation?
More information:
Macbook Air M1, 512GB, 8G RAM
Matlab R2023b (Apple silicon) macos, sonoma, eeglab, figure MATLAB Answers — New Questions
How to solve for 1D non homogenous ODE by Finite element method
I am unable to input the dirichlet condition into this non homogenous ode. Please point out my mistake.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% -u" + u = – 5x + 4 0 < x <= 1 %%%%
%%%% u(0) = 0, u(1) = 2 %%%%
%%%% Exact solution u = (exp(x)*(3*exp(1) + 4))/(exp(2) – 1) – 5*x – (exp(-x)*(3*exp(1) + 4*exp(2)))/(exp(2) – 1) + 4 %%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all;
close all;
format long;
N = 20;
x0 = 0;
xN = 1;
h = 1/N;
for j = 1:N+1
X(j) = x0 + (j-1)*h;
end
f = @(x)(- 5*x +4);
A = zeros(N+1,N+1);
F = zeros(N+1,1);
%%%% Local stiffness matrix %%%%
a = [1/h -1/h ; -1/h 1/h] ;
for i=1:N
phi1 = @(x)(X(i+1)-x)/h; %%%% linear basis function %%%%
phi2 = @(x)(x-X(i))/h; %%%% linear basis function %%%%
f1 = @(x)f(x)*phi1(x); %%%% integrand for load vector %%%%
f2 = @(x)f(x)*phi2(x); %%%% integrand for load vector %%%%
v(1,i) = gauss(f1,X(i),X(i+1),1); %%%% element wise values of
v(2,i) = gauss(f2,X(i),X(i+1),1); %%%% load vector
end
%%%% Assembling %%%%
for i=1:N
A([i i+1],[i i+1]) = A([i i+1],[i i+1]) + a;
F([i i+1],1) = F([i i+1],1) + v([1 2],i);
end
%%%% Dirichlet Boundary condition %%%%
% F(N+1,1) = F(N+1,1)+2;
fullnodes = [1:N+1];
%%%%% Dirichlet boundary condition %%%%%
freenodes=setdiff(fullnodes,[1]);
Uh = zeros(N+1,1);
Uh(N+1,1) = 2;
%%%% Approximate solution %%%%
Uh(freenodes)=A(freenodes,freenodes)F(freenodes,1);
%%%% Exact solution %%%%
U = zeros(N+1,1);
for i =1:N+1
U(i) = (exp(X(i))*(3*exp(1) + 4))/(exp(2) – 1) – 5*X(i) – (exp(-X(i))*(3*exp(1) + 4*exp(2)))/(exp(2) – 1) + 4;
end
error = max(abs(U-Uh));
[U Uh]
plot(X,U,X,Uh,’o’)I am unable to input the dirichlet condition into this non homogenous ode. Please point out my mistake.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% -u" + u = – 5x + 4 0 < x <= 1 %%%%
%%%% u(0) = 0, u(1) = 2 %%%%
%%%% Exact solution u = (exp(x)*(3*exp(1) + 4))/(exp(2) – 1) – 5*x – (exp(-x)*(3*exp(1) + 4*exp(2)))/(exp(2) – 1) + 4 %%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all;
close all;
format long;
N = 20;
x0 = 0;
xN = 1;
h = 1/N;
for j = 1:N+1
X(j) = x0 + (j-1)*h;
end
f = @(x)(- 5*x +4);
A = zeros(N+1,N+1);
F = zeros(N+1,1);
%%%% Local stiffness matrix %%%%
a = [1/h -1/h ; -1/h 1/h] ;
for i=1:N
phi1 = @(x)(X(i+1)-x)/h; %%%% linear basis function %%%%
phi2 = @(x)(x-X(i))/h; %%%% linear basis function %%%%
f1 = @(x)f(x)*phi1(x); %%%% integrand for load vector %%%%
f2 = @(x)f(x)*phi2(x); %%%% integrand for load vector %%%%
v(1,i) = gauss(f1,X(i),X(i+1),1); %%%% element wise values of
v(2,i) = gauss(f2,X(i),X(i+1),1); %%%% load vector
end
%%%% Assembling %%%%
for i=1:N
A([i i+1],[i i+1]) = A([i i+1],[i i+1]) + a;
F([i i+1],1) = F([i i+1],1) + v([1 2],i);
end
%%%% Dirichlet Boundary condition %%%%
% F(N+1,1) = F(N+1,1)+2;
fullnodes = [1:N+1];
%%%%% Dirichlet boundary condition %%%%%
freenodes=setdiff(fullnodes,[1]);
Uh = zeros(N+1,1);
Uh(N+1,1) = 2;
%%%% Approximate solution %%%%
Uh(freenodes)=A(freenodes,freenodes)F(freenodes,1);
%%%% Exact solution %%%%
U = zeros(N+1,1);
for i =1:N+1
U(i) = (exp(X(i))*(3*exp(1) + 4))/(exp(2) – 1) – 5*X(i) – (exp(-X(i))*(3*exp(1) + 4*exp(2)))/(exp(2) – 1) + 4;
end
error = max(abs(U-Uh));
[U Uh]
plot(X,U,X,Uh,’o’) I am unable to input the dirichlet condition into this non homogenous ode. Please point out my mistake.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% -u" + u = – 5x + 4 0 < x <= 1 %%%%
%%%% u(0) = 0, u(1) = 2 %%%%
%%%% Exact solution u = (exp(x)*(3*exp(1) + 4))/(exp(2) – 1) – 5*x – (exp(-x)*(3*exp(1) + 4*exp(2)))/(exp(2) – 1) + 4 %%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all;
close all;
format long;
N = 20;
x0 = 0;
xN = 1;
h = 1/N;
for j = 1:N+1
X(j) = x0 + (j-1)*h;
end
f = @(x)(- 5*x +4);
A = zeros(N+1,N+1);
F = zeros(N+1,1);
%%%% Local stiffness matrix %%%%
a = [1/h -1/h ; -1/h 1/h] ;
for i=1:N
phi1 = @(x)(X(i+1)-x)/h; %%%% linear basis function %%%%
phi2 = @(x)(x-X(i))/h; %%%% linear basis function %%%%
f1 = @(x)f(x)*phi1(x); %%%% integrand for load vector %%%%
f2 = @(x)f(x)*phi2(x); %%%% integrand for load vector %%%%
v(1,i) = gauss(f1,X(i),X(i+1),1); %%%% element wise values of
v(2,i) = gauss(f2,X(i),X(i+1),1); %%%% load vector
end
%%%% Assembling %%%%
for i=1:N
A([i i+1],[i i+1]) = A([i i+1],[i i+1]) + a;
F([i i+1],1) = F([i i+1],1) + v([1 2],i);
end
%%%% Dirichlet Boundary condition %%%%
% F(N+1,1) = F(N+1,1)+2;
fullnodes = [1:N+1];
%%%%% Dirichlet boundary condition %%%%%
freenodes=setdiff(fullnodes,[1]);
Uh = zeros(N+1,1);
Uh(N+1,1) = 2;
%%%% Approximate solution %%%%
Uh(freenodes)=A(freenodes,freenodes)F(freenodes,1);
%%%% Exact solution %%%%
U = zeros(N+1,1);
for i =1:N+1
U(i) = (exp(X(i))*(3*exp(1) + 4))/(exp(2) – 1) – 5*X(i) – (exp(-X(i))*(3*exp(1) + 4*exp(2)))/(exp(2) – 1) + 4;
end
error = max(abs(U-Uh));
[U Uh]
plot(X,U,X,Uh,’o’) finite element method MATLAB Answers — New Questions
Why the Kf_LMax value is increased beyond its limits. Is their is any logical error Kindly help me out .
Why the Kf_LMax value is increased beyond its limits. Is their is any logical error Kindly help me out .
% Define parameters
Kf_Max = 100; % maximum forward rate
RLC = [0.1, 0.5, 10, 5, 10, 1]; % RLC values
TauKf_ON = -0.01; % TauKf_ON
TauKf_OFF = -0.01; % TauKf_OFF
PhaseTimes = [0, 500, 1000, 2000, 3000, 4000, 5000]; % phase times (each row defines a phase)
% Generate time vector
t = 0:0.01:5000;
% Call the function to compute receptor concentrations and Kf
[ Kf_LMax] = Kf_Cal(Kf_Max, RLC, TauKf_ON, TauKf_OFF, PhaseTimes, t);
% Plotting
figure;
% Plot Kf_LMax
plot(t, Kf_LMax, ‘b’, ‘LineWidth’, 1.5);
title(‘Kf_LMax over Time’);
xlabel(‘Time’);
ylabel(‘Kf_LMax’);
grid on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ Kf_LMax] = Kf_Cal(Kf_Max, RLC, TauKf_ON, TauKf_OFF, PhaseTimes, t)
% Initialize output variables
Kf_LMax = zeros(size(t));
% Calculate Kf_L for each time step
for i = 1:length(t)
Kf_LMax(i) = calculate_kf(t(i), PhaseTimes, Kf_Max, RLC, TauKf_ON, TauKf_OFF);
end
% Nested function for calculating Kf_L based on time
function Kf_L = calculate_kf(t_current, PhaseTimes, Kf_Max, RLC, TauKf_ON, TauKf_OFF)
% Calculate maximum Kf_L based on RLC values using Element wise
% division
Kf_LMax_values = Kf_Max * (RLC ./ (1 + RLC));
% Default Kf_L to the maximum value of the first phase
Kf_L = Kf_LMax_values(1);
% Number of phases
num_phases = numel(RLC);
% Iterate through each phase to determine the current phase based on time
for j = 1:num_phases
T_start = PhaseTimes(j); % Start time of the current phase
if j < num_phases
T_end = PhaseTimes(j + 1); % End time of the current phase
else
T_end = inf; % Handle last phase separately
end
% Check if the current time t_current is within the current phase
if t_current >= T_start && t_current < T_end
if j == 1
% For the first phase, use the maximum value directly
Kf_L = Kf_LMax_values(j);
else
% Time at the end of the previous phase
% prev_end = PhaseTimes(j – 1);
if j < num_phases
% Check RLC conditions and compute Kf_L
if RLC(j – 1) < RLC(j) && RLC(j) > RLC(j + 1)
% Peak condition
Kf_endA = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endA – Kf_LMax_values(j – 1)) *exp(TauKf_OFF * ( t_current – T_start));
elseif RLC(j – 1) < RLC(j) && RLC(j) < RLC(j + 1)
% Increasing RLC condition
Kf_endB = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endB – Kf_LMax_values(j – 1)) *exp(TauKf_OFF * (t_current – T_start));
elseif RLC(j – 1) > RLC(j) && RLC(j) < RLC(j + 1)
% Decreasing RLC condition
Kf_endC = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endC – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start ));
elseif RLC(j – 1) > RLC(j) && RLC(j) >= RLC(j + 1)
% Flat or decreasing RLC condition
Kf_endD = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endD – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start ));
end
else
% % % Handling for the last phase
if RLC(j – 1) < RLC(j)
Kf_end1 = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start) Kf_L = Kf_LMax_values(j) + (Kf_end1 – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start));
elseif RLC(j – 1) > RLC(j)
Kf_end2 = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_end2 – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start));
end
end
end
return; % Exit the function after finding the correct phase
end
end
end
endWhy the Kf_LMax value is increased beyond its limits. Is their is any logical error Kindly help me out .
% Define parameters
Kf_Max = 100; % maximum forward rate
RLC = [0.1, 0.5, 10, 5, 10, 1]; % RLC values
TauKf_ON = -0.01; % TauKf_ON
TauKf_OFF = -0.01; % TauKf_OFF
PhaseTimes = [0, 500, 1000, 2000, 3000, 4000, 5000]; % phase times (each row defines a phase)
% Generate time vector
t = 0:0.01:5000;
% Call the function to compute receptor concentrations and Kf
[ Kf_LMax] = Kf_Cal(Kf_Max, RLC, TauKf_ON, TauKf_OFF, PhaseTimes, t);
% Plotting
figure;
% Plot Kf_LMax
plot(t, Kf_LMax, ‘b’, ‘LineWidth’, 1.5);
title(‘Kf_LMax over Time’);
xlabel(‘Time’);
ylabel(‘Kf_LMax’);
grid on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ Kf_LMax] = Kf_Cal(Kf_Max, RLC, TauKf_ON, TauKf_OFF, PhaseTimes, t)
% Initialize output variables
Kf_LMax = zeros(size(t));
% Calculate Kf_L for each time step
for i = 1:length(t)
Kf_LMax(i) = calculate_kf(t(i), PhaseTimes, Kf_Max, RLC, TauKf_ON, TauKf_OFF);
end
% Nested function for calculating Kf_L based on time
function Kf_L = calculate_kf(t_current, PhaseTimes, Kf_Max, RLC, TauKf_ON, TauKf_OFF)
% Calculate maximum Kf_L based on RLC values using Element wise
% division
Kf_LMax_values = Kf_Max * (RLC ./ (1 + RLC));
% Default Kf_L to the maximum value of the first phase
Kf_L = Kf_LMax_values(1);
% Number of phases
num_phases = numel(RLC);
% Iterate through each phase to determine the current phase based on time
for j = 1:num_phases
T_start = PhaseTimes(j); % Start time of the current phase
if j < num_phases
T_end = PhaseTimes(j + 1); % End time of the current phase
else
T_end = inf; % Handle last phase separately
end
% Check if the current time t_current is within the current phase
if t_current >= T_start && t_current < T_end
if j == 1
% For the first phase, use the maximum value directly
Kf_L = Kf_LMax_values(j);
else
% Time at the end of the previous phase
% prev_end = PhaseTimes(j – 1);
if j < num_phases
% Check RLC conditions and compute Kf_L
if RLC(j – 1) < RLC(j) && RLC(j) > RLC(j + 1)
% Peak condition
Kf_endA = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endA – Kf_LMax_values(j – 1)) *exp(TauKf_OFF * ( t_current – T_start));
elseif RLC(j – 1) < RLC(j) && RLC(j) < RLC(j + 1)
% Increasing RLC condition
Kf_endB = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endB – Kf_LMax_values(j – 1)) *exp(TauKf_OFF * (t_current – T_start));
elseif RLC(j – 1) > RLC(j) && RLC(j) < RLC(j + 1)
% Decreasing RLC condition
Kf_endC = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endC – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start ));
elseif RLC(j – 1) > RLC(j) && RLC(j) >= RLC(j + 1)
% Flat or decreasing RLC condition
Kf_endD = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endD – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start ));
end
else
% % % Handling for the last phase
if RLC(j – 1) < RLC(j)
Kf_end1 = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start) Kf_L = Kf_LMax_values(j) + (Kf_end1 – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start));
elseif RLC(j – 1) > RLC(j)
Kf_end2 = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_end2 – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start));
end
end
end
return; % Exit the function after finding the correct phase
end
end
end
end Why the Kf_LMax value is increased beyond its limits. Is their is any logical error Kindly help me out .
% Define parameters
Kf_Max = 100; % maximum forward rate
RLC = [0.1, 0.5, 10, 5, 10, 1]; % RLC values
TauKf_ON = -0.01; % TauKf_ON
TauKf_OFF = -0.01; % TauKf_OFF
PhaseTimes = [0, 500, 1000, 2000, 3000, 4000, 5000]; % phase times (each row defines a phase)
% Generate time vector
t = 0:0.01:5000;
% Call the function to compute receptor concentrations and Kf
[ Kf_LMax] = Kf_Cal(Kf_Max, RLC, TauKf_ON, TauKf_OFF, PhaseTimes, t);
% Plotting
figure;
% Plot Kf_LMax
plot(t, Kf_LMax, ‘b’, ‘LineWidth’, 1.5);
title(‘Kf_LMax over Time’);
xlabel(‘Time’);
ylabel(‘Kf_LMax’);
grid on;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ Kf_LMax] = Kf_Cal(Kf_Max, RLC, TauKf_ON, TauKf_OFF, PhaseTimes, t)
% Initialize output variables
Kf_LMax = zeros(size(t));
% Calculate Kf_L for each time step
for i = 1:length(t)
Kf_LMax(i) = calculate_kf(t(i), PhaseTimes, Kf_Max, RLC, TauKf_ON, TauKf_OFF);
end
% Nested function for calculating Kf_L based on time
function Kf_L = calculate_kf(t_current, PhaseTimes, Kf_Max, RLC, TauKf_ON, TauKf_OFF)
% Calculate maximum Kf_L based on RLC values using Element wise
% division
Kf_LMax_values = Kf_Max * (RLC ./ (1 + RLC));
% Default Kf_L to the maximum value of the first phase
Kf_L = Kf_LMax_values(1);
% Number of phases
num_phases = numel(RLC);
% Iterate through each phase to determine the current phase based on time
for j = 1:num_phases
T_start = PhaseTimes(j); % Start time of the current phase
if j < num_phases
T_end = PhaseTimes(j + 1); % End time of the current phase
else
T_end = inf; % Handle last phase separately
end
% Check if the current time t_current is within the current phase
if t_current >= T_start && t_current < T_end
if j == 1
% For the first phase, use the maximum value directly
Kf_L = Kf_LMax_values(j);
else
% Time at the end of the previous phase
% prev_end = PhaseTimes(j – 1);
if j < num_phases
% Check RLC conditions and compute Kf_L
if RLC(j – 1) < RLC(j) && RLC(j) > RLC(j + 1)
% Peak condition
Kf_endA = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endA – Kf_LMax_values(j – 1)) *exp(TauKf_OFF * ( t_current – T_start));
elseif RLC(j – 1) < RLC(j) && RLC(j) < RLC(j + 1)
% Increasing RLC condition
Kf_endB = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endB – Kf_LMax_values(j – 1)) *exp(TauKf_OFF * (t_current – T_start));
elseif RLC(j – 1) > RLC(j) && RLC(j) < RLC(j + 1)
% Decreasing RLC condition
Kf_endC = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endC – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start ));
elseif RLC(j – 1) > RLC(j) && RLC(j) >= RLC(j + 1)
% Flat or decreasing RLC condition
Kf_endD = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_endD – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start ));
end
else
% % % Handling for the last phase
if RLC(j – 1) < RLC(j)
Kf_end1 = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start) Kf_L = Kf_LMax_values(j) + (Kf_end1 – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start));
elseif RLC(j – 1) > RLC(j)
Kf_end2 = Kf_LMax_values(j) – (Kf_LMax_values(j) – Kf_LMax_values(j – 1)) * exp(TauKf_ON * (t_current – T_start));
Kf_L = Kf_LMax_values(j) + (Kf_end2 – Kf_LMax_values(j – 1)) * exp(TauKf_OFF * (t_current – T_start));
end
end
end
return; % Exit the function after finding the correct phase
end
end
end
end graph MATLAB Answers — New Questions
How to find center and radius of an arc from binarized image
I have image of anulus, I need to find center and radius of inner and outer arcI have image of anulus, I need to find center and radius of inner and outer arc I have image of anulus, I need to find center and radius of inner and outer arc image processing, circle fitting, binary image processing MATLAB Answers — New Questions
generated rs code function result is not different with matlab simulink simulation
Hello,
I use the rs decoder of hdl coder. the simulation in matlab simulink is correct…
but when I load this code in fpga board and capture data by using the ILA, Its not same…
I think that when generated code is converted to verilog, difference is occured??
possible waring list..
optimization option
timing closure
tool version
1. optimization option : I set correct clock, fpga board, distributed pipeline … and so on.
-> I dont know that my setting value is correct????
2. timing satisfy, fpga clock : 16Mhz
3. matlab ver : 23a, vivado ver : 20.2
please give me check point….
thank you your corporation
Je Heo.Hello,
I use the rs decoder of hdl coder. the simulation in matlab simulink is correct…
but when I load this code in fpga board and capture data by using the ILA, Its not same…
I think that when generated code is converted to verilog, difference is occured??
possible waring list..
optimization option
timing closure
tool version
1. optimization option : I set correct clock, fpga board, distributed pipeline … and so on.
-> I dont know that my setting value is correct????
2. timing satisfy, fpga clock : 16Mhz
3. matlab ver : 23a, vivado ver : 20.2
please give me check point….
thank you your corporation
Je Heo. Hello,
I use the rs decoder of hdl coder. the simulation in matlab simulink is correct…
but when I load this code in fpga board and capture data by using the ILA, Its not same…
I think that when generated code is converted to verilog, difference is occured??
possible waring list..
optimization option
timing closure
tool version
1. optimization option : I set correct clock, fpga board, distributed pipeline … and so on.
-> I dont know that my setting value is correct????
2. timing satisfy, fpga clock : 16Mhz
3. matlab ver : 23a, vivado ver : 20.2
please give me check point….
thank you your corporation
Je Heo. hdl coder, rs decoder, fpga, generated hdl code, ila MATLAB Answers — New Questions
How do I plot a spectrogram of a real time plugin?
I managed to program a plugin that does a bit of reverb and a low pass filter. The plugin itself just shows me the spectrum of a signal during the time it is played but I need the entire spectrogram of that signal. Is there an option to plot the entire spectrogram with the audioTestBench function?
classdef FDNreverb2 < audioPlugin
properties
preDelayT = 0; % pre delay [ms]
reverbTime = 1.0; % reverb time [s]
roomSize = 5;
mix = 70; % mix of wet and dry signal [Percent], 100 % -> only wet
order = enumFDNorder.order8; % order of FDN, should be power of 2
in_coeff = 1/2; % coeff for in and output lines — just for now one value for all
out_coeff = 0.7;
end
properties (Access = private)
N = 8; % order of FDN
a = 1.1; % multiplying factor for delays
cSound = 343.2; % speed of sound
primeDelays = [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 …
67 71 73 79 83 89 97 101 103 107 109 113 127 131];
% following values have to be set manually for Interface
maxPreDelay = 0.2; % max pre delay [s] (200ms)
maxRoomSize = 20.0; % max room size [m]
% following variables initialized in reset method
fs; % sample rate
A; % feedback matrix
b; % input gain coefficients
c; % output gain coefficients
f; % feedback lines after matrix
v; % signal before delay – v_i(n) = b_i * x(n) + f_i(n)
s; % output lines
d; % signal to be sent to matrix A
buffDelayLines; % buffer delay lines, initialized in reset method
m; % delay in samples of each delay line
g; % gain coefficients of delay lines
maxDelay; % maximum delay in delay lines
buffInput; % input buffer for pre delay
pBuffDelayLines; % pointer for delay lines buffer
pBuffInput; % pointer for input buffer
preDelayS; % preDelay in samples
alpha;
v_prev2;
v_prev1;
v_filt_prev1;
v_filt_prev2;
end
properties(Constant)
PluginInterface = audioPluginInterface( …
audioPluginParameter(‘preDelayT’, …
‘DisplayName’, ‘Pre Delay [ms]’, …
‘Mapping’, {‘int’, 0, 200}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,1]), …
audioPluginParameter(‘roomSize’, …
‘DisplayName’, ‘Room Size [m]’, …
‘Mapping’, {‘lin’, 1.0, 20.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,2]), …
audioPluginParameter(‘reverbTime’, …
‘DisplayName’, ‘Reverb Time [s]’, …
‘Mapping’, {‘lin’, 0.1, 5.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,3]), …
audioPluginParameter(‘order’, …
‘DisplayName’, ‘Order of FDN’, …
‘Mapping’, {‘enum’, ‘8’, ’16’, ’32’}, …
‘Layout’, [3,2]), …
audioPluginParameter(‘in_coeff’, …
‘DisplayName’, ‘Input Gain’, …
‘Mapping’, {‘lin’, 0.0, 1.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,3]), …
audioPluginParameter(‘out_coeff’, …
‘DisplayName’, ‘Output Gain’, …
‘Mapping’, {‘lin’, 0.0, 1.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,4]), …
audioPluginParameter(‘mix’, …
‘DisplayName’, ‘Mix’, …
‘Mapping’, {‘int’, 0, 100}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,1]), …
audioPluginGridLayout( …
‘RowHeight’, [100 100 100 100 100 100], …
‘ColumnWidth’,[100, 100 100 100 100 100], …
‘RowSpacing’, 10, …
‘ColumnSpacing’, 10, …
‘Padding’, [10 10 10 10]) …
);
end
methods
function plugin = FDNreverb
init(plugin)
end
function out = process(plugin, in)
out = zeros(size(in));
%Butterworth coefficients
[bx, ax] = butter(2, 3000/(plugin.fs/2)); % 2. Ordnung, Grenzfrequenz 1000 Hz
b0 = bx(1);
b1 = bx(2);
b2 = bx(3);
a1 = ax(2);
a2 = ax(3);
% rawVn(1) = b0*plugin.v(1);
% rawVn(2) = b0*plugin.v(2) + b1*plugin.v(1) – a1* rawVn(1);
% Define the cutoff frequency and calculate alpha
cutoffFreq = 1000; % Example cutoff frequency in Hz
plugin.alpha = (2 * pi * cutoffFreq) / (plugin.fs + 2 * pi * cutoffFreq);
% Initialize the previous output for the filter
prevY = zeros(plugin.N, 1);
for i = 1:size(in,1)
% Summieren der L/R – Kan�le
inL = in(i,1);
inR = in(i,2);
inSum = (inL + inR)/2;
plugin.buffInput(plugin.pBuffInput + 1) = inSum;
% loop over delay lines
for n=1:plugin.N
% d_n = gain * delayed v_n
for k=1:plugin.N
plugin.d(k) = plugin.g(k) * plugin.buffDelayLines(k, mod(plugin.pBuffDelayLines + plugin.m(k), plugin.maxDelay +1) + 1);
end
% f_n = A(n,:) * d’
plugin.f(n) = plugin.A(n,:) * plugin.d(:);
% v_n with pre delay
rawVn = plugin.b(n) * plugin.buffInput(mod(plugin.pBuffInput + plugin.preDelayS, (plugin.maxPreDelay * plugin.fs + 1)) + 1) + plugin.f(n);
% Filter anwenden
plugin.v(n) = b0 * rawVn + b1 * plugin.v_prev1(n) + b2 * plugin.v_prev2(n) …
– a1 * plugin.v_filt_prev1(n) – a2 * plugin.v_filt_prev2(n);
% Update der vorherigen Filterwerte
plugin.v_prev2(n) = plugin.v_prev1(n);
plugin.v_prev1(n) = rawVn;
plugin.v_filt_prev2(n) = plugin.v_filt_prev1(n);
plugin.v_filt_prev1(n) = plugin.v(n);
plugin.buffDelayLines(n, plugin.pBuffDelayLines + 1) = plugin.v(n);
% output lines
plugin.s(n) = plugin.c(n) * plugin.d(n);
out(i,:) = out(i,:) + real(plugin.s(n));
end
% Assign to output
out(i,1) = plugin.mix/100 * out(i,1) + (1.0 – plugin.mix/100) * in(i,1);
out(i,2) = plugin.mix/100 * out(i,2) + (1.0 – plugin.mix/100) * in(i,2);
calculatePointer(plugin);
end
end
function calculatePointer(plugin)
if (plugin.pBuffDelayLines==0)
plugin.pBuffDelayLines = plugin.maxDelay;
else
plugin.pBuffDelayLines = plugin.pBuffDelayLines – 1;
end
if (plugin.pBuffInput==0)
plugin.pBuffInput = plugin.maxPreDelay * plugin.fs;
else
plugin.pBuffInput = plugin.pBuffInput – 1;
end
end
function set.in_coeff(plugin, val)
plugin.in_coeff = val;
plugin.b = ones(plugin.N,1) * val;
end
function set.out_coeff(plugin, val)
plugin.out_coeff = val;
plugin.c = ones(plugin.N,1) * val;
end
function set.order(plugin, val)
plugin.order = val;
switch (plugin.order)
case enumFDNorder.order8
plugin.N = 8;
case enumFDNorder.order16
plugin.N = 16;
case enumFDNorder.order32
plugin.N = 32;
end
reset(plugin)
end
function set.reverbTime(plugin, val)
plugin.reverbTime = val;
calculateGainCoeffs(plugin, plugin.reverbTime)
calculateDelays(plugin)
%sprintf(‘Set Reverb Time: %f’, plugin.reverbTime)
%disp([‘Set Reverb Time: ‘, num2str(plugin.reverbTime), ‘ s.’]);
end
function set.preDelayT(plugin, val)
plugin.preDelayT = val;
calculatePreDelayS(plugin, plugin.preDelayT)
%disp([‘Set Predelay: ‘, int2str(plugin.preDelayT), ‘ ms.’]);
end
function set.mix(plugin, val)
plugin.mix = val;
%disp([‘Set Mix value: ‘, int2str(plugin.mix), ‘ %.’]);
end
function calculateMatrix(plugin)
plugin.A = generateFDNmatrix(plugin.N);
end
function calculateDelays(plugin)
% calculate sample delays dependent on room size (val) and
% sample rate (fs)
% m_1 = trace of sound / cSound * fs
M = ceil(0.15 * plugin.reverbTime * plugin.fs);
%disp([‘M = ‘, int2str(M)]);
plugin.m = zeros(plugin.N,1);
interval = M/(plugin.N*4);
%test = 0;
for i=1:plugin.N
tmp = interval/2 + (i-1) * interval;
e = floor(0.5 + log(tmp)/log(plugin.primeDelays(i)));
plugin.m(i) = plugin.primeDelays(i)^(e);
end
end
function calculateGainCoeffs(plugin, val)
for i=1:plugin.N
plugin.g(i) = 10^((-3) * (plugin.m(i)/plugin.fs) / val);
end
end
function calculatePreDelayS(plugin, val)
plugin.preDelayS = val * plugin.fs / 1000;
end
function init(plugin)
plugin.fs = getSampleRate(plugin);
% initialize buffDelayLines & pointer
%plugin.maxDelay = floor(plugin.maxRoomSize/plugin.cSound * plugin.fs * plugin.a^(plugin.N)); %probably higher than actual max delay as actual delays get rounded down
%plugin.maxDelay = ceil(0.15 * 5 * plugin.fs); % maximum possible delay for max reverb time = 5s
plugin.maxDelay = 131^2;
plugin.buffDelayLines = zeros(plugin.N, plugin.maxDelay + 1);
plugin.pBuffDelayLines = plugin.maxDelay;
%initialize filter elements
plugin.v_prev1 = zeros(plugin.N,1);
plugin.v_prev2 = zeros(plugin.N,1);
plugin.v_filt_prev2 = zeros(plugin.N,1);
plugin.v_filt_prev1 = zeros(plugin.N,1);
% initialize
plugin.A = zeros(plugin.N);
plugin.b = ones(plugin.N,1) * plugin.in_coeff; % input gain coefficients
plugin.c = ones(plugin.N,1) * plugin.out_coeff; % output gain coefficients
plugin.f = zeros(plugin.N,1); % feedback lines after matrix
plugin.v = zeros(plugin.N,1); % signal before delay – v_i(n) = b_i * x(n) + f_i(n)
plugin.s = zeros(plugin.N,1); % output lines
plugin.d = zeros(plugin.N,1); % signal to be sent fsto matrix A
plugin.m = zeros(plugin.N,1); % delay in samples of each delay line
plugin.g = zeros(plugin.N,1); % gain coefficients of delay lines
plugin.buffInput = zeros((plugin.maxPreDelay * plugin.fs) + 1, 1); % input buffer for pre delay, 0.2 = max pre delay of 200ms
plugin.preDelayS = 0; % pre delay in samples
plugin.pBuffInput = plugin.maxPreDelay * plugin.fs; % pointer for input buffer
% calculate sample delays of delay lines
calculateDelays(plugin)
% calculate gain coeffs of delay lines
calculateGainCoeffs(plugin, plugin.reverbTime)
% calculate FDN matrix based on set order
calculateMatrix(plugin)
end
function reset(plugin)
init(plugin)
end
function generateFDNmatrix(order)
% generates FDN matrix with evenly distributed eigenvalues at
% the unit circle
eig_nr = order/2;
FDNmatrix = zeros(order, order);
M = orth((rand(order,order)));
BC_n = zeros(order, order, eig_nr);
DtD_n = zeros(order, order, eig_nr);
k1 = 1;
for k=2:2:eig_nr*2
x = M(:,k-1);
y = M(:,k);
x = x / sqrt(2);
y = y / sqrt(2);
B = x * x.’;
C = y * y.’;
D = x * y.’;
BC_n(1:order,1:order,k1) = B + C;
DtD_n(1:order,1:order,k1) = D.’ – D;
w = pi * k / (eig_nr * 2 + 2);
temp = 2 * BC_n(:,:,k1) * cos(w) + 2 * DtD_n(:,:,k1) * sin(w);
FDNmatrix = FDNmatrix + temp;
k1 = k1 + 1;
end
end
end
endI managed to program a plugin that does a bit of reverb and a low pass filter. The plugin itself just shows me the spectrum of a signal during the time it is played but I need the entire spectrogram of that signal. Is there an option to plot the entire spectrogram with the audioTestBench function?
classdef FDNreverb2 < audioPlugin
properties
preDelayT = 0; % pre delay [ms]
reverbTime = 1.0; % reverb time [s]
roomSize = 5;
mix = 70; % mix of wet and dry signal [Percent], 100 % -> only wet
order = enumFDNorder.order8; % order of FDN, should be power of 2
in_coeff = 1/2; % coeff for in and output lines — just for now one value for all
out_coeff = 0.7;
end
properties (Access = private)
N = 8; % order of FDN
a = 1.1; % multiplying factor for delays
cSound = 343.2; % speed of sound
primeDelays = [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 …
67 71 73 79 83 89 97 101 103 107 109 113 127 131];
% following values have to be set manually for Interface
maxPreDelay = 0.2; % max pre delay [s] (200ms)
maxRoomSize = 20.0; % max room size [m]
% following variables initialized in reset method
fs; % sample rate
A; % feedback matrix
b; % input gain coefficients
c; % output gain coefficients
f; % feedback lines after matrix
v; % signal before delay – v_i(n) = b_i * x(n) + f_i(n)
s; % output lines
d; % signal to be sent to matrix A
buffDelayLines; % buffer delay lines, initialized in reset method
m; % delay in samples of each delay line
g; % gain coefficients of delay lines
maxDelay; % maximum delay in delay lines
buffInput; % input buffer for pre delay
pBuffDelayLines; % pointer for delay lines buffer
pBuffInput; % pointer for input buffer
preDelayS; % preDelay in samples
alpha;
v_prev2;
v_prev1;
v_filt_prev1;
v_filt_prev2;
end
properties(Constant)
PluginInterface = audioPluginInterface( …
audioPluginParameter(‘preDelayT’, …
‘DisplayName’, ‘Pre Delay [ms]’, …
‘Mapping’, {‘int’, 0, 200}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,1]), …
audioPluginParameter(‘roomSize’, …
‘DisplayName’, ‘Room Size [m]’, …
‘Mapping’, {‘lin’, 1.0, 20.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,2]), …
audioPluginParameter(‘reverbTime’, …
‘DisplayName’, ‘Reverb Time [s]’, …
‘Mapping’, {‘lin’, 0.1, 5.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,3]), …
audioPluginParameter(‘order’, …
‘DisplayName’, ‘Order of FDN’, …
‘Mapping’, {‘enum’, ‘8’, ’16’, ’32’}, …
‘Layout’, [3,2]), …
audioPluginParameter(‘in_coeff’, …
‘DisplayName’, ‘Input Gain’, …
‘Mapping’, {‘lin’, 0.0, 1.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,3]), …
audioPluginParameter(‘out_coeff’, …
‘DisplayName’, ‘Output Gain’, …
‘Mapping’, {‘lin’, 0.0, 1.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,4]), …
audioPluginParameter(‘mix’, …
‘DisplayName’, ‘Mix’, …
‘Mapping’, {‘int’, 0, 100}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,1]), …
audioPluginGridLayout( …
‘RowHeight’, [100 100 100 100 100 100], …
‘ColumnWidth’,[100, 100 100 100 100 100], …
‘RowSpacing’, 10, …
‘ColumnSpacing’, 10, …
‘Padding’, [10 10 10 10]) …
);
end
methods
function plugin = FDNreverb
init(plugin)
end
function out = process(plugin, in)
out = zeros(size(in));
%Butterworth coefficients
[bx, ax] = butter(2, 3000/(plugin.fs/2)); % 2. Ordnung, Grenzfrequenz 1000 Hz
b0 = bx(1);
b1 = bx(2);
b2 = bx(3);
a1 = ax(2);
a2 = ax(3);
% rawVn(1) = b0*plugin.v(1);
% rawVn(2) = b0*plugin.v(2) + b1*plugin.v(1) – a1* rawVn(1);
% Define the cutoff frequency and calculate alpha
cutoffFreq = 1000; % Example cutoff frequency in Hz
plugin.alpha = (2 * pi * cutoffFreq) / (plugin.fs + 2 * pi * cutoffFreq);
% Initialize the previous output for the filter
prevY = zeros(plugin.N, 1);
for i = 1:size(in,1)
% Summieren der L/R – Kan�le
inL = in(i,1);
inR = in(i,2);
inSum = (inL + inR)/2;
plugin.buffInput(plugin.pBuffInput + 1) = inSum;
% loop over delay lines
for n=1:plugin.N
% d_n = gain * delayed v_n
for k=1:plugin.N
plugin.d(k) = plugin.g(k) * plugin.buffDelayLines(k, mod(plugin.pBuffDelayLines + plugin.m(k), plugin.maxDelay +1) + 1);
end
% f_n = A(n,:) * d’
plugin.f(n) = plugin.A(n,:) * plugin.d(:);
% v_n with pre delay
rawVn = plugin.b(n) * plugin.buffInput(mod(plugin.pBuffInput + plugin.preDelayS, (plugin.maxPreDelay * plugin.fs + 1)) + 1) + plugin.f(n);
% Filter anwenden
plugin.v(n) = b0 * rawVn + b1 * plugin.v_prev1(n) + b2 * plugin.v_prev2(n) …
– a1 * plugin.v_filt_prev1(n) – a2 * plugin.v_filt_prev2(n);
% Update der vorherigen Filterwerte
plugin.v_prev2(n) = plugin.v_prev1(n);
plugin.v_prev1(n) = rawVn;
plugin.v_filt_prev2(n) = plugin.v_filt_prev1(n);
plugin.v_filt_prev1(n) = plugin.v(n);
plugin.buffDelayLines(n, plugin.pBuffDelayLines + 1) = plugin.v(n);
% output lines
plugin.s(n) = plugin.c(n) * plugin.d(n);
out(i,:) = out(i,:) + real(plugin.s(n));
end
% Assign to output
out(i,1) = plugin.mix/100 * out(i,1) + (1.0 – plugin.mix/100) * in(i,1);
out(i,2) = plugin.mix/100 * out(i,2) + (1.0 – plugin.mix/100) * in(i,2);
calculatePointer(plugin);
end
end
function calculatePointer(plugin)
if (plugin.pBuffDelayLines==0)
plugin.pBuffDelayLines = plugin.maxDelay;
else
plugin.pBuffDelayLines = plugin.pBuffDelayLines – 1;
end
if (plugin.pBuffInput==0)
plugin.pBuffInput = plugin.maxPreDelay * plugin.fs;
else
plugin.pBuffInput = plugin.pBuffInput – 1;
end
end
function set.in_coeff(plugin, val)
plugin.in_coeff = val;
plugin.b = ones(plugin.N,1) * val;
end
function set.out_coeff(plugin, val)
plugin.out_coeff = val;
plugin.c = ones(plugin.N,1) * val;
end
function set.order(plugin, val)
plugin.order = val;
switch (plugin.order)
case enumFDNorder.order8
plugin.N = 8;
case enumFDNorder.order16
plugin.N = 16;
case enumFDNorder.order32
plugin.N = 32;
end
reset(plugin)
end
function set.reverbTime(plugin, val)
plugin.reverbTime = val;
calculateGainCoeffs(plugin, plugin.reverbTime)
calculateDelays(plugin)
%sprintf(‘Set Reverb Time: %f’, plugin.reverbTime)
%disp([‘Set Reverb Time: ‘, num2str(plugin.reverbTime), ‘ s.’]);
end
function set.preDelayT(plugin, val)
plugin.preDelayT = val;
calculatePreDelayS(plugin, plugin.preDelayT)
%disp([‘Set Predelay: ‘, int2str(plugin.preDelayT), ‘ ms.’]);
end
function set.mix(plugin, val)
plugin.mix = val;
%disp([‘Set Mix value: ‘, int2str(plugin.mix), ‘ %.’]);
end
function calculateMatrix(plugin)
plugin.A = generateFDNmatrix(plugin.N);
end
function calculateDelays(plugin)
% calculate sample delays dependent on room size (val) and
% sample rate (fs)
% m_1 = trace of sound / cSound * fs
M = ceil(0.15 * plugin.reverbTime * plugin.fs);
%disp([‘M = ‘, int2str(M)]);
plugin.m = zeros(plugin.N,1);
interval = M/(plugin.N*4);
%test = 0;
for i=1:plugin.N
tmp = interval/2 + (i-1) * interval;
e = floor(0.5 + log(tmp)/log(plugin.primeDelays(i)));
plugin.m(i) = plugin.primeDelays(i)^(e);
end
end
function calculateGainCoeffs(plugin, val)
for i=1:plugin.N
plugin.g(i) = 10^((-3) * (plugin.m(i)/plugin.fs) / val);
end
end
function calculatePreDelayS(plugin, val)
plugin.preDelayS = val * plugin.fs / 1000;
end
function init(plugin)
plugin.fs = getSampleRate(plugin);
% initialize buffDelayLines & pointer
%plugin.maxDelay = floor(plugin.maxRoomSize/plugin.cSound * plugin.fs * plugin.a^(plugin.N)); %probably higher than actual max delay as actual delays get rounded down
%plugin.maxDelay = ceil(0.15 * 5 * plugin.fs); % maximum possible delay for max reverb time = 5s
plugin.maxDelay = 131^2;
plugin.buffDelayLines = zeros(plugin.N, plugin.maxDelay + 1);
plugin.pBuffDelayLines = plugin.maxDelay;
%initialize filter elements
plugin.v_prev1 = zeros(plugin.N,1);
plugin.v_prev2 = zeros(plugin.N,1);
plugin.v_filt_prev2 = zeros(plugin.N,1);
plugin.v_filt_prev1 = zeros(plugin.N,1);
% initialize
plugin.A = zeros(plugin.N);
plugin.b = ones(plugin.N,1) * plugin.in_coeff; % input gain coefficients
plugin.c = ones(plugin.N,1) * plugin.out_coeff; % output gain coefficients
plugin.f = zeros(plugin.N,1); % feedback lines after matrix
plugin.v = zeros(plugin.N,1); % signal before delay – v_i(n) = b_i * x(n) + f_i(n)
plugin.s = zeros(plugin.N,1); % output lines
plugin.d = zeros(plugin.N,1); % signal to be sent fsto matrix A
plugin.m = zeros(plugin.N,1); % delay in samples of each delay line
plugin.g = zeros(plugin.N,1); % gain coefficients of delay lines
plugin.buffInput = zeros((plugin.maxPreDelay * plugin.fs) + 1, 1); % input buffer for pre delay, 0.2 = max pre delay of 200ms
plugin.preDelayS = 0; % pre delay in samples
plugin.pBuffInput = plugin.maxPreDelay * plugin.fs; % pointer for input buffer
% calculate sample delays of delay lines
calculateDelays(plugin)
% calculate gain coeffs of delay lines
calculateGainCoeffs(plugin, plugin.reverbTime)
% calculate FDN matrix based on set order
calculateMatrix(plugin)
end
function reset(plugin)
init(plugin)
end
function generateFDNmatrix(order)
% generates FDN matrix with evenly distributed eigenvalues at
% the unit circle
eig_nr = order/2;
FDNmatrix = zeros(order, order);
M = orth((rand(order,order)));
BC_n = zeros(order, order, eig_nr);
DtD_n = zeros(order, order, eig_nr);
k1 = 1;
for k=2:2:eig_nr*2
x = M(:,k-1);
y = M(:,k);
x = x / sqrt(2);
y = y / sqrt(2);
B = x * x.’;
C = y * y.’;
D = x * y.’;
BC_n(1:order,1:order,k1) = B + C;
DtD_n(1:order,1:order,k1) = D.’ – D;
w = pi * k / (eig_nr * 2 + 2);
temp = 2 * BC_n(:,:,k1) * cos(w) + 2 * DtD_n(:,:,k1) * sin(w);
FDNmatrix = FDNmatrix + temp;
k1 = k1 + 1;
end
end
end
end I managed to program a plugin that does a bit of reverb and a low pass filter. The plugin itself just shows me the spectrum of a signal during the time it is played but I need the entire spectrogram of that signal. Is there an option to plot the entire spectrogram with the audioTestBench function?
classdef FDNreverb2 < audioPlugin
properties
preDelayT = 0; % pre delay [ms]
reverbTime = 1.0; % reverb time [s]
roomSize = 5;
mix = 70; % mix of wet and dry signal [Percent], 100 % -> only wet
order = enumFDNorder.order8; % order of FDN, should be power of 2
in_coeff = 1/2; % coeff for in and output lines — just for now one value for all
out_coeff = 0.7;
end
properties (Access = private)
N = 8; % order of FDN
a = 1.1; % multiplying factor for delays
cSound = 343.2; % speed of sound
primeDelays = [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 …
67 71 73 79 83 89 97 101 103 107 109 113 127 131];
% following values have to be set manually for Interface
maxPreDelay = 0.2; % max pre delay [s] (200ms)
maxRoomSize = 20.0; % max room size [m]
% following variables initialized in reset method
fs; % sample rate
A; % feedback matrix
b; % input gain coefficients
c; % output gain coefficients
f; % feedback lines after matrix
v; % signal before delay – v_i(n) = b_i * x(n) + f_i(n)
s; % output lines
d; % signal to be sent to matrix A
buffDelayLines; % buffer delay lines, initialized in reset method
m; % delay in samples of each delay line
g; % gain coefficients of delay lines
maxDelay; % maximum delay in delay lines
buffInput; % input buffer for pre delay
pBuffDelayLines; % pointer for delay lines buffer
pBuffInput; % pointer for input buffer
preDelayS; % preDelay in samples
alpha;
v_prev2;
v_prev1;
v_filt_prev1;
v_filt_prev2;
end
properties(Constant)
PluginInterface = audioPluginInterface( …
audioPluginParameter(‘preDelayT’, …
‘DisplayName’, ‘Pre Delay [ms]’, …
‘Mapping’, {‘int’, 0, 200}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,1]), …
audioPluginParameter(‘roomSize’, …
‘DisplayName’, ‘Room Size [m]’, …
‘Mapping’, {‘lin’, 1.0, 20.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,2]), …
audioPluginParameter(‘reverbTime’, …
‘DisplayName’, ‘Reverb Time [s]’, …
‘Mapping’, {‘lin’, 0.1, 5.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [1,3]), …
audioPluginParameter(‘order’, …
‘DisplayName’, ‘Order of FDN’, …
‘Mapping’, {‘enum’, ‘8’, ’16’, ’32’}, …
‘Layout’, [3,2]), …
audioPluginParameter(‘in_coeff’, …
‘DisplayName’, ‘Input Gain’, …
‘Mapping’, {‘lin’, 0.0, 1.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,3]), …
audioPluginParameter(‘out_coeff’, …
‘DisplayName’, ‘Output Gain’, …
‘Mapping’, {‘lin’, 0.0, 1.0}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,4]), …
audioPluginParameter(‘mix’, …
‘DisplayName’, ‘Mix’, …
‘Mapping’, {‘int’, 0, 100}, …
‘Style’, ‘rotary’, …
‘Layout’, [3,1]), …
audioPluginGridLayout( …
‘RowHeight’, [100 100 100 100 100 100], …
‘ColumnWidth’,[100, 100 100 100 100 100], …
‘RowSpacing’, 10, …
‘ColumnSpacing’, 10, …
‘Padding’, [10 10 10 10]) …
);
end
methods
function plugin = FDNreverb
init(plugin)
end
function out = process(plugin, in)
out = zeros(size(in));
%Butterworth coefficients
[bx, ax] = butter(2, 3000/(plugin.fs/2)); % 2. Ordnung, Grenzfrequenz 1000 Hz
b0 = bx(1);
b1 = bx(2);
b2 = bx(3);
a1 = ax(2);
a2 = ax(3);
% rawVn(1) = b0*plugin.v(1);
% rawVn(2) = b0*plugin.v(2) + b1*plugin.v(1) – a1* rawVn(1);
% Define the cutoff frequency and calculate alpha
cutoffFreq = 1000; % Example cutoff frequency in Hz
plugin.alpha = (2 * pi * cutoffFreq) / (plugin.fs + 2 * pi * cutoffFreq);
% Initialize the previous output for the filter
prevY = zeros(plugin.N, 1);
for i = 1:size(in,1)
% Summieren der L/R – Kan�le
inL = in(i,1);
inR = in(i,2);
inSum = (inL + inR)/2;
plugin.buffInput(plugin.pBuffInput + 1) = inSum;
% loop over delay lines
for n=1:plugin.N
% d_n = gain * delayed v_n
for k=1:plugin.N
plugin.d(k) = plugin.g(k) * plugin.buffDelayLines(k, mod(plugin.pBuffDelayLines + plugin.m(k), plugin.maxDelay +1) + 1);
end
% f_n = A(n,:) * d’
plugin.f(n) = plugin.A(n,:) * plugin.d(:);
% v_n with pre delay
rawVn = plugin.b(n) * plugin.buffInput(mod(plugin.pBuffInput + plugin.preDelayS, (plugin.maxPreDelay * plugin.fs + 1)) + 1) + plugin.f(n);
% Filter anwenden
plugin.v(n) = b0 * rawVn + b1 * plugin.v_prev1(n) + b2 * plugin.v_prev2(n) …
– a1 * plugin.v_filt_prev1(n) – a2 * plugin.v_filt_prev2(n);
% Update der vorherigen Filterwerte
plugin.v_prev2(n) = plugin.v_prev1(n);
plugin.v_prev1(n) = rawVn;
plugin.v_filt_prev2(n) = plugin.v_filt_prev1(n);
plugin.v_filt_prev1(n) = plugin.v(n);
plugin.buffDelayLines(n, plugin.pBuffDelayLines + 1) = plugin.v(n);
% output lines
plugin.s(n) = plugin.c(n) * plugin.d(n);
out(i,:) = out(i,:) + real(plugin.s(n));
end
% Assign to output
out(i,1) = plugin.mix/100 * out(i,1) + (1.0 – plugin.mix/100) * in(i,1);
out(i,2) = plugin.mix/100 * out(i,2) + (1.0 – plugin.mix/100) * in(i,2);
calculatePointer(plugin);
end
end
function calculatePointer(plugin)
if (plugin.pBuffDelayLines==0)
plugin.pBuffDelayLines = plugin.maxDelay;
else
plugin.pBuffDelayLines = plugin.pBuffDelayLines – 1;
end
if (plugin.pBuffInput==0)
plugin.pBuffInput = plugin.maxPreDelay * plugin.fs;
else
plugin.pBuffInput = plugin.pBuffInput – 1;
end
end
function set.in_coeff(plugin, val)
plugin.in_coeff = val;
plugin.b = ones(plugin.N,1) * val;
end
function set.out_coeff(plugin, val)
plugin.out_coeff = val;
plugin.c = ones(plugin.N,1) * val;
end
function set.order(plugin, val)
plugin.order = val;
switch (plugin.order)
case enumFDNorder.order8
plugin.N = 8;
case enumFDNorder.order16
plugin.N = 16;
case enumFDNorder.order32
plugin.N = 32;
end
reset(plugin)
end
function set.reverbTime(plugin, val)
plugin.reverbTime = val;
calculateGainCoeffs(plugin, plugin.reverbTime)
calculateDelays(plugin)
%sprintf(‘Set Reverb Time: %f’, plugin.reverbTime)
%disp([‘Set Reverb Time: ‘, num2str(plugin.reverbTime), ‘ s.’]);
end
function set.preDelayT(plugin, val)
plugin.preDelayT = val;
calculatePreDelayS(plugin, plugin.preDelayT)
%disp([‘Set Predelay: ‘, int2str(plugin.preDelayT), ‘ ms.’]);
end
function set.mix(plugin, val)
plugin.mix = val;
%disp([‘Set Mix value: ‘, int2str(plugin.mix), ‘ %.’]);
end
function calculateMatrix(plugin)
plugin.A = generateFDNmatrix(plugin.N);
end
function calculateDelays(plugin)
% calculate sample delays dependent on room size (val) and
% sample rate (fs)
% m_1 = trace of sound / cSound * fs
M = ceil(0.15 * plugin.reverbTime * plugin.fs);
%disp([‘M = ‘, int2str(M)]);
plugin.m = zeros(plugin.N,1);
interval = M/(plugin.N*4);
%test = 0;
for i=1:plugin.N
tmp = interval/2 + (i-1) * interval;
e = floor(0.5 + log(tmp)/log(plugin.primeDelays(i)));
plugin.m(i) = plugin.primeDelays(i)^(e);
end
end
function calculateGainCoeffs(plugin, val)
for i=1:plugin.N
plugin.g(i) = 10^((-3) * (plugin.m(i)/plugin.fs) / val);
end
end
function calculatePreDelayS(plugin, val)
plugin.preDelayS = val * plugin.fs / 1000;
end
function init(plugin)
plugin.fs = getSampleRate(plugin);
% initialize buffDelayLines & pointer
%plugin.maxDelay = floor(plugin.maxRoomSize/plugin.cSound * plugin.fs * plugin.a^(plugin.N)); %probably higher than actual max delay as actual delays get rounded down
%plugin.maxDelay = ceil(0.15 * 5 * plugin.fs); % maximum possible delay for max reverb time = 5s
plugin.maxDelay = 131^2;
plugin.buffDelayLines = zeros(plugin.N, plugin.maxDelay + 1);
plugin.pBuffDelayLines = plugin.maxDelay;
%initialize filter elements
plugin.v_prev1 = zeros(plugin.N,1);
plugin.v_prev2 = zeros(plugin.N,1);
plugin.v_filt_prev2 = zeros(plugin.N,1);
plugin.v_filt_prev1 = zeros(plugin.N,1);
% initialize
plugin.A = zeros(plugin.N);
plugin.b = ones(plugin.N,1) * plugin.in_coeff; % input gain coefficients
plugin.c = ones(plugin.N,1) * plugin.out_coeff; % output gain coefficients
plugin.f = zeros(plugin.N,1); % feedback lines after matrix
plugin.v = zeros(plugin.N,1); % signal before delay – v_i(n) = b_i * x(n) + f_i(n)
plugin.s = zeros(plugin.N,1); % output lines
plugin.d = zeros(plugin.N,1); % signal to be sent fsto matrix A
plugin.m = zeros(plugin.N,1); % delay in samples of each delay line
plugin.g = zeros(plugin.N,1); % gain coefficients of delay lines
plugin.buffInput = zeros((plugin.maxPreDelay * plugin.fs) + 1, 1); % input buffer for pre delay, 0.2 = max pre delay of 200ms
plugin.preDelayS = 0; % pre delay in samples
plugin.pBuffInput = plugin.maxPreDelay * plugin.fs; % pointer for input buffer
% calculate sample delays of delay lines
calculateDelays(plugin)
% calculate gain coeffs of delay lines
calculateGainCoeffs(plugin, plugin.reverbTime)
% calculate FDN matrix based on set order
calculateMatrix(plugin)
end
function reset(plugin)
init(plugin)
end
function generateFDNmatrix(order)
% generates FDN matrix with evenly distributed eigenvalues at
% the unit circle
eig_nr = order/2;
FDNmatrix = zeros(order, order);
M = orth((rand(order,order)));
BC_n = zeros(order, order, eig_nr);
DtD_n = zeros(order, order, eig_nr);
k1 = 1;
for k=2:2:eig_nr*2
x = M(:,k-1);
y = M(:,k);
x = x / sqrt(2);
y = y / sqrt(2);
B = x * x.’;
C = y * y.’;
D = x * y.’;
BC_n(1:order,1:order,k1) = B + C;
DtD_n(1:order,1:order,k1) = D.’ – D;
w = pi * k / (eig_nr * 2 + 2);
temp = 2 * BC_n(:,:,k1) * cos(w) + 2 * DtD_n(:,:,k1) * sin(w);
FDNmatrix = FDNmatrix + temp;
k1 = k1 + 1;
end
end
end
end spectrogram, reverb, filter, audio toolbox MATLAB Answers — New Questions
Why my validation RMSE and loss increase after some epoch by my training data increase
Hello everyone
I am trying to predict traffic flow of future steps by previous collected data so I Use LSTM for it
but my validation loss and rmse increase and training loss and rmse decrease .because I am net to LSTM I don’t know which parameters I should check for improving model and predictions.
the picture of training progress is :
also I use different lags time for my predictions and here in my codes I have 4 step lag time
XTrain_ZaMir = (XTrain_ZaMir – mu_ZaMir)/sig_ZaMir;
YTrain_ZaMir = (YTrain_ZaMir – mu_ZaMir)/sig_ZaMir;
XTrain_ZaMir = XTrain_ZaMir(:,1:end-4);
YTrain_ZaMir = YTrain_ZaMir(:,5:end);
Test_ZaMir = [flowTe_ZaMir flowTeOther_ZaMir]’;
nt = floor(0.7*length(Test_ZaMir));
YTest_ZaMir = Test_ZaMir(1,1:end);
XTest_ZaMir = Test_ZaMir(1,1:end); %One input
% XTest_ZaMir = Test_ZaMir(:,1:end); % More than One input
XTest_ZaMir = (XTest_ZaMir – mu_ZaMir)/sig_ZaMir;
YTest_ZaMir = (YTest_ZaMir – mu_ZaMir)/sig_ZaMir;
XVal_ZaMir = XTest_ZaMir(:,1:nt-4);
YVal_ZaMir = YTest_ZaMir(:,5:nt);
XTest_ZaMir = XTest_ZaMir(:,nt+4:end-1);
YTest_ZaMir = YTest_ZaMir(:,nt+5:end);
%% Layers and Options
numResponses = 1 ;
featureDimension = 1;
numHiddenUnits =200 ;
layers = [ …
sequenceInputLayer(featureDimension)
lstmLayer(numHiddenUnits)
% dropoutLayer(0.002)
fullyConnectedLayer(numResponses)
regressionLayer
];
maxepochs = 250;
minibatchsize =128;
options = trainingOptions(‘adam’, … %%adam
‘MaxEpochs’,maxepochs, …
‘GradientThreshold’,1, …
‘InitialLearnRate’,0.005, …
‘ValidationData’,{XVal_ZaMir,YVal_ZaMir},…
‘ValidationFrequency’,20,…
‘Shuffle’,’every-epoch’,…
‘MiniBatchSize’,minibatchsize,…
‘LearnRateSchedule’,’piecewise’, …
‘LearnRateDropPeriod’,150, …
‘LearnRateDropFactor’,0.005, …
‘Verbose’,1, …
‘Plots’,’training-progress’);
%% Train the Network
[net,info] = trainNetwork(XTrain_ZaMir,YTrain_ZaMir,layers,options);
[net,YPred_ZaMir]= predictAndUpdateState(net,XTest_ZaMir);
numTimeStepsTest= (0.5*floor(length(XTest_ZaMir)));
for i = 2:numTimeStepsTest
[net,YPred_ZaMir(:,i)] = predictAndUpdateState(net,XTest_ZaMir(:,i-1),’ExecutionEnvironment’,’cpu’);
% net = resetState(net);
end
YTest_ZaMir = sig_ZaMir*YTest_ZaMir + mu_ZaMir;
YPred_ZaMir = sig_ZaMir*YPred_ZaMir + mu_ZaMir;Hello everyone
I am trying to predict traffic flow of future steps by previous collected data so I Use LSTM for it
but my validation loss and rmse increase and training loss and rmse decrease .because I am net to LSTM I don’t know which parameters I should check for improving model and predictions.
the picture of training progress is :
also I use different lags time for my predictions and here in my codes I have 4 step lag time
XTrain_ZaMir = (XTrain_ZaMir – mu_ZaMir)/sig_ZaMir;
YTrain_ZaMir = (YTrain_ZaMir – mu_ZaMir)/sig_ZaMir;
XTrain_ZaMir = XTrain_ZaMir(:,1:end-4);
YTrain_ZaMir = YTrain_ZaMir(:,5:end);
Test_ZaMir = [flowTe_ZaMir flowTeOther_ZaMir]’;
nt = floor(0.7*length(Test_ZaMir));
YTest_ZaMir = Test_ZaMir(1,1:end);
XTest_ZaMir = Test_ZaMir(1,1:end); %One input
% XTest_ZaMir = Test_ZaMir(:,1:end); % More than One input
XTest_ZaMir = (XTest_ZaMir – mu_ZaMir)/sig_ZaMir;
YTest_ZaMir = (YTest_ZaMir – mu_ZaMir)/sig_ZaMir;
XVal_ZaMir = XTest_ZaMir(:,1:nt-4);
YVal_ZaMir = YTest_ZaMir(:,5:nt);
XTest_ZaMir = XTest_ZaMir(:,nt+4:end-1);
YTest_ZaMir = YTest_ZaMir(:,nt+5:end);
%% Layers and Options
numResponses = 1 ;
featureDimension = 1;
numHiddenUnits =200 ;
layers = [ …
sequenceInputLayer(featureDimension)
lstmLayer(numHiddenUnits)
% dropoutLayer(0.002)
fullyConnectedLayer(numResponses)
regressionLayer
];
maxepochs = 250;
minibatchsize =128;
options = trainingOptions(‘adam’, … %%adam
‘MaxEpochs’,maxepochs, …
‘GradientThreshold’,1, …
‘InitialLearnRate’,0.005, …
‘ValidationData’,{XVal_ZaMir,YVal_ZaMir},…
‘ValidationFrequency’,20,…
‘Shuffle’,’every-epoch’,…
‘MiniBatchSize’,minibatchsize,…
‘LearnRateSchedule’,’piecewise’, …
‘LearnRateDropPeriod’,150, …
‘LearnRateDropFactor’,0.005, …
‘Verbose’,1, …
‘Plots’,’training-progress’);
%% Train the Network
[net,info] = trainNetwork(XTrain_ZaMir,YTrain_ZaMir,layers,options);
[net,YPred_ZaMir]= predictAndUpdateState(net,XTest_ZaMir);
numTimeStepsTest= (0.5*floor(length(XTest_ZaMir)));
for i = 2:numTimeStepsTest
[net,YPred_ZaMir(:,i)] = predictAndUpdateState(net,XTest_ZaMir(:,i-1),’ExecutionEnvironment’,’cpu’);
% net = resetState(net);
end
YTest_ZaMir = sig_ZaMir*YTest_ZaMir + mu_ZaMir;
YPred_ZaMir = sig_ZaMir*YPred_ZaMir + mu_ZaMir; Hello everyone
I am trying to predict traffic flow of future steps by previous collected data so I Use LSTM for it
but my validation loss and rmse increase and training loss and rmse decrease .because I am net to LSTM I don’t know which parameters I should check for improving model and predictions.
the picture of training progress is :
also I use different lags time for my predictions and here in my codes I have 4 step lag time
XTrain_ZaMir = (XTrain_ZaMir – mu_ZaMir)/sig_ZaMir;
YTrain_ZaMir = (YTrain_ZaMir – mu_ZaMir)/sig_ZaMir;
XTrain_ZaMir = XTrain_ZaMir(:,1:end-4);
YTrain_ZaMir = YTrain_ZaMir(:,5:end);
Test_ZaMir = [flowTe_ZaMir flowTeOther_ZaMir]’;
nt = floor(0.7*length(Test_ZaMir));
YTest_ZaMir = Test_ZaMir(1,1:end);
XTest_ZaMir = Test_ZaMir(1,1:end); %One input
% XTest_ZaMir = Test_ZaMir(:,1:end); % More than One input
XTest_ZaMir = (XTest_ZaMir – mu_ZaMir)/sig_ZaMir;
YTest_ZaMir = (YTest_ZaMir – mu_ZaMir)/sig_ZaMir;
XVal_ZaMir = XTest_ZaMir(:,1:nt-4);
YVal_ZaMir = YTest_ZaMir(:,5:nt);
XTest_ZaMir = XTest_ZaMir(:,nt+4:end-1);
YTest_ZaMir = YTest_ZaMir(:,nt+5:end);
%% Layers and Options
numResponses = 1 ;
featureDimension = 1;
numHiddenUnits =200 ;
layers = [ …
sequenceInputLayer(featureDimension)
lstmLayer(numHiddenUnits)
% dropoutLayer(0.002)
fullyConnectedLayer(numResponses)
regressionLayer
];
maxepochs = 250;
minibatchsize =128;
options = trainingOptions(‘adam’, … %%adam
‘MaxEpochs’,maxepochs, …
‘GradientThreshold’,1, …
‘InitialLearnRate’,0.005, …
‘ValidationData’,{XVal_ZaMir,YVal_ZaMir},…
‘ValidationFrequency’,20,…
‘Shuffle’,’every-epoch’,…
‘MiniBatchSize’,minibatchsize,…
‘LearnRateSchedule’,’piecewise’, …
‘LearnRateDropPeriod’,150, …
‘LearnRateDropFactor’,0.005, …
‘Verbose’,1, …
‘Plots’,’training-progress’);
%% Train the Network
[net,info] = trainNetwork(XTrain_ZaMir,YTrain_ZaMir,layers,options);
[net,YPred_ZaMir]= predictAndUpdateState(net,XTest_ZaMir);
numTimeStepsTest= (0.5*floor(length(XTest_ZaMir)));
for i = 2:numTimeStepsTest
[net,YPred_ZaMir(:,i)] = predictAndUpdateState(net,XTest_ZaMir(:,i-1),’ExecutionEnvironment’,’cpu’);
% net = resetState(net);
end
YTest_ZaMir = sig_ZaMir*YTest_ZaMir + mu_ZaMir;
YPred_ZaMir = sig_ZaMir*YPred_ZaMir + mu_ZaMir; predictions, lstm, validation, train MATLAB Answers — New Questions
How to do CAN Loopback test on jetson agx orin
Need to send a sample packet from can0 itself as loopback test or send from CAN0 to CAN1 in NVIDIA Jetson AGX Orin.Need to send a sample packet from can0 itself as loopback test or send from CAN0 to CAN1 in NVIDIA Jetson AGX Orin. Need to send a sample packet from can0 itself as loopback test or send from CAN0 to CAN1 in NVIDIA Jetson AGX Orin. can communication, nvidia jetson MATLAB Answers — New Questions
undefined symbol xcb_shm_id when trying to startup MatLab
When trying to start up MatLab, I get
> ./bin/matlab
MATLAB is selecting SOFTWARE rendering.
/home/pblase/.MathWorks/ServiceHost/clr-df9a0cbb6bd34e079ef626671d1a7b7c/_tmp_MSHI_5363-9225-767d-e56f/mci/_tempinstaller_glnxa64/bin/glnxa64/InstallMathWorksServiceHost: symbol lookup error: /usr/lib64/libcairo.so.2: undefined symbol: xcb_shm_id
/home/pblase/.MathWorks/ServiceHost/clr-df9a0cbb6bd34e079ef626671d1a7b7c/_tmp_MSHI_5363-9225-767d-e56f/mci/_tempinstaller_glnxa64/bin/glnxa64/InstallMathWorksServiceHost: symbol lookup error: /usr/lib64/libcairo.so.2: undefined symbol: xcb_shm_id
Unexpected exception: ‘N7mwboost10wrapexceptINS_16exception_detail39current_exception_std_exception_wrapperISt13runtime_errorEEEE: Error loading /home/pblase/matlab/bin/glnxa64/matlab_startup_plugins/matlab_graphics_ui/mwuixloader.so. /usr/lib64/libXt.so.6: undefined symbol: SmcModifyCallbacks: Success: Success’ in createMVMAndCallParser phase ‘Creating local MVM’When trying to start up MatLab, I get
> ./bin/matlab
MATLAB is selecting SOFTWARE rendering.
/home/pblase/.MathWorks/ServiceHost/clr-df9a0cbb6bd34e079ef626671d1a7b7c/_tmp_MSHI_5363-9225-767d-e56f/mci/_tempinstaller_glnxa64/bin/glnxa64/InstallMathWorksServiceHost: symbol lookup error: /usr/lib64/libcairo.so.2: undefined symbol: xcb_shm_id
/home/pblase/.MathWorks/ServiceHost/clr-df9a0cbb6bd34e079ef626671d1a7b7c/_tmp_MSHI_5363-9225-767d-e56f/mci/_tempinstaller_glnxa64/bin/glnxa64/InstallMathWorksServiceHost: symbol lookup error: /usr/lib64/libcairo.so.2: undefined symbol: xcb_shm_id
Unexpected exception: ‘N7mwboost10wrapexceptINS_16exception_detail39current_exception_std_exception_wrapperISt13runtime_errorEEEE: Error loading /home/pblase/matlab/bin/glnxa64/matlab_startup_plugins/matlab_graphics_ui/mwuixloader.so. /usr/lib64/libXt.so.6: undefined symbol: SmcModifyCallbacks: Success: Success’ in createMVMAndCallParser phase ‘Creating local MVM’ When trying to start up MatLab, I get
> ./bin/matlab
MATLAB is selecting SOFTWARE rendering.
/home/pblase/.MathWorks/ServiceHost/clr-df9a0cbb6bd34e079ef626671d1a7b7c/_tmp_MSHI_5363-9225-767d-e56f/mci/_tempinstaller_glnxa64/bin/glnxa64/InstallMathWorksServiceHost: symbol lookup error: /usr/lib64/libcairo.so.2: undefined symbol: xcb_shm_id
/home/pblase/.MathWorks/ServiceHost/clr-df9a0cbb6bd34e079ef626671d1a7b7c/_tmp_MSHI_5363-9225-767d-e56f/mci/_tempinstaller_glnxa64/bin/glnxa64/InstallMathWorksServiceHost: symbol lookup error: /usr/lib64/libcairo.so.2: undefined symbol: xcb_shm_id
Unexpected exception: ‘N7mwboost10wrapexceptINS_16exception_detail39current_exception_std_exception_wrapperISt13runtime_errorEEEE: Error loading /home/pblase/matlab/bin/glnxa64/matlab_startup_plugins/matlab_graphics_ui/mwuixloader.so. /usr/lib64/libXt.so.6: undefined symbol: SmcModifyCallbacks: Success: Success’ in createMVMAndCallParser phase ‘Creating local MVM’ libcairo MATLAB Answers — New Questions
Intro to matlab lab and I have no idea how this works
<</matlabcentral/answers/uploaded_files/1765134/Screenshot%202024-09-02%20at%206.21.33%E2%80%AFPM.png>>
I don’t know what I am supposed to do with the second part of question 3 and also don’t know what to do with #4. This is my first time ever taking a class about coding so I’m super lost.<</matlabcentral/answers/uploaded_files/1765134/Screenshot%202024-09-02%20at%206.21.33%E2%80%AFPM.png>>
I don’t know what I am supposed to do with the second part of question 3 and also don’t know what to do with #4. This is my first time ever taking a class about coding so I’m super lost. <</matlabcentral/answers/uploaded_files/1765134/Screenshot%202024-09-02%20at%206.21.33%E2%80%AFPM.png>>
I don’t know what I am supposed to do with the second part of question 3 and also don’t know what to do with #4. This is my first time ever taking a class about coding so I’m super lost. vector, vectors, variable MATLAB Answers — New Questions
Poor performance of linprog in practice
I have to solve a dynamic programming problem using a linear programming approach. For details, please see this paper. The LP that I want to solve is:
min c’*v
s.t.
A*v>=u,
where c is n*1, v is n*1, A is n^2*n, u is n^2*1.
The min is with respect to v, the value function of the original DP problem. I have a moderate number of variables, n=300 and m=n^2*n=90000 linear inequalities as constraints. No bound constraints on v.
I use the Matlab function linprog which in turn is based on the solver HIGHS (since R2024a). The code is slow for my purposes (i.e. a brute-force value iteration is much faster). Moreover, linprog gives correct results only if I set the option ‘Algorithm’,’dual-simplex-highs’. With other algorithms, it gets stuck.
After profiling the code, it turns out that the bottleneck is line 377 of linprog:
[x, fval, exitflag, output, lambda] = run(algorithm, problem);
I was wondering if there is a way to speed up the code. Any help or suggestion is greatly appreciated! I put below a MWE to illustrate the problem.
clear,clc,close all
%% Set parameters
crra = 2;
alpha = 0.36;
beta = 0.95;
delta = 0.1;
%% Grid for capital
k_ss = ((1-beta*(1-delta))/(alpha*beta))^(1/(alpha-1));
n_k = 300;
k_grid = linspace(0.1*k_ss,1.5*k_ss,n_k)’;
%% Build current return matrix, U(k’,k)
cons = k_grid’.^alpha+(1-delta)*k_grid’-k_grid;
U_mat = f_util(cons,crra);
U_mat(cons<=0) = -inf;
%% Using LINEAR PROGRAMMING
% min c’*v
% s.t.
% A*v>=u, where c is n*1, v is n*1, A is n^2*n, u is n^2*1
n = length(k_grid);
c_vec = ones(n,1);
u_vec = U_mat(:); %% U(k’,k), stack columnwise
%% Build A matrix using cell-based method
tic
A = cell(n,1);
bigI = (-beta)*speye(n);
for i=1:n
temp = bigI;
temp(:,i) = temp(:,i)+1;
A{i} = temp;
end
A = vertcat(A{:});
disp(‘Time to build A matrix with cell method:’)
toc
%% Call linprog
% ‘dual-simplex-highs’ (default and by far the best)
options = optimoptions(‘linprog’,’Algorithm’,’dual-simplex-highs’);
tic
[V_lin,fval,exitflag,output] = linprog(c_vec,-A,-u_vec,[],[],[],[],options);
disp(‘Time linear programming:’)
toc
if exitflag<=0
warning(‘linprog did not find a solution’)
fprintf(‘exitflag = %d n’,exitflag)
end
%% Now that we solved for V, compute policy function
RHS_mat = U_mat+beta*V_lin; % (k’,k)
[V1,pol_k_ind] = max(RHS_mat,[],1);
pol_k = k_grid(pol_k_ind);
% Plots
figure
plot(k_grid,V1)
figure
plot(k_grid,k_grid,’–‘,k_grid,pol_k)
function util = f_util(c,crra)
util = c.^(1-crra)/(1-crra);
end
PROFILEI have to solve a dynamic programming problem using a linear programming approach. For details, please see this paper. The LP that I want to solve is:
min c’*v
s.t.
A*v>=u,
where c is n*1, v is n*1, A is n^2*n, u is n^2*1.
The min is with respect to v, the value function of the original DP problem. I have a moderate number of variables, n=300 and m=n^2*n=90000 linear inequalities as constraints. No bound constraints on v.
I use the Matlab function linprog which in turn is based on the solver HIGHS (since R2024a). The code is slow for my purposes (i.e. a brute-force value iteration is much faster). Moreover, linprog gives correct results only if I set the option ‘Algorithm’,’dual-simplex-highs’. With other algorithms, it gets stuck.
After profiling the code, it turns out that the bottleneck is line 377 of linprog:
[x, fval, exitflag, output, lambda] = run(algorithm, problem);
I was wondering if there is a way to speed up the code. Any help or suggestion is greatly appreciated! I put below a MWE to illustrate the problem.
clear,clc,close all
%% Set parameters
crra = 2;
alpha = 0.36;
beta = 0.95;
delta = 0.1;
%% Grid for capital
k_ss = ((1-beta*(1-delta))/(alpha*beta))^(1/(alpha-1));
n_k = 300;
k_grid = linspace(0.1*k_ss,1.5*k_ss,n_k)’;
%% Build current return matrix, U(k’,k)
cons = k_grid’.^alpha+(1-delta)*k_grid’-k_grid;
U_mat = f_util(cons,crra);
U_mat(cons<=0) = -inf;
%% Using LINEAR PROGRAMMING
% min c’*v
% s.t.
% A*v>=u, where c is n*1, v is n*1, A is n^2*n, u is n^2*1
n = length(k_grid);
c_vec = ones(n,1);
u_vec = U_mat(:); %% U(k’,k), stack columnwise
%% Build A matrix using cell-based method
tic
A = cell(n,1);
bigI = (-beta)*speye(n);
for i=1:n
temp = bigI;
temp(:,i) = temp(:,i)+1;
A{i} = temp;
end
A = vertcat(A{:});
disp(‘Time to build A matrix with cell method:’)
toc
%% Call linprog
% ‘dual-simplex-highs’ (default and by far the best)
options = optimoptions(‘linprog’,’Algorithm’,’dual-simplex-highs’);
tic
[V_lin,fval,exitflag,output] = linprog(c_vec,-A,-u_vec,[],[],[],[],options);
disp(‘Time linear programming:’)
toc
if exitflag<=0
warning(‘linprog did not find a solution’)
fprintf(‘exitflag = %d n’,exitflag)
end
%% Now that we solved for V, compute policy function
RHS_mat = U_mat+beta*V_lin; % (k’,k)
[V1,pol_k_ind] = max(RHS_mat,[],1);
pol_k = k_grid(pol_k_ind);
% Plots
figure
plot(k_grid,V1)
figure
plot(k_grid,k_grid,’–‘,k_grid,pol_k)
function util = f_util(c,crra)
util = c.^(1-crra)/(1-crra);
end
PROFILE I have to solve a dynamic programming problem using a linear programming approach. For details, please see this paper. The LP that I want to solve is:
min c’*v
s.t.
A*v>=u,
where c is n*1, v is n*1, A is n^2*n, u is n^2*1.
The min is with respect to v, the value function of the original DP problem. I have a moderate number of variables, n=300 and m=n^2*n=90000 linear inequalities as constraints. No bound constraints on v.
I use the Matlab function linprog which in turn is based on the solver HIGHS (since R2024a). The code is slow for my purposes (i.e. a brute-force value iteration is much faster). Moreover, linprog gives correct results only if I set the option ‘Algorithm’,’dual-simplex-highs’. With other algorithms, it gets stuck.
After profiling the code, it turns out that the bottleneck is line 377 of linprog:
[x, fval, exitflag, output, lambda] = run(algorithm, problem);
I was wondering if there is a way to speed up the code. Any help or suggestion is greatly appreciated! I put below a MWE to illustrate the problem.
clear,clc,close all
%% Set parameters
crra = 2;
alpha = 0.36;
beta = 0.95;
delta = 0.1;
%% Grid for capital
k_ss = ((1-beta*(1-delta))/(alpha*beta))^(1/(alpha-1));
n_k = 300;
k_grid = linspace(0.1*k_ss,1.5*k_ss,n_k)’;
%% Build current return matrix, U(k’,k)
cons = k_grid’.^alpha+(1-delta)*k_grid’-k_grid;
U_mat = f_util(cons,crra);
U_mat(cons<=0) = -inf;
%% Using LINEAR PROGRAMMING
% min c’*v
% s.t.
% A*v>=u, where c is n*1, v is n*1, A is n^2*n, u is n^2*1
n = length(k_grid);
c_vec = ones(n,1);
u_vec = U_mat(:); %% U(k’,k), stack columnwise
%% Build A matrix using cell-based method
tic
A = cell(n,1);
bigI = (-beta)*speye(n);
for i=1:n
temp = bigI;
temp(:,i) = temp(:,i)+1;
A{i} = temp;
end
A = vertcat(A{:});
disp(‘Time to build A matrix with cell method:’)
toc
%% Call linprog
% ‘dual-simplex-highs’ (default and by far the best)
options = optimoptions(‘linprog’,’Algorithm’,’dual-simplex-highs’);
tic
[V_lin,fval,exitflag,output] = linprog(c_vec,-A,-u_vec,[],[],[],[],options);
disp(‘Time linear programming:’)
toc
if exitflag<=0
warning(‘linprog did not find a solution’)
fprintf(‘exitflag = %d n’,exitflag)
end
%% Now that we solved for V, compute policy function
RHS_mat = U_mat+beta*V_lin; % (k’,k)
[V1,pol_k_ind] = max(RHS_mat,[],1);
pol_k = k_grid(pol_k_ind);
% Plots
figure
plot(k_grid,V1)
figure
plot(k_grid,k_grid,’–‘,k_grid,pol_k)
function util = f_util(c,crra)
util = c.^(1-crra)/(1-crra);
end
PROFILE linprog, performance MATLAB Answers — New Questions
How to import .EEG or text or excel file to EEGlab
Hi all I’ve 1-hour EEG data with a sampling frequency 291hz.I’ve installed EEGlab v14.1.1 version and tried to load my data files of ‘.EEG file’,’text’ and ‘excel’formats, but none of them are loading to EEGlab.It’s showing the following error. Please help me to slove this issue since I’m new to this EEGlab softwareHi all I’ve 1-hour EEG data with a sampling frequency 291hz.I’ve installed EEGlab v14.1.1 version and tried to load my data files of ‘.EEG file’,’text’ and ‘excel’formats, but none of them are loading to EEGlab.It’s showing the following error. Please help me to slove this issue since I’m new to this EEGlab software Hi all I’ve 1-hour EEG data with a sampling frequency 291hz.I’ve installed EEGlab v14.1.1 version and tried to load my data files of ‘.EEG file’,’text’ and ‘excel’formats, but none of them are loading to EEGlab.It’s showing the following error. Please help me to slove this issue since I’m new to this EEGlab software eeg, eeglab, signal processing MATLAB Answers — New Questions