Category: Matlab
Category Archives: Matlab
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
Using symbolic solver, I seem to not be able to get a system of equations that give me a desired answer. Does a solution not exist?
syms V1 V2 Vp Vn Vxp Vxn Vpx Vnx
syms Rp Rx Rn positive
Ison=((Vp/((Rp*68220)/(Rp+68220)))-(Vxp/((Rx*68220)/(Rx+68220))));
equ1=Vp==(V1+V2)-Ison*Rn;
Isop=((Vn/((Rn*68220)/(Rn+68220)))-(Vxn/((Rx*68220)/(Rx+68220))));
equ2=Vn==(V1+V2)-Isop*Rp;
Isox=((Vnx/((Rn*68220)/(Rn+68220)))-(Vpx/((Rp*68220)/(Rp+68220))));
equ3= Vpx==V1+Rx*Isox;
[Rn, Rp, Rx] = solve([equ1, equ2,equ3],[Rn , Rp, Rx]);
simplify(Rn)
simplify(Rp)
simplify(Rx)
Rn=vpa(subs(Rn,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
Rp=vpa(subs(Rp,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
Rx=vpa(subs(Rx,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
So I am trying to find values for Rn,Rx and Rp. I have three equations and three unknowns. When I use solve to find symbolic equation, I get equations for each variable. But when I sub real values in, I get an answer that is wrong or doesnt make sense. Adding assume doesnt seem to change anything and the return conditions is the same as the equations. The real values of Rn, Rp and Rx should be 2e6,1.5e6 and 700k. If you were to put these values in the original equations, you can verify that these values are correct. How do I get a system of equations that will give me the desired answer?syms V1 V2 Vp Vn Vxp Vxn Vpx Vnx
syms Rp Rx Rn positive
Ison=((Vp/((Rp*68220)/(Rp+68220)))-(Vxp/((Rx*68220)/(Rx+68220))));
equ1=Vp==(V1+V2)-Ison*Rn;
Isop=((Vn/((Rn*68220)/(Rn+68220)))-(Vxn/((Rx*68220)/(Rx+68220))));
equ2=Vn==(V1+V2)-Isop*Rp;
Isox=((Vnx/((Rn*68220)/(Rn+68220)))-(Vpx/((Rp*68220)/(Rp+68220))));
equ3= Vpx==V1+Rx*Isox;
[Rn, Rp, Rx] = solve([equ1, equ2,equ3],[Rn , Rp, Rx]);
simplify(Rn)
simplify(Rp)
simplify(Rx)
Rn=vpa(subs(Rn,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
Rp=vpa(subs(Rp,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
Rx=vpa(subs(Rx,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
So I am trying to find values for Rn,Rx and Rp. I have three equations and three unknowns. When I use solve to find symbolic equation, I get equations for each variable. But when I sub real values in, I get an answer that is wrong or doesnt make sense. Adding assume doesnt seem to change anything and the return conditions is the same as the equations. The real values of Rn, Rp and Rx should be 2e6,1.5e6 and 700k. If you were to put these values in the original equations, you can verify that these values are correct. How do I get a system of equations that will give me the desired answer? syms V1 V2 Vp Vn Vxp Vxn Vpx Vnx
syms Rp Rx Rn positive
Ison=((Vp/((Rp*68220)/(Rp+68220)))-(Vxp/((Rx*68220)/(Rx+68220))));
equ1=Vp==(V1+V2)-Ison*Rn;
Isop=((Vn/((Rn*68220)/(Rn+68220)))-(Vxn/((Rx*68220)/(Rx+68220))));
equ2=Vn==(V1+V2)-Isop*Rp;
Isox=((Vnx/((Rn*68220)/(Rn+68220)))-(Vpx/((Rp*68220)/(Rp+68220))));
equ3= Vpx==V1+Rx*Isox;
[Rn, Rp, Rx] = solve([equ1, equ2,equ3],[Rn , Rp, Rx]);
simplify(Rn)
simplify(Rp)
simplify(Rx)
Rn=vpa(subs(Rn,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
Rp=vpa(subs(Rp,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
Rx=vpa(subs(Rx,{V1,V2,Vp,Vn,Vxp,Vxn,Vpx,Vnx},{270,270,144.56868,147.38892,125.43132,122.61108,268.58987,271.41013}))
So I am trying to find values for Rn,Rx and Rp. I have three equations and three unknowns. When I use solve to find symbolic equation, I get equations for each variable. But when I sub real values in, I get an answer that is wrong or doesnt make sense. Adding assume doesnt seem to change anything and the return conditions is the same as the equations. The real values of Rn, Rp and Rx should be 2e6,1.5e6 and 700k. If you were to put these values in the original equations, you can verify that these values are correct. How do I get a system of equations that will give me the desired answer? solve, symbolic MATLAB Answers — New Questions
filtfilt provides excessive transient
I observed that ‘filtfilt’ suffers from an undesired behavior when I provide IIR bandpass filters having steep transition bands. Specifically, the output signal exhibits excessive transient response; nevertheless, this behaviour does not emerge if I use a ‘home-made’ version of zerophase filtering based on ‘filter’. I guess that it is not a numerical issue involving the filter coefficients or structure, nor the ‘filter’ function.
% design bandpass filter having transition bandwidth of 200 Hz (Fs = 8000)
bp = designfilt(‘bandpassiir’, ‘StopbandFrequency1’, 50, ‘PassbandFrequency1’, 250,…
‘PassbandFrequency2’, 3600, ‘StopbandFrequency2’, 3700, ‘StopbandAttenuation1’, 30,…
‘PassbandRipple’, 0.1, ‘StopbandAttenuation2’, 30, ‘SampleRate’, 8000, ‘DesignMethod’, ‘cheby2’);
% check stability
assert(isstable(bp),’Unstable filter’);
% apply filtfilt to a random (white) long input signal; output signal shows an undesirable transient
x = randn(2^20,1);
y = filtfilt(bp,x);
% apply ‘home-made’ filtfilt to the same input; output signal shows a more accptable transient
y2 = flipud(filter(bp,flipud(filter(bp,x))));
% compare effects
figure; semilogy(abs(y-y2));
As a rule of thumb, the effect grows as the transition bands get narrower, while it tends to vanish as they get broader.
Where is the problem? Have I missed some recommendations or hints in the function’s help?I observed that ‘filtfilt’ suffers from an undesired behavior when I provide IIR bandpass filters having steep transition bands. Specifically, the output signal exhibits excessive transient response; nevertheless, this behaviour does not emerge if I use a ‘home-made’ version of zerophase filtering based on ‘filter’. I guess that it is not a numerical issue involving the filter coefficients or structure, nor the ‘filter’ function.
% design bandpass filter having transition bandwidth of 200 Hz (Fs = 8000)
bp = designfilt(‘bandpassiir’, ‘StopbandFrequency1’, 50, ‘PassbandFrequency1’, 250,…
‘PassbandFrequency2’, 3600, ‘StopbandFrequency2’, 3700, ‘StopbandAttenuation1’, 30,…
‘PassbandRipple’, 0.1, ‘StopbandAttenuation2’, 30, ‘SampleRate’, 8000, ‘DesignMethod’, ‘cheby2’);
% check stability
assert(isstable(bp),’Unstable filter’);
% apply filtfilt to a random (white) long input signal; output signal shows an undesirable transient
x = randn(2^20,1);
y = filtfilt(bp,x);
% apply ‘home-made’ filtfilt to the same input; output signal shows a more accptable transient
y2 = flipud(filter(bp,flipud(filter(bp,x))));
% compare effects
figure; semilogy(abs(y-y2));
As a rule of thumb, the effect grows as the transition bands get narrower, while it tends to vanish as they get broader.
Where is the problem? Have I missed some recommendations or hints in the function’s help? I observed that ‘filtfilt’ suffers from an undesired behavior when I provide IIR bandpass filters having steep transition bands. Specifically, the output signal exhibits excessive transient response; nevertheless, this behaviour does not emerge if I use a ‘home-made’ version of zerophase filtering based on ‘filter’. I guess that it is not a numerical issue involving the filter coefficients or structure, nor the ‘filter’ function.
% design bandpass filter having transition bandwidth of 200 Hz (Fs = 8000)
bp = designfilt(‘bandpassiir’, ‘StopbandFrequency1’, 50, ‘PassbandFrequency1’, 250,…
‘PassbandFrequency2’, 3600, ‘StopbandFrequency2’, 3700, ‘StopbandAttenuation1’, 30,…
‘PassbandRipple’, 0.1, ‘StopbandAttenuation2’, 30, ‘SampleRate’, 8000, ‘DesignMethod’, ‘cheby2’);
% check stability
assert(isstable(bp),’Unstable filter’);
% apply filtfilt to a random (white) long input signal; output signal shows an undesirable transient
x = randn(2^20,1);
y = filtfilt(bp,x);
% apply ‘home-made’ filtfilt to the same input; output signal shows a more accptable transient
y2 = flipud(filter(bp,flipud(filter(bp,x))));
% compare effects
figure; semilogy(abs(y-y2));
As a rule of thumb, the effect grows as the transition bands get narrower, while it tends to vanish as they get broader.
Where is the problem? Have I missed some recommendations or hints in the function’s help? filtfilt, numerical stability, transient effects MATLAB Answers — New Questions
Reading Bytes from Arduino to MATLAB
I’ve been trying to read data from ESP32S-Dev module to MATLAB sending over the data in bytes to make the transmission quicker. As seen below, I convert float data into bytes and then write the data. MATLAB sees the data and then creates a 1×8 array for each float value instead of just 1 value for each float. I’ve tried other methods, shown in 2nd part of MATLAB code, and it creates 1 value for each float but their wildly off (7-34 orders of magnitude)
I’ve tried different baud rates and even asked for help from the almighty ChatGPT but have not been able to crack the code. Any thoughts.
Arduino IDE code:
#include <SPI.h>
const int CS_SiPM_pot = 34;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200); //Starting
delay(1000);
SPI.begin();
pinMode(CS_SiPM_pot, OUTPUT);
}
void loop() {
for (int d_pot2 = 55; d_pot2 <= 55; d_pot2 = d_pot2 + 1) //57
{
digitalWrite(CS_SiPM_pot, LOW); //LOW
delay(10); //10
SPI.transfer(d_pot2);
digitalWrite(CS_SiPM_pot, HIGH);
// put your main code here, to run repeatedly:
float newTmp[4] = { 01.00, 02.00, 03.00, 04.00 };
for (int i = 0; i < 4; i++) {
byte *byteData = (byte *)&newTmp[i];
Serial.write(byteData, sizeof(float)); // Send each float as 4 bytes
delay(10);
}
}
}
MATLAB code:
esp = serialport(‘COM5’,152000);
%%
flush(esp)
% Read 16 bytes of data (4 floats * 4 bytes per float)
numBytes = 16;
data = read(esp, numBytes, ‘uint8’);
% Convert each 4-byte sequence to a float
float1 = typecast(data(1:4)), ‘single’);
float2 = typecast(data(5:8), ‘single’);
float3 = typecast(data(9:12), ‘single’);
float4 = typecast(data(13:16), ‘single’);
disp([float1, float2, float3, float4]);
% Convert the bytes back to float values
floatValues = typecast(uint8(data), ‘single’);
% Display the result
disp(‘Float values:’);
disp(floatValues);
disp(‘Raw bytes received:’);
disp(data); % Print the raw bytes
Results from MATLAB:
Float1: 0 0 0 0 0 0 0 0
Float2: 0 3.7480 0 0 0 0 0 0
Float3: 0 2.1250 0 3.7480 0 0 0 0
Float4: 0 0 0 0 0 3.7480 0 0
data: 0 0 0 0 255 0 0 0 3 255 0 0 0 0 255 0I’ve been trying to read data from ESP32S-Dev module to MATLAB sending over the data in bytes to make the transmission quicker. As seen below, I convert float data into bytes and then write the data. MATLAB sees the data and then creates a 1×8 array for each float value instead of just 1 value for each float. I’ve tried other methods, shown in 2nd part of MATLAB code, and it creates 1 value for each float but their wildly off (7-34 orders of magnitude)
I’ve tried different baud rates and even asked for help from the almighty ChatGPT but have not been able to crack the code. Any thoughts.
Arduino IDE code:
#include <SPI.h>
const int CS_SiPM_pot = 34;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200); //Starting
delay(1000);
SPI.begin();
pinMode(CS_SiPM_pot, OUTPUT);
}
void loop() {
for (int d_pot2 = 55; d_pot2 <= 55; d_pot2 = d_pot2 + 1) //57
{
digitalWrite(CS_SiPM_pot, LOW); //LOW
delay(10); //10
SPI.transfer(d_pot2);
digitalWrite(CS_SiPM_pot, HIGH);
// put your main code here, to run repeatedly:
float newTmp[4] = { 01.00, 02.00, 03.00, 04.00 };
for (int i = 0; i < 4; i++) {
byte *byteData = (byte *)&newTmp[i];
Serial.write(byteData, sizeof(float)); // Send each float as 4 bytes
delay(10);
}
}
}
MATLAB code:
esp = serialport(‘COM5’,152000);
%%
flush(esp)
% Read 16 bytes of data (4 floats * 4 bytes per float)
numBytes = 16;
data = read(esp, numBytes, ‘uint8’);
% Convert each 4-byte sequence to a float
float1 = typecast(data(1:4)), ‘single’);
float2 = typecast(data(5:8), ‘single’);
float3 = typecast(data(9:12), ‘single’);
float4 = typecast(data(13:16), ‘single’);
disp([float1, float2, float3, float4]);
% Convert the bytes back to float values
floatValues = typecast(uint8(data), ‘single’);
% Display the result
disp(‘Float values:’);
disp(floatValues);
disp(‘Raw bytes received:’);
disp(data); % Print the raw bytes
Results from MATLAB:
Float1: 0 0 0 0 0 0 0 0
Float2: 0 3.7480 0 0 0 0 0 0
Float3: 0 2.1250 0 3.7480 0 0 0 0
Float4: 0 0 0 0 0 3.7480 0 0
data: 0 0 0 0 255 0 0 0 3 255 0 0 0 0 255 0 I’ve been trying to read data from ESP32S-Dev module to MATLAB sending over the data in bytes to make the transmission quicker. As seen below, I convert float data into bytes and then write the data. MATLAB sees the data and then creates a 1×8 array for each float value instead of just 1 value for each float. I’ve tried other methods, shown in 2nd part of MATLAB code, and it creates 1 value for each float but their wildly off (7-34 orders of magnitude)
I’ve tried different baud rates and even asked for help from the almighty ChatGPT but have not been able to crack the code. Any thoughts.
Arduino IDE code:
#include <SPI.h>
const int CS_SiPM_pot = 34;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200); //Starting
delay(1000);
SPI.begin();
pinMode(CS_SiPM_pot, OUTPUT);
}
void loop() {
for (int d_pot2 = 55; d_pot2 <= 55; d_pot2 = d_pot2 + 1) //57
{
digitalWrite(CS_SiPM_pot, LOW); //LOW
delay(10); //10
SPI.transfer(d_pot2);
digitalWrite(CS_SiPM_pot, HIGH);
// put your main code here, to run repeatedly:
float newTmp[4] = { 01.00, 02.00, 03.00, 04.00 };
for (int i = 0; i < 4; i++) {
byte *byteData = (byte *)&newTmp[i];
Serial.write(byteData, sizeof(float)); // Send each float as 4 bytes
delay(10);
}
}
}
MATLAB code:
esp = serialport(‘COM5’,152000);
%%
flush(esp)
% Read 16 bytes of data (4 floats * 4 bytes per float)
numBytes = 16;
data = read(esp, numBytes, ‘uint8’);
% Convert each 4-byte sequence to a float
float1 = typecast(data(1:4)), ‘single’);
float2 = typecast(data(5:8), ‘single’);
float3 = typecast(data(9:12), ‘single’);
float4 = typecast(data(13:16), ‘single’);
disp([float1, float2, float3, float4]);
% Convert the bytes back to float values
floatValues = typecast(uint8(data), ‘single’);
% Display the result
disp(‘Float values:’);
disp(floatValues);
disp(‘Raw bytes received:’);
disp(data); % Print the raw bytes
Results from MATLAB:
Float1: 0 0 0 0 0 0 0 0
Float2: 0 3.7480 0 0 0 0 0 0
Float3: 0 2.1250 0 3.7480 0 0 0 0
Float4: 0 0 0 0 0 3.7480 0 0
data: 0 0 0 0 255 0 0 0 3 255 0 0 0 0 255 0 arduino, esp32, matlab, serialport, float-to-bytes MATLAB Answers — New Questions
When the orientation of the object changed, how to measure the force on each support point?
Thank you for your interest in my question.
If we assume that there is a box with x, y, z-axis lengths of [1, 0.5, 0.2] (m) , weight is m=100kg,
and set the center point as the origin frame. At this time, if we support the force of m*g/4 at each of the four points [0.5, 0.25, -0.1], [0.5, -0.25, -0.1], [-0.5, -0.25, -0.1], [-0.5, 0.25, -0.1], the object will stay statically.
Then, if the box rotates 30 degrees about the x-axis, I can’t measure the force applied at the four corners of the box.
As the box rotates, the coordinate frame of the corner also rotates.
If the box rotates 45 degrees for y-axis after rotating 30 degree for the x-axis,
how should we apply force to each point so that the box stays still?Thank you for your interest in my question.
If we assume that there is a box with x, y, z-axis lengths of [1, 0.5, 0.2] (m) , weight is m=100kg,
and set the center point as the origin frame. At this time, if we support the force of m*g/4 at each of the four points [0.5, 0.25, -0.1], [0.5, -0.25, -0.1], [-0.5, -0.25, -0.1], [-0.5, 0.25, -0.1], the object will stay statically.
Then, if the box rotates 30 degrees about the x-axis, I can’t measure the force applied at the four corners of the box.
As the box rotates, the coordinate frame of the corner also rotates.
If the box rotates 45 degrees for y-axis after rotating 30 degree for the x-axis,
how should we apply force to each point so that the box stays still? Thank you for your interest in my question.
If we assume that there is a box with x, y, z-axis lengths of [1, 0.5, 0.2] (m) , weight is m=100kg,
and set the center point as the origin frame. At this time, if we support the force of m*g/4 at each of the four points [0.5, 0.25, -0.1], [0.5, -0.25, -0.1], [-0.5, -0.25, -0.1], [-0.5, 0.25, -0.1], the object will stay statically.
Then, if the box rotates 30 degrees about the x-axis, I can’t measure the force applied at the four corners of the box.
As the box rotates, the coordinate frame of the corner also rotates.
If the box rotates 45 degrees for y-axis after rotating 30 degree for the x-axis,
how should we apply force to each point so that the box stays still? force, gravity compensation MATLAB Answers — New Questions
Hi! I created a bad script a long time ago (months) and it has essentially destroyed my Matlab Online. I cannot run any other script without that old error occurring
The Summery is essentially it. I created a script four months ago and accidentially used the wrong syntax (&&) and it has corrupted my Matlab Online. I can run scripts with only comments, but as soon as I add anything else I get the errors back.
Help? I am so confused
Script I am running:
%% Problem 1
k1 = 10;
k2 = 5;
k3 = 8;
k4 = 10;
k5 = 20;
L1 = [1 0 0 0;
0 1 0 0]
Error Message:
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to
reduce operands to logical scalar values.
Error in internal.matlab.variableeditor.Actions.struct.EditActionBase/UpdateActionState (line 33)
editable = height(sRows) == 1 && (sRows(2)-sRows(1)+1 == 1);
Error in internal.matlab.variableeditor.VEActionDataService/updateActionStates (line 138)
action.UpdateActionState();
Error in internal.matlab.variableeditor.VEActionDataService/enableListenersAndUpdateActionStates (line 84)
this.updateActionStates();
Error in internal.matlab.variableeditor.VEActionDataService/initActionStates (line 54)
this.enableListenersAndUpdateActionStates();
Error in internal.matlab.datatoolsservices.actiondataservice.ActionManager/initActions (line 55)
this.ActionDataService.initActionStates();
Error in internal.matlab.variableeditor.peer.RemoteManager/callInitActionOnIdle (line 376)
ActionManager.initActions(startPath, classType);
Error in internal.matlab.variableeditor.peer.RemoteManager>@()this.callInitActionOnIdle(actionNamespace,startPath,classType,ActionManager) (line 121)
builtin(‘_dtcallback’, @() this.callInitActionOnIdle(actionNamespace, startPath, classType, ActionManager), …The Summery is essentially it. I created a script four months ago and accidentially used the wrong syntax (&&) and it has corrupted my Matlab Online. I can run scripts with only comments, but as soon as I add anything else I get the errors back.
Help? I am so confused
Script I am running:
%% Problem 1
k1 = 10;
k2 = 5;
k3 = 8;
k4 = 10;
k5 = 20;
L1 = [1 0 0 0;
0 1 0 0]
Error Message:
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to
reduce operands to logical scalar values.
Error in internal.matlab.variableeditor.Actions.struct.EditActionBase/UpdateActionState (line 33)
editable = height(sRows) == 1 && (sRows(2)-sRows(1)+1 == 1);
Error in internal.matlab.variableeditor.VEActionDataService/updateActionStates (line 138)
action.UpdateActionState();
Error in internal.matlab.variableeditor.VEActionDataService/enableListenersAndUpdateActionStates (line 84)
this.updateActionStates();
Error in internal.matlab.variableeditor.VEActionDataService/initActionStates (line 54)
this.enableListenersAndUpdateActionStates();
Error in internal.matlab.datatoolsservices.actiondataservice.ActionManager/initActions (line 55)
this.ActionDataService.initActionStates();
Error in internal.matlab.variableeditor.peer.RemoteManager/callInitActionOnIdle (line 376)
ActionManager.initActions(startPath, classType);
Error in internal.matlab.variableeditor.peer.RemoteManager>@()this.callInitActionOnIdle(actionNamespace,startPath,classType,ActionManager) (line 121)
builtin(‘_dtcallback’, @() this.callInitActionOnIdle(actionNamespace, startPath, classType, ActionManager), … The Summery is essentially it. I created a script four months ago and accidentially used the wrong syntax (&&) and it has corrupted my Matlab Online. I can run scripts with only comments, but as soon as I add anything else I get the errors back.
Help? I am so confused
Script I am running:
%% Problem 1
k1 = 10;
k2 = 5;
k3 = 8;
k4 = 10;
k5 = 20;
L1 = [1 0 0 0;
0 1 0 0]
Error Message:
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to
reduce operands to logical scalar values.
Error in internal.matlab.variableeditor.Actions.struct.EditActionBase/UpdateActionState (line 33)
editable = height(sRows) == 1 && (sRows(2)-sRows(1)+1 == 1);
Error in internal.matlab.variableeditor.VEActionDataService/updateActionStates (line 138)
action.UpdateActionState();
Error in internal.matlab.variableeditor.VEActionDataService/enableListenersAndUpdateActionStates (line 84)
this.updateActionStates();
Error in internal.matlab.variableeditor.VEActionDataService/initActionStates (line 54)
this.enableListenersAndUpdateActionStates();
Error in internal.matlab.datatoolsservices.actiondataservice.ActionManager/initActions (line 55)
this.ActionDataService.initActionStates();
Error in internal.matlab.variableeditor.peer.RemoteManager/callInitActionOnIdle (line 376)
ActionManager.initActions(startPath, classType);
Error in internal.matlab.variableeditor.peer.RemoteManager>@()this.callInitActionOnIdle(actionNamespace,startPath,classType,ActionManager) (line 121)
builtin(‘_dtcallback’, @() this.callInitActionOnIdle(actionNamespace, startPath, classType, ActionManager), … help, persistent error, have i broken matlab? MATLAB Answers — New Questions
HTML file to PDF file, deal with base64,svg picture problem solution.
HTML file to PDF file, error when processing base64,svg imagesHTML file to PDF file, error when processing base64,svg images HTML file to PDF file, error when processing base64,svg images html, simulink, pdf MATLAB Answers — New Questions
Include rows containing specific value
I have a 1400*9 table (1400 rows and 9 columns) in MATLAB workspace. Each column has a different name. I want to select rows containing specific value. For example, how can I create a new table containig all rows with value of 0.456 in the column named "Biology"? I tried to use following code, but it gave error.
newData=[Data(find(Data.Biology == 0.456, :))]I have a 1400*9 table (1400 rows and 9 columns) in MATLAB workspace. Each column has a different name. I want to select rows containing specific value. For example, how can I create a new table containig all rows with value of 0.456 in the column named "Biology"? I tried to use following code, but it gave error.
newData=[Data(find(Data.Biology == 0.456, :))] I have a 1400*9 table (1400 rows and 9 columns) in MATLAB workspace. Each column has a different name. I want to select rows containing specific value. For example, how can I create a new table containig all rows with value of 0.456 in the column named "Biology"? I tried to use following code, but it gave error.
newData=[Data(find(Data.Biology == 0.456, :))] table, find MATLAB Answers — New Questions
Force saved figure to use a specific number of pixels
I am saving different maps, I need to compare some specific pixels, but Matlab somehow adds a line at the bottom (3 pixels) for example when I save my image, which kills everything I try to do later. Is there any method to force exportgraphics to use X pixels horizontally and Y vertically (I mean height and width)? Or when I call my figure to be X and Y dimensions? Force it not to add this line. I tried exportgraphics/export_fig they both fail at it.
It is not random, as only some specific files get the line added and always even if I try to replot, I still did not figure out why this happens, my data have the same resolution/grid.I am saving different maps, I need to compare some specific pixels, but Matlab somehow adds a line at the bottom (3 pixels) for example when I save my image, which kills everything I try to do later. Is there any method to force exportgraphics to use X pixels horizontally and Y vertically (I mean height and width)? Or when I call my figure to be X and Y dimensions? Force it not to add this line. I tried exportgraphics/export_fig they both fail at it.
It is not random, as only some specific files get the line added and always even if I try to replot, I still did not figure out why this happens, my data have the same resolution/grid. I am saving different maps, I need to compare some specific pixels, but Matlab somehow adds a line at the bottom (3 pixels) for example when I save my image, which kills everything I try to do later. Is there any method to force exportgraphics to use X pixels horizontally and Y vertically (I mean height and width)? Or when I call my figure to be X and Y dimensions? Force it not to add this line. I tried exportgraphics/export_fig they both fail at it.
It is not random, as only some specific files get the line added and always even if I try to replot, I still did not figure out why this happens, my data have the same resolution/grid. image-processing, exportgraphics MATLAB Answers — New Questions
Working in Excel with live on MATLAB
On matlab, I am going to import an Excel file and work on it live in real time.
If I change the value in Excel, I want to reflect it in real time in MATLAB.
However, as far as I know, if you modify it without saving the Excel, it cannot be applied in MATLAB right away.
Is there a way to solve this?On matlab, I am going to import an Excel file and work on it live in real time.
If I change the value in Excel, I want to reflect it in real time in MATLAB.
However, as far as I know, if you modify it without saving the Excel, it cannot be applied in MATLAB right away.
Is there a way to solve this? On matlab, I am going to import an Excel file and work on it live in real time.
If I change the value in Excel, I want to reflect it in real time in MATLAB.
However, as far as I know, if you modify it without saving the Excel, it cannot be applied in MATLAB right away.
Is there a way to solve this? excel, live MATLAB Answers — New Questions