Tag Archives: matlab
TD3 agent fails to explore again after hitting the max action and gets stuck at the max action value. Additionally, the Q0 value exploded to large value.
The range of the a single action = 0.01 to 5. During learning using TD3, the learning is consist. However, if the agent applies the maximum values, it get stuck fails to explores lower values and suddenly does not improve or deteriorate further. I am not sure what could be the reason. The Q0 value explodes at this point. at this point.The range of the a single action = 0.01 to 5. During learning using TD3, the learning is consist. However, if the agent applies the maximum values, it get stuck fails to explores lower values and suddenly does not improve or deteriorate further. I am not sure what could be the reason. The Q0 value explodes at this point. at this point. The range of the a single action = 0.01 to 5. During learning using TD3, the learning is consist. However, if the agent applies the maximum values, it get stuck fails to explores lower values and suddenly does not improve or deteriorate further. I am not sure what could be the reason. The Q0 value explodes at this point. at this point. reinforcement learning, stuck learning, td3 MATLAB Answers — New Questions
errors with Simscape and SSC HDL Coder Workflow Advisor
hello, I’m having some really frustrating problems with Simscape and sschdladvisor.
there is going to be a lot of context up ahead, but I assure you it isn’t very dense at all.
—
initially, I tried following this document to generate HDL code, where they load the Full Wave Bridge Rectifier example. after following along and executing the workflow advisor tool, though, I’m met with the following warning at the very end (I renamed the simulink file to "fwbr"):
Warning
Run hdlsetup on the model ‘fwbr’ to modify configuration parameter values recommended for HDL code generation and rerun the workflow. Generated implementation model ‘gmStateSpaceHDL_fwbr’ with the ‘HDL settings’. The HDL Algorithm requires latency. Each output port experiences 1 additional delay.
but this is essentially an error, because it does not in fact generate the "gmStateSpaceHDL_fwbr" model. when I try opening it, I get the following error:
‘C:UsersCrisDocumentsMATLABssc_bcsschdlfwbrgmStateSpaceHDL_fwbr’ is not a valid Simulink object name and there is no file with that name.
there’s absolutely no configuration in the model nor in the Workflow Advisor I can use to make this warning go away.
I then run into the command sschdl.generateOptimizedModel, which was introduced in the R2024a version of MATLAB, which can replace all the Simscape components that might cause issues for HDL code generation into their dynamic block equivalent. after this and after making sure the generated optimized model is behaviourally identical, I can finally execute the Workflow Advisor with no problems.
—
after that, I try following along a different example, the Halfwave Rectifier model. this one executes flawlessly right off the bat and I get a dynamic system equivalent model out of the Workflow Advisor, for which I can then generate VHDL code with 0 issues.
—
I then try to make my own simscape system, a simple buck converter:
but I run into exactly the same issue as I did with the full wave bridge rectifier where it would throw that "warning" that wouldn’t let me actually generate the HDL coder adapted model. I then find this document with a buck converter model example, which executes flawlessly. this part in particular puzzles me, because in an attempt to find the problem with my own implementation I start moving parameters around both in the system and in the model settings themselves. eventually, I end up straight up copy-pasting the entire system into my own .slx file, and configure every single setting to be exactly the same as the example’s, and it still won’t let me generate the model by showing me that warning from before.
I tried applying the generateOptimizedModel command, but to my dismay it completely changed the behaviour of my circuit, and I could pinpoint that the one block causing the change in behaviour was the ideal switch’s replacement. this actually happens in every circuit where I use the generateOptimizedModel command and there are any switches. the command works, and it lets me generate the HDL Coder-adapted system with no warnings, but I cannot use it if my system now behaves differently.
—
phew, that should be all.
this is genuinely extremely confusing to me, from the fact that some default examples work right out of the box and some don’t, to the fact that two systems that are exactly the same in quite literally everything except the fact they’re different files don’t produce the same result when running them through sschdladvisor. for anyone who might have the slightest idea to what’s going on, I would be eternally grateful if you could tell me what the problem can be. the only thing I can think of is that something might have broken in some update since 2022.hello, I’m having some really frustrating problems with Simscape and sschdladvisor.
there is going to be a lot of context up ahead, but I assure you it isn’t very dense at all.
—
initially, I tried following this document to generate HDL code, where they load the Full Wave Bridge Rectifier example. after following along and executing the workflow advisor tool, though, I’m met with the following warning at the very end (I renamed the simulink file to "fwbr"):
Warning
Run hdlsetup on the model ‘fwbr’ to modify configuration parameter values recommended for HDL code generation and rerun the workflow. Generated implementation model ‘gmStateSpaceHDL_fwbr’ with the ‘HDL settings’. The HDL Algorithm requires latency. Each output port experiences 1 additional delay.
but this is essentially an error, because it does not in fact generate the "gmStateSpaceHDL_fwbr" model. when I try opening it, I get the following error:
‘C:UsersCrisDocumentsMATLABssc_bcsschdlfwbrgmStateSpaceHDL_fwbr’ is not a valid Simulink object name and there is no file with that name.
there’s absolutely no configuration in the model nor in the Workflow Advisor I can use to make this warning go away.
I then run into the command sschdl.generateOptimizedModel, which was introduced in the R2024a version of MATLAB, which can replace all the Simscape components that might cause issues for HDL code generation into their dynamic block equivalent. after this and after making sure the generated optimized model is behaviourally identical, I can finally execute the Workflow Advisor with no problems.
—
after that, I try following along a different example, the Halfwave Rectifier model. this one executes flawlessly right off the bat and I get a dynamic system equivalent model out of the Workflow Advisor, for which I can then generate VHDL code with 0 issues.
—
I then try to make my own simscape system, a simple buck converter:
but I run into exactly the same issue as I did with the full wave bridge rectifier where it would throw that "warning" that wouldn’t let me actually generate the HDL coder adapted model. I then find this document with a buck converter model example, which executes flawlessly. this part in particular puzzles me, because in an attempt to find the problem with my own implementation I start moving parameters around both in the system and in the model settings themselves. eventually, I end up straight up copy-pasting the entire system into my own .slx file, and configure every single setting to be exactly the same as the example’s, and it still won’t let me generate the model by showing me that warning from before.
I tried applying the generateOptimizedModel command, but to my dismay it completely changed the behaviour of my circuit, and I could pinpoint that the one block causing the change in behaviour was the ideal switch’s replacement. this actually happens in every circuit where I use the generateOptimizedModel command and there are any switches. the command works, and it lets me generate the HDL Coder-adapted system with no warnings, but I cannot use it if my system now behaves differently.
—
phew, that should be all.
this is genuinely extremely confusing to me, from the fact that some default examples work right out of the box and some don’t, to the fact that two systems that are exactly the same in quite literally everything except the fact they’re different files don’t produce the same result when running them through sschdladvisor. for anyone who might have the slightest idea to what’s going on, I would be eternally grateful if you could tell me what the problem can be. the only thing I can think of is that something might have broken in some update since 2022. hello, I’m having some really frustrating problems with Simscape and sschdladvisor.
there is going to be a lot of context up ahead, but I assure you it isn’t very dense at all.
—
initially, I tried following this document to generate HDL code, where they load the Full Wave Bridge Rectifier example. after following along and executing the workflow advisor tool, though, I’m met with the following warning at the very end (I renamed the simulink file to "fwbr"):
Warning
Run hdlsetup on the model ‘fwbr’ to modify configuration parameter values recommended for HDL code generation and rerun the workflow. Generated implementation model ‘gmStateSpaceHDL_fwbr’ with the ‘HDL settings’. The HDL Algorithm requires latency. Each output port experiences 1 additional delay.
but this is essentially an error, because it does not in fact generate the "gmStateSpaceHDL_fwbr" model. when I try opening it, I get the following error:
‘C:UsersCrisDocumentsMATLABssc_bcsschdlfwbrgmStateSpaceHDL_fwbr’ is not a valid Simulink object name and there is no file with that name.
there’s absolutely no configuration in the model nor in the Workflow Advisor I can use to make this warning go away.
I then run into the command sschdl.generateOptimizedModel, which was introduced in the R2024a version of MATLAB, which can replace all the Simscape components that might cause issues for HDL code generation into their dynamic block equivalent. after this and after making sure the generated optimized model is behaviourally identical, I can finally execute the Workflow Advisor with no problems.
—
after that, I try following along a different example, the Halfwave Rectifier model. this one executes flawlessly right off the bat and I get a dynamic system equivalent model out of the Workflow Advisor, for which I can then generate VHDL code with 0 issues.
—
I then try to make my own simscape system, a simple buck converter:
but I run into exactly the same issue as I did with the full wave bridge rectifier where it would throw that "warning" that wouldn’t let me actually generate the HDL coder adapted model. I then find this document with a buck converter model example, which executes flawlessly. this part in particular puzzles me, because in an attempt to find the problem with my own implementation I start moving parameters around both in the system and in the model settings themselves. eventually, I end up straight up copy-pasting the entire system into my own .slx file, and configure every single setting to be exactly the same as the example’s, and it still won’t let me generate the model by showing me that warning from before.
I tried applying the generateOptimizedModel command, but to my dismay it completely changed the behaviour of my circuit, and I could pinpoint that the one block causing the change in behaviour was the ideal switch’s replacement. this actually happens in every circuit where I use the generateOptimizedModel command and there are any switches. the command works, and it lets me generate the HDL Coder-adapted system with no warnings, but I cannot use it if my system now behaves differently.
—
phew, that should be all.
this is genuinely extremely confusing to me, from the fact that some default examples work right out of the box and some don’t, to the fact that two systems that are exactly the same in quite literally everything except the fact they’re different files don’t produce the same result when running them through sschdladvisor. for anyone who might have the slightest idea to what’s going on, I would be eternally grateful if you could tell me what the problem can be. the only thing I can think of is that something might have broken in some update since 2022. fpga, simscape, hdl coder, sschdl MATLAB Answers — New Questions
can’t find Init button by double click the Init subsystem inside the Rx block
when I try to follow the example "Globally Adapt Receiver Components Using Pulse Response Metrics to Improve SerDes Performance"when I try to follow the example "Globally Adapt Receiver Components Using Pulse Response Metrics to Improve SerDes Performance" when I try to follow the example "Globally Adapt Receiver Components Using Pulse Response Metrics to Improve SerDes Performance" serdesdesigner, equalization, serdes MATLAB Answers — New Questions
The follow code was create to calculate the time to increase the temperature, but when I run it the result is infinite. Anyone can help me?
Below are the tow functions used to calculate the time to increase the temp. according to the inputs: L1, L2, L3 and heat+power. The initial values were: 0.05m; 0.1 m; 0.05m and 500W respectively. But with any other values the result returns the same: inifinite seconds! I need the results in terms of plotting.
function time_to_increase_temperature = calculate_time_to_increase_temperature( …
rho_concrete, rho_air, k_concrete, k_air, ~, cp_concrete, …
cp_air, T_initial, T_surface, L1, L2, L3, volume_P1_P3, ~, …
Nx, Nt, delta_T, heat_power)
% Calculate total thickness
total_thickness = L1 + L2 + L3;
% Thermal diffusivities
alpha_concrete = k_concrete / (rho_concrete * cp_concrete); % m²/s
alpha_air = k_air / (rho_air * cp_air); % m²/s
% Discretization parameters
dx = total_thickness / Nx; % Spatial step size
dt = 6 / Nt; % Time step size
% Preallocate temperature arrays
T = T_initial * ones(Nx, 1);
T_new = T;
% Define material properties at each point
len_P1 = round(Nx * L1 / total_thickness); % Length of concrete layer P1
len_P2 = round(Nx * L2 / total_thickness); % Length of air layer P2
len_P3 = Nx – len_P1 – len_P2; % Length of concrete layer P3
% Ensure len_P3 is correctly adjusted if rounding caused any issues
if len_P1 + len_P2 + len_P3 ~= Nx
len_P3 = Nx – len_P1 – len_P2;
end
% Preallocate material array
material = zeros(Nx, 1);
material(1:len_P1) = alpha_concrete;
material(len_P1+1:len_P1+len_P2) = alpha_air;
material(len_P1+len_P2+1:Nx) = alpha_concrete;
time_to_increase_temperature = inf; % Initialize to store time to increase temperature
% Calculate heat input per spatial point
heat_input_per_point = heat_power * dt / (rho_concrete * cp_concrete * volume_P1_P3 / Nx);
% Time integration using Finite Difference Method (FDM)
time = 0; % Initialize time
for n = 1:Nt
for i = 2:Nx-1
T_new(i) = T(i) + material(i) * dt / dx^2 * (T(i+1) – 2*T(i) + T(i-1));
end
% Boundary conditions
T_new(1) = T(1) + alpha_concrete * dt / dx^2 * (T(2) – T(1)) + heat_input_per_point * (T_surface – T(1));
T_new(Nx) = T(Nx-1);
% Update temperature
T = T_new;
time = time + dt;
% Check if the temperature at the right side of P3 reaches T_initial + delta_T
if T(Nx) >= T_initial + delta_T
time_to_increase_temperature = time;
break;
end
end
% Return the time to increase temperature by 1 K at the right side of P3
end
Function main_process:
function main_process()
% Parameters with fixed values
rho_concrete = 2500; % kg/m³
rho_air = 1293; % kg/m³
k_concrete = 1.35; % W/(m·K)
k_air = 0.024; % W/(m·K) assuming typical value for air
cp_concrete = 0.92 * 1000; % J/(kg·K)
cp_air = 1.005 * 1000; % J/(kg·K)
T_initial = 300; % Initial temperature in K
T_surface = 411; % Surface temperature in K
volume_P1_P3 = 0.00488; % Volume of each concrete plate in m³
Nx = 100; % Number of spatial points
Nt = 1000; % Number of time steps
delta_T = 1; % Temperature increase in K
% Prompt the user for specific input parameters
L1 = input(‘Enter the thickness of the first concrete layer (m): ‘);
L2 = input(‘Enter the thickness of the air layer (m): ‘);
L3 = input(‘Enter the thickness of the second concrete layer (m): ‘);
heat_power = input(‘Enter the heat power (W): ‘);
% Call the function
time_to_increase_temperature = calculate_time_to_increase_temperature( …
rho_concrete, rho_air, k_concrete, k_air, [], cp_concrete, …
cp_air, T_initial, T_surface, L1, L2, L3, volume_P1_P3, [], …
Nx, Nt, delta_T, heat_power);
% Display the result
fprintf(‘Time to increase temperature by 1 K at the right side of P3: %.2f secondsn’, time_to_increase_temperature);
% Plot the result
total_thickness = L1 + L2 + L3;
x = linspace(0, total_thickness, Nx); % Spatial points
y = linspace(0, time_to_increase_temperature, Nx); % Temporal points for plotting
plot(x, y, ‘DisplayName’, ‘Time to Increase Temperature by 1 K’);
xlabel(‘Position (m)’);
ylabel(‘Time (s)’);
legend(‘show’);
title(‘Time to Increase Temperature by 1 K at the right side of P3’);
endBelow are the tow functions used to calculate the time to increase the temp. according to the inputs: L1, L2, L3 and heat+power. The initial values were: 0.05m; 0.1 m; 0.05m and 500W respectively. But with any other values the result returns the same: inifinite seconds! I need the results in terms of plotting.
function time_to_increase_temperature = calculate_time_to_increase_temperature( …
rho_concrete, rho_air, k_concrete, k_air, ~, cp_concrete, …
cp_air, T_initial, T_surface, L1, L2, L3, volume_P1_P3, ~, …
Nx, Nt, delta_T, heat_power)
% Calculate total thickness
total_thickness = L1 + L2 + L3;
% Thermal diffusivities
alpha_concrete = k_concrete / (rho_concrete * cp_concrete); % m²/s
alpha_air = k_air / (rho_air * cp_air); % m²/s
% Discretization parameters
dx = total_thickness / Nx; % Spatial step size
dt = 6 / Nt; % Time step size
% Preallocate temperature arrays
T = T_initial * ones(Nx, 1);
T_new = T;
% Define material properties at each point
len_P1 = round(Nx * L1 / total_thickness); % Length of concrete layer P1
len_P2 = round(Nx * L2 / total_thickness); % Length of air layer P2
len_P3 = Nx – len_P1 – len_P2; % Length of concrete layer P3
% Ensure len_P3 is correctly adjusted if rounding caused any issues
if len_P1 + len_P2 + len_P3 ~= Nx
len_P3 = Nx – len_P1 – len_P2;
end
% Preallocate material array
material = zeros(Nx, 1);
material(1:len_P1) = alpha_concrete;
material(len_P1+1:len_P1+len_P2) = alpha_air;
material(len_P1+len_P2+1:Nx) = alpha_concrete;
time_to_increase_temperature = inf; % Initialize to store time to increase temperature
% Calculate heat input per spatial point
heat_input_per_point = heat_power * dt / (rho_concrete * cp_concrete * volume_P1_P3 / Nx);
% Time integration using Finite Difference Method (FDM)
time = 0; % Initialize time
for n = 1:Nt
for i = 2:Nx-1
T_new(i) = T(i) + material(i) * dt / dx^2 * (T(i+1) – 2*T(i) + T(i-1));
end
% Boundary conditions
T_new(1) = T(1) + alpha_concrete * dt / dx^2 * (T(2) – T(1)) + heat_input_per_point * (T_surface – T(1));
T_new(Nx) = T(Nx-1);
% Update temperature
T = T_new;
time = time + dt;
% Check if the temperature at the right side of P3 reaches T_initial + delta_T
if T(Nx) >= T_initial + delta_T
time_to_increase_temperature = time;
break;
end
end
% Return the time to increase temperature by 1 K at the right side of P3
end
Function main_process:
function main_process()
% Parameters with fixed values
rho_concrete = 2500; % kg/m³
rho_air = 1293; % kg/m³
k_concrete = 1.35; % W/(m·K)
k_air = 0.024; % W/(m·K) assuming typical value for air
cp_concrete = 0.92 * 1000; % J/(kg·K)
cp_air = 1.005 * 1000; % J/(kg·K)
T_initial = 300; % Initial temperature in K
T_surface = 411; % Surface temperature in K
volume_P1_P3 = 0.00488; % Volume of each concrete plate in m³
Nx = 100; % Number of spatial points
Nt = 1000; % Number of time steps
delta_T = 1; % Temperature increase in K
% Prompt the user for specific input parameters
L1 = input(‘Enter the thickness of the first concrete layer (m): ‘);
L2 = input(‘Enter the thickness of the air layer (m): ‘);
L3 = input(‘Enter the thickness of the second concrete layer (m): ‘);
heat_power = input(‘Enter the heat power (W): ‘);
% Call the function
time_to_increase_temperature = calculate_time_to_increase_temperature( …
rho_concrete, rho_air, k_concrete, k_air, [], cp_concrete, …
cp_air, T_initial, T_surface, L1, L2, L3, volume_P1_P3, [], …
Nx, Nt, delta_T, heat_power);
% Display the result
fprintf(‘Time to increase temperature by 1 K at the right side of P3: %.2f secondsn’, time_to_increase_temperature);
% Plot the result
total_thickness = L1 + L2 + L3;
x = linspace(0, total_thickness, Nx); % Spatial points
y = linspace(0, time_to_increase_temperature, Nx); % Temporal points for plotting
plot(x, y, ‘DisplayName’, ‘Time to Increase Temperature by 1 K’);
xlabel(‘Position (m)’);
ylabel(‘Time (s)’);
legend(‘show’);
title(‘Time to Increase Temperature by 1 K at the right side of P3’);
end Below are the tow functions used to calculate the time to increase the temp. according to the inputs: L1, L2, L3 and heat+power. The initial values were: 0.05m; 0.1 m; 0.05m and 500W respectively. But with any other values the result returns the same: inifinite seconds! I need the results in terms of plotting.
function time_to_increase_temperature = calculate_time_to_increase_temperature( …
rho_concrete, rho_air, k_concrete, k_air, ~, cp_concrete, …
cp_air, T_initial, T_surface, L1, L2, L3, volume_P1_P3, ~, …
Nx, Nt, delta_T, heat_power)
% Calculate total thickness
total_thickness = L1 + L2 + L3;
% Thermal diffusivities
alpha_concrete = k_concrete / (rho_concrete * cp_concrete); % m²/s
alpha_air = k_air / (rho_air * cp_air); % m²/s
% Discretization parameters
dx = total_thickness / Nx; % Spatial step size
dt = 6 / Nt; % Time step size
% Preallocate temperature arrays
T = T_initial * ones(Nx, 1);
T_new = T;
% Define material properties at each point
len_P1 = round(Nx * L1 / total_thickness); % Length of concrete layer P1
len_P2 = round(Nx * L2 / total_thickness); % Length of air layer P2
len_P3 = Nx – len_P1 – len_P2; % Length of concrete layer P3
% Ensure len_P3 is correctly adjusted if rounding caused any issues
if len_P1 + len_P2 + len_P3 ~= Nx
len_P3 = Nx – len_P1 – len_P2;
end
% Preallocate material array
material = zeros(Nx, 1);
material(1:len_P1) = alpha_concrete;
material(len_P1+1:len_P1+len_P2) = alpha_air;
material(len_P1+len_P2+1:Nx) = alpha_concrete;
time_to_increase_temperature = inf; % Initialize to store time to increase temperature
% Calculate heat input per spatial point
heat_input_per_point = heat_power * dt / (rho_concrete * cp_concrete * volume_P1_P3 / Nx);
% Time integration using Finite Difference Method (FDM)
time = 0; % Initialize time
for n = 1:Nt
for i = 2:Nx-1
T_new(i) = T(i) + material(i) * dt / dx^2 * (T(i+1) – 2*T(i) + T(i-1));
end
% Boundary conditions
T_new(1) = T(1) + alpha_concrete * dt / dx^2 * (T(2) – T(1)) + heat_input_per_point * (T_surface – T(1));
T_new(Nx) = T(Nx-1);
% Update temperature
T = T_new;
time = time + dt;
% Check if the temperature at the right side of P3 reaches T_initial + delta_T
if T(Nx) >= T_initial + delta_T
time_to_increase_temperature = time;
break;
end
end
% Return the time to increase temperature by 1 K at the right side of P3
end
Function main_process:
function main_process()
% Parameters with fixed values
rho_concrete = 2500; % kg/m³
rho_air = 1293; % kg/m³
k_concrete = 1.35; % W/(m·K)
k_air = 0.024; % W/(m·K) assuming typical value for air
cp_concrete = 0.92 * 1000; % J/(kg·K)
cp_air = 1.005 * 1000; % J/(kg·K)
T_initial = 300; % Initial temperature in K
T_surface = 411; % Surface temperature in K
volume_P1_P3 = 0.00488; % Volume of each concrete plate in m³
Nx = 100; % Number of spatial points
Nt = 1000; % Number of time steps
delta_T = 1; % Temperature increase in K
% Prompt the user for specific input parameters
L1 = input(‘Enter the thickness of the first concrete layer (m): ‘);
L2 = input(‘Enter the thickness of the air layer (m): ‘);
L3 = input(‘Enter the thickness of the second concrete layer (m): ‘);
heat_power = input(‘Enter the heat power (W): ‘);
% Call the function
time_to_increase_temperature = calculate_time_to_increase_temperature( …
rho_concrete, rho_air, k_concrete, k_air, [], cp_concrete, …
cp_air, T_initial, T_surface, L1, L2, L3, volume_P1_P3, [], …
Nx, Nt, delta_T, heat_power);
% Display the result
fprintf(‘Time to increase temperature by 1 K at the right side of P3: %.2f secondsn’, time_to_increase_temperature);
% Plot the result
total_thickness = L1 + L2 + L3;
x = linspace(0, total_thickness, Nx); % Spatial points
y = linspace(0, time_to_increase_temperature, Nx); % Temporal points for plotting
plot(x, y, ‘DisplayName’, ‘Time to Increase Temperature by 1 K’);
xlabel(‘Position (m)’);
ylabel(‘Time (s)’);
legend(‘show’);
title(‘Time to Increase Temperature by 1 K at the right side of P3’);
end solving issue, unknown error, break linkage MATLAB Answers — New Questions
¿Por que me aparece el error de Incorrect number or types of inputs or outputs for function applyBoundaryCondition en mi codigo?
% Definir las dimensiones del bloque en metros
L = 0.12; % largo en metros
H = 0.01; % altura en metros
% Crear el modelo PDE
model = createpde(‘thermal’, ‘transient’);
% Definir la geometría del rectángulo usando decsg
R1 = [3, 4, 0, L, L, 0, 0, 0, H, H]’;
gd = R1;
ns = char(‘R1’);
ns = ns’;
sf = ‘R1’;
[dl, bt] = decsg(gd, sf, ns);
% Crear la geometría del modelo
geometryFromEdges(model, dl);
% Especificar las propiedades físicas del material
conductividad = 0.3; % conductividad térmica en W/(m·K)
densidad = 1060; % densidad en kg/m³
calor_especifico = 2500; % calor específico en J/(kg·K)
thermalProperties(model, ‘ThermalConductivity’, conductividad, …
‘MassDensity’, densidad, …
‘SpecificHeat’, calor_especifico);
% Definir las condiciones iniciales
temperatura_inicial = 25; % temperatura inicial en °C
thermalIC(model, temperatura_inicial);
pdegplot(model,"EdgeLabels","on")
% Definir las condiciones de frontera (todas las caras a 140°C)
h = 10; % coeficiente de convección en W/(m^2·K)
Tamb = 25; % temperatura ambiente en °C
applyBoundaryCondition(model, ‘mixed’, ‘Edge’, edges, ‘ConvectiveCoefficient’, h, ‘AmbientTemperature’, Tamb);
% Generar la malla
generateMesh(model);
% Definir el rango de tiempo de simulación
tiempo_final = 60; % tiempo final en segundos
n_pasos = 50; % número de pasos de tiempo
tlist = linspace(0, tiempo_final, n_pasos);
% Resolver el problema de transferencia de calor
resultado = solve(model, tlist);
% Extraer la temperatura en cada nodo de la malla para el tiempo final
temperatura_final = resultado.Temperature(:, end);
% Graficar la distribución de temperatura en el tiempo final
figure;
pdeplot(model, ‘XYData’, temperatura_final, ‘Contour’, ‘on’);
title(‘Distribución de temperatura en el tiempo final’);
xlabel(‘x (m)’);
ylabel(‘y (m)’);
colorbar;% Definir las dimensiones del bloque en metros
L = 0.12; % largo en metros
H = 0.01; % altura en metros
% Crear el modelo PDE
model = createpde(‘thermal’, ‘transient’);
% Definir la geometría del rectángulo usando decsg
R1 = [3, 4, 0, L, L, 0, 0, 0, H, H]’;
gd = R1;
ns = char(‘R1’);
ns = ns’;
sf = ‘R1’;
[dl, bt] = decsg(gd, sf, ns);
% Crear la geometría del modelo
geometryFromEdges(model, dl);
% Especificar las propiedades físicas del material
conductividad = 0.3; % conductividad térmica en W/(m·K)
densidad = 1060; % densidad en kg/m³
calor_especifico = 2500; % calor específico en J/(kg·K)
thermalProperties(model, ‘ThermalConductivity’, conductividad, …
‘MassDensity’, densidad, …
‘SpecificHeat’, calor_especifico);
% Definir las condiciones iniciales
temperatura_inicial = 25; % temperatura inicial en °C
thermalIC(model, temperatura_inicial);
pdegplot(model,"EdgeLabels","on")
% Definir las condiciones de frontera (todas las caras a 140°C)
h = 10; % coeficiente de convección en W/(m^2·K)
Tamb = 25; % temperatura ambiente en °C
applyBoundaryCondition(model, ‘mixed’, ‘Edge’, edges, ‘ConvectiveCoefficient’, h, ‘AmbientTemperature’, Tamb);
% Generar la malla
generateMesh(model);
% Definir el rango de tiempo de simulación
tiempo_final = 60; % tiempo final en segundos
n_pasos = 50; % número de pasos de tiempo
tlist = linspace(0, tiempo_final, n_pasos);
% Resolver el problema de transferencia de calor
resultado = solve(model, tlist);
% Extraer la temperatura en cada nodo de la malla para el tiempo final
temperatura_final = resultado.Temperature(:, end);
% Graficar la distribución de temperatura en el tiempo final
figure;
pdeplot(model, ‘XYData’, temperatura_final, ‘Contour’, ‘on’);
title(‘Distribución de temperatura en el tiempo final’);
xlabel(‘x (m)’);
ylabel(‘y (m)’);
colorbar; % Definir las dimensiones del bloque en metros
L = 0.12; % largo en metros
H = 0.01; % altura en metros
% Crear el modelo PDE
model = createpde(‘thermal’, ‘transient’);
% Definir la geometría del rectángulo usando decsg
R1 = [3, 4, 0, L, L, 0, 0, 0, H, H]’;
gd = R1;
ns = char(‘R1’);
ns = ns’;
sf = ‘R1’;
[dl, bt] = decsg(gd, sf, ns);
% Crear la geometría del modelo
geometryFromEdges(model, dl);
% Especificar las propiedades físicas del material
conductividad = 0.3; % conductividad térmica en W/(m·K)
densidad = 1060; % densidad en kg/m³
calor_especifico = 2500; % calor específico en J/(kg·K)
thermalProperties(model, ‘ThermalConductivity’, conductividad, …
‘MassDensity’, densidad, …
‘SpecificHeat’, calor_especifico);
% Definir las condiciones iniciales
temperatura_inicial = 25; % temperatura inicial en °C
thermalIC(model, temperatura_inicial);
pdegplot(model,"EdgeLabels","on")
% Definir las condiciones de frontera (todas las caras a 140°C)
h = 10; % coeficiente de convección en W/(m^2·K)
Tamb = 25; % temperatura ambiente en °C
applyBoundaryCondition(model, ‘mixed’, ‘Edge’, edges, ‘ConvectiveCoefficient’, h, ‘AmbientTemperature’, Tamb);
% Generar la malla
generateMesh(model);
% Definir el rango de tiempo de simulación
tiempo_final = 60; % tiempo final en segundos
n_pasos = 50; % número de pasos de tiempo
tlist = linspace(0, tiempo_final, n_pasos);
% Resolver el problema de transferencia de calor
resultado = solve(model, tlist);
% Extraer la temperatura en cada nodo de la malla para el tiempo final
temperatura_final = resultado.Temperature(:, end);
% Graficar la distribución de temperatura en el tiempo final
figure;
pdeplot(model, ‘XYData’, temperatura_final, ‘Contour’, ‘on’);
title(‘Distribución de temperatura en el tiempo final’);
xlabel(‘x (m)’);
ylabel(‘y (m)’);
colorbar; applyboundarycondition. MATLAB Answers — New Questions
Error training Yolo V4 object detector
Hi,
I am running the scripts in Gazebo Simulation of Semi-Structured Intelligent Bin Picking for UR5e Using YOLO and PCA-Based Object Detection example and everthing works well. However, when I try to train the detector by using the trainYoloV4ForSimCuboidObject.mlx live script, I get this error:
Intermediate dot ‘.’ indexing produced a comma-separated list with 0 values, but it must produce a single value when followed by subsequent indexing operations.
Error in deep.internal.sdk.forwardDataAttributes>iForwardExampleInputsLayerGraph (line 250)
plY{i} = layerAnalyzer.Outputs.Meta{1};
Error in deep.internal.sdk.forwardDataAttributes (line 69)
[sizes, formats] = iForwardExampleInputsLayerGraph(net, opts.Outputs, X{:});
Error in yolov4ObjectDetector>iConfigureDetector (line 1884)
[orderedNetworkActivationSizes, ~] = deep.internal.sdk.forwardDataAttributes(lgraph,’Outputs’,orderedDetectionNetworkSource);
Error in yolov4ObjectDetector/parseDetectorInputs (line 1161)
[lgraph, params.DetectionNetworkSource] = iConfigureDetector(lgraph,numClasses,params.AnchorBoxes,params.DetectionNetworkSource,params.PredictedBoxType);
Error in yolov4ObjectDetector (line 286)
params = yolov4ObjectDetector.parseDetectorInputs(varargin{:});
I didn’t change anything and I provided the recommended donwnloaded dataset folders. So, what could be the cause of this error?Hi,
I am running the scripts in Gazebo Simulation of Semi-Structured Intelligent Bin Picking for UR5e Using YOLO and PCA-Based Object Detection example and everthing works well. However, when I try to train the detector by using the trainYoloV4ForSimCuboidObject.mlx live script, I get this error:
Intermediate dot ‘.’ indexing produced a comma-separated list with 0 values, but it must produce a single value when followed by subsequent indexing operations.
Error in deep.internal.sdk.forwardDataAttributes>iForwardExampleInputsLayerGraph (line 250)
plY{i} = layerAnalyzer.Outputs.Meta{1};
Error in deep.internal.sdk.forwardDataAttributes (line 69)
[sizes, formats] = iForwardExampleInputsLayerGraph(net, opts.Outputs, X{:});
Error in yolov4ObjectDetector>iConfigureDetector (line 1884)
[orderedNetworkActivationSizes, ~] = deep.internal.sdk.forwardDataAttributes(lgraph,’Outputs’,orderedDetectionNetworkSource);
Error in yolov4ObjectDetector/parseDetectorInputs (line 1161)
[lgraph, params.DetectionNetworkSource] = iConfigureDetector(lgraph,numClasses,params.AnchorBoxes,params.DetectionNetworkSource,params.PredictedBoxType);
Error in yolov4ObjectDetector (line 286)
params = yolov4ObjectDetector.parseDetectorInputs(varargin{:});
I didn’t change anything and I provided the recommended donwnloaded dataset folders. So, what could be the cause of this error? Hi,
I am running the scripts in Gazebo Simulation of Semi-Structured Intelligent Bin Picking for UR5e Using YOLO and PCA-Based Object Detection example and everthing works well. However, when I try to train the detector by using the trainYoloV4ForSimCuboidObject.mlx live script, I get this error:
Intermediate dot ‘.’ indexing produced a comma-separated list with 0 values, but it must produce a single value when followed by subsequent indexing operations.
Error in deep.internal.sdk.forwardDataAttributes>iForwardExampleInputsLayerGraph (line 250)
plY{i} = layerAnalyzer.Outputs.Meta{1};
Error in deep.internal.sdk.forwardDataAttributes (line 69)
[sizes, formats] = iForwardExampleInputsLayerGraph(net, opts.Outputs, X{:});
Error in yolov4ObjectDetector>iConfigureDetector (line 1884)
[orderedNetworkActivationSizes, ~] = deep.internal.sdk.forwardDataAttributes(lgraph,’Outputs’,orderedDetectionNetworkSource);
Error in yolov4ObjectDetector/parseDetectorInputs (line 1161)
[lgraph, params.DetectionNetworkSource] = iConfigureDetector(lgraph,numClasses,params.AnchorBoxes,params.DetectionNetworkSource,params.PredictedBoxType);
Error in yolov4ObjectDetector (line 286)
params = yolov4ObjectDetector.parseDetectorInputs(varargin{:});
I didn’t change anything and I provided the recommended donwnloaded dataset folders. So, what could be the cause of this error? training, computer vision, yolo v4 MATLAB Answers — New Questions
How do I calculate the duration between two times?
Hi,
I have two different data sets that each contain times in the format ‘HH:mm:ss’.
results_start_array (see attached) contains a list of general start times in the first column (each representing the general start time of a participant). Each time indicates when a participant started their task.
results_start_end (see attached) is a cell array of cells, with 12 tables in each cell. Each table has two times. Each of these tables represents a sub-task. In each table, the first row is a start time and the second row is a end time of each respective sub-task.
My goal is to calcualate all the different durations between (for each participant):
start time of sub-task 1 – general start time
end time of sub-task 1 – general start time
start time of sub-task 2 – general start time
end time of sub-task 2 – general start time
start time of sub-task 3 – general start time
end time of sub-task 3 – general start time
etc. …
I tried this out by calculating only the start time of sub-task 1 – general start time using this code:
% Extract the start time from results_start_array
start_time = results_start_array(1);
% Extract the end time from the first row in the first table in the first cell of results_start_end
end_time_str = results_start_end{1}{1, ‘Time’};
% Convert the end time string to datetime object
end_time = datetime(end_time_str{1}, ‘InputFormat’, ‘HH:mm:ss’);
% Convert the start time to datetime object assuming it is in the same day
start_time_dt = datetime(start_time, ‘ConvertFrom’, ‘duration’, ‘Format’, ‘HH:mm:ss’);
% Calculate the duration between the two times
time_duration = end_time – start_time_dt;
% Display the duration
disp(time_duration);
Which didnt seem to work. What am I doing wrong and how can I fix this?
ThxHi,
I have two different data sets that each contain times in the format ‘HH:mm:ss’.
results_start_array (see attached) contains a list of general start times in the first column (each representing the general start time of a participant). Each time indicates when a participant started their task.
results_start_end (see attached) is a cell array of cells, with 12 tables in each cell. Each table has two times. Each of these tables represents a sub-task. In each table, the first row is a start time and the second row is a end time of each respective sub-task.
My goal is to calcualate all the different durations between (for each participant):
start time of sub-task 1 – general start time
end time of sub-task 1 – general start time
start time of sub-task 2 – general start time
end time of sub-task 2 – general start time
start time of sub-task 3 – general start time
end time of sub-task 3 – general start time
etc. …
I tried this out by calculating only the start time of sub-task 1 – general start time using this code:
% Extract the start time from results_start_array
start_time = results_start_array(1);
% Extract the end time from the first row in the first table in the first cell of results_start_end
end_time_str = results_start_end{1}{1, ‘Time’};
% Convert the end time string to datetime object
end_time = datetime(end_time_str{1}, ‘InputFormat’, ‘HH:mm:ss’);
% Convert the start time to datetime object assuming it is in the same day
start_time_dt = datetime(start_time, ‘ConvertFrom’, ‘duration’, ‘Format’, ‘HH:mm:ss’);
% Calculate the duration between the two times
time_duration = end_time – start_time_dt;
% Display the duration
disp(time_duration);
Which didnt seem to work. What am I doing wrong and how can I fix this?
Thx Hi,
I have two different data sets that each contain times in the format ‘HH:mm:ss’.
results_start_array (see attached) contains a list of general start times in the first column (each representing the general start time of a participant). Each time indicates when a participant started their task.
results_start_end (see attached) is a cell array of cells, with 12 tables in each cell. Each table has two times. Each of these tables represents a sub-task. In each table, the first row is a start time and the second row is a end time of each respective sub-task.
My goal is to calcualate all the different durations between (for each participant):
start time of sub-task 1 – general start time
end time of sub-task 1 – general start time
start time of sub-task 2 – general start time
end time of sub-task 2 – general start time
start time of sub-task 3 – general start time
end time of sub-task 3 – general start time
etc. …
I tried this out by calculating only the start time of sub-task 1 – general start time using this code:
% Extract the start time from results_start_array
start_time = results_start_array(1);
% Extract the end time from the first row in the first table in the first cell of results_start_end
end_time_str = results_start_end{1}{1, ‘Time’};
% Convert the end time string to datetime object
end_time = datetime(end_time_str{1}, ‘InputFormat’, ‘HH:mm:ss’);
% Convert the start time to datetime object assuming it is in the same day
start_time_dt = datetime(start_time, ‘ConvertFrom’, ‘duration’, ‘Format’, ‘HH:mm:ss’);
% Calculate the duration between the two times
time_duration = end_time – start_time_dt;
% Display the duration
disp(time_duration);
Which didnt seem to work. What am I doing wrong and how can I fix this?
Thx time, duration, subtract, duration array, error, calculate duration MATLAB Answers — New Questions
The combine(S) and horner(p) functions did not work as expected?
Code:
syms C_F C_L C_GS g_m R_L omega positive
s = i*omega;
Y_in=(1-(s*C_F-g_m)/(1/R_L+s*C_F+s*C_L))*s*C_F+s*C_GS
Re = real(Y_in)
[N,D] = numden(simplify(Re))
D-1
combine(D-1)
horner(D-1)
D
combine(D)
horner(D)
Behavior:Code:
syms C_F C_L C_GS g_m R_L omega positive
s = i*omega;
Y_in=(1-(s*C_F-g_m)/(1/R_L+s*C_F+s*C_L))*s*C_F+s*C_GS
Re = real(Y_in)
[N,D] = numden(simplify(Re))
D-1
combine(D-1)
horner(D-1)
D
combine(D)
horner(D)
Behavior: Code:
syms C_F C_L C_GS g_m R_L omega positive
s = i*omega;
Y_in=(1-(s*C_F-g_m)/(1/R_L+s*C_F+s*C_L))*s*C_F+s*C_GS
Re = real(Y_in)
[N,D] = numden(simplify(Re))
D-1
combine(D-1)
horner(D-1)
D
combine(D)
horner(D)
Behavior: symbolic MATLAB Answers — New Questions
How to compute diffraction integral using fast Fourier transform (fft2) ?
Hi there !
The following code computes Fresnel diffraction integral using fft2. It works for (obj.E = ones(Ny, Nx);) and performs the fft2 analysis, but when the input is (obj.E = zeroes(Ny, Nx);), it plots nothing. I checked the same code on python with zeros and it worked but in MATLAB it is not performing fft2 for zeros (gives only zero values). Kindly help me resolve this issue.
The Sheet.m (code):
classdef Sheet
properties
dx
dy
x
y
xx
yy
Nx
Ny
E
end
methods
function obj = Sheet(extent_x, extent_y, Nx, Ny)
obj.dx = extent_x / Nx;
obj.dy = extent_y / Ny;
obj.x = obj.dx * ((0:Nx-1) – floor(Nx/2));
obj.y = obj.dy * ((0:Ny-1) – floor(Ny/2));
[obj.xx, obj.yy] = meshgrid(obj.x, obj.y);
obj.Nx = Nx;
obj.Ny = Ny;
obj.E = zeros(Ny, Nx);
end
function rectangular_slit(obj, x0, y0, lx, ly)
% Creates a slit centered at the point (x0, y0) with width lx and height ly
mask = ((obj.xx > (x0 – lx/2)) & (obj.xx < (x0 + lx/2))) & ((obj.yy > (y0 – ly/2)) & (obj.yy < (y0 + ly/2)));
obj.E = obj.E + mask;
end
end
end
The main code :
% Simulation input
Lx = 1.4;
Ly = 0.4;
Nx = 2500;
Ny = 1500;
sheet = Sheet(2*Lx, 2*Ly, Nx, Ny);
% Slit separation
mm = 1e-3;
D = 128 * mm;
sheet.rectangular_slit(-D/2, 0, 22 * mm, 88 * mm);
sheet.rectangular_slit(D/2, 0, 22 * mm, 88 * mm);
% Distance from slit to the screen (mm)
z = 5000;
% Wavelength (mm)
lambda = 18.5*1e-7;
k = 2*pi / lambda;
% Initialize complex array for phase information
fft_c = fft2(sheet.E .* exp(1i * k/(2*z) * (sheet.xx.^2 + sheet.yy.^2)));
c = fftshift(fft_c);
% Plot with MATLAB
abs_c = abs(c);
% Screen size (mm)
dx_screen = z*lambda/(2*Lx);
dy_screen = z*lambda/(2*Ly);
x_screen = dx_screen * ((1:Nx) – Nx/2);
y_screen = dy_screen * ((1:Ny) – Ny/2);
figure;
subplot(2, 1, 1);
imagesc(x_screen([1 end]), y_screen([1 end]), abs_c);
colormap(gray);
axis equal;
xlabel(‘x (mm)’);
ylabel(‘y (mm)’);
title(‘Probability Density |psi|^2’);
xlim([-2, 2]);
ylim([-1, 1]);
subplot(2, 1, 2);
plot(x_screen, abs(c(Ny/2, :)).^2, ‘LineWidth’, 1);
xlabel(‘x (mm)’);
ylabel(‘Probability Density |psi|^2’);
title(‘Probability Density |psi|^2 along y=0’);
xlim([-2, 2]);Hi there !
The following code computes Fresnel diffraction integral using fft2. It works for (obj.E = ones(Ny, Nx);) and performs the fft2 analysis, but when the input is (obj.E = zeroes(Ny, Nx);), it plots nothing. I checked the same code on python with zeros and it worked but in MATLAB it is not performing fft2 for zeros (gives only zero values). Kindly help me resolve this issue.
The Sheet.m (code):
classdef Sheet
properties
dx
dy
x
y
xx
yy
Nx
Ny
E
end
methods
function obj = Sheet(extent_x, extent_y, Nx, Ny)
obj.dx = extent_x / Nx;
obj.dy = extent_y / Ny;
obj.x = obj.dx * ((0:Nx-1) – floor(Nx/2));
obj.y = obj.dy * ((0:Ny-1) – floor(Ny/2));
[obj.xx, obj.yy] = meshgrid(obj.x, obj.y);
obj.Nx = Nx;
obj.Ny = Ny;
obj.E = zeros(Ny, Nx);
end
function rectangular_slit(obj, x0, y0, lx, ly)
% Creates a slit centered at the point (x0, y0) with width lx and height ly
mask = ((obj.xx > (x0 – lx/2)) & (obj.xx < (x0 + lx/2))) & ((obj.yy > (y0 – ly/2)) & (obj.yy < (y0 + ly/2)));
obj.E = obj.E + mask;
end
end
end
The main code :
% Simulation input
Lx = 1.4;
Ly = 0.4;
Nx = 2500;
Ny = 1500;
sheet = Sheet(2*Lx, 2*Ly, Nx, Ny);
% Slit separation
mm = 1e-3;
D = 128 * mm;
sheet.rectangular_slit(-D/2, 0, 22 * mm, 88 * mm);
sheet.rectangular_slit(D/2, 0, 22 * mm, 88 * mm);
% Distance from slit to the screen (mm)
z = 5000;
% Wavelength (mm)
lambda = 18.5*1e-7;
k = 2*pi / lambda;
% Initialize complex array for phase information
fft_c = fft2(sheet.E .* exp(1i * k/(2*z) * (sheet.xx.^2 + sheet.yy.^2)));
c = fftshift(fft_c);
% Plot with MATLAB
abs_c = abs(c);
% Screen size (mm)
dx_screen = z*lambda/(2*Lx);
dy_screen = z*lambda/(2*Ly);
x_screen = dx_screen * ((1:Nx) – Nx/2);
y_screen = dy_screen * ((1:Ny) – Ny/2);
figure;
subplot(2, 1, 1);
imagesc(x_screen([1 end]), y_screen([1 end]), abs_c);
colormap(gray);
axis equal;
xlabel(‘x (mm)’);
ylabel(‘y (mm)’);
title(‘Probability Density |psi|^2’);
xlim([-2, 2]);
ylim([-1, 1]);
subplot(2, 1, 2);
plot(x_screen, abs(c(Ny/2, :)).^2, ‘LineWidth’, 1);
xlabel(‘x (mm)’);
ylabel(‘Probability Density |psi|^2’);
title(‘Probability Density |psi|^2 along y=0’);
xlim([-2, 2]); Hi there !
The following code computes Fresnel diffraction integral using fft2. It works for (obj.E = ones(Ny, Nx);) and performs the fft2 analysis, but when the input is (obj.E = zeroes(Ny, Nx);), it plots nothing. I checked the same code on python with zeros and it worked but in MATLAB it is not performing fft2 for zeros (gives only zero values). Kindly help me resolve this issue.
The Sheet.m (code):
classdef Sheet
properties
dx
dy
x
y
xx
yy
Nx
Ny
E
end
methods
function obj = Sheet(extent_x, extent_y, Nx, Ny)
obj.dx = extent_x / Nx;
obj.dy = extent_y / Ny;
obj.x = obj.dx * ((0:Nx-1) – floor(Nx/2));
obj.y = obj.dy * ((0:Ny-1) – floor(Ny/2));
[obj.xx, obj.yy] = meshgrid(obj.x, obj.y);
obj.Nx = Nx;
obj.Ny = Ny;
obj.E = zeros(Ny, Nx);
end
function rectangular_slit(obj, x0, y0, lx, ly)
% Creates a slit centered at the point (x0, y0) with width lx and height ly
mask = ((obj.xx > (x0 – lx/2)) & (obj.xx < (x0 + lx/2))) & ((obj.yy > (y0 – ly/2)) & (obj.yy < (y0 + ly/2)));
obj.E = obj.E + mask;
end
end
end
The main code :
% Simulation input
Lx = 1.4;
Ly = 0.4;
Nx = 2500;
Ny = 1500;
sheet = Sheet(2*Lx, 2*Ly, Nx, Ny);
% Slit separation
mm = 1e-3;
D = 128 * mm;
sheet.rectangular_slit(-D/2, 0, 22 * mm, 88 * mm);
sheet.rectangular_slit(D/2, 0, 22 * mm, 88 * mm);
% Distance from slit to the screen (mm)
z = 5000;
% Wavelength (mm)
lambda = 18.5*1e-7;
k = 2*pi / lambda;
% Initialize complex array for phase information
fft_c = fft2(sheet.E .* exp(1i * k/(2*z) * (sheet.xx.^2 + sheet.yy.^2)));
c = fftshift(fft_c);
% Plot with MATLAB
abs_c = abs(c);
% Screen size (mm)
dx_screen = z*lambda/(2*Lx);
dy_screen = z*lambda/(2*Ly);
x_screen = dx_screen * ((1:Nx) – Nx/2);
y_screen = dy_screen * ((1:Ny) – Ny/2);
figure;
subplot(2, 1, 1);
imagesc(x_screen([1 end]), y_screen([1 end]), abs_c);
colormap(gray);
axis equal;
xlabel(‘x (mm)’);
ylabel(‘y (mm)’);
title(‘Probability Density |psi|^2’);
xlim([-2, 2]);
ylim([-1, 1]);
subplot(2, 1, 2);
plot(x_screen, abs(c(Ny/2, :)).^2, ‘LineWidth’, 1);
xlabel(‘x (mm)’);
ylabel(‘Probability Density |psi|^2’);
title(‘Probability Density |psi|^2 along y=0’);
xlim([-2, 2]); diffraction, fft2, fresnel, numerical integration, plot MATLAB Answers — New Questions
Weight Tying for Layers in a CNN model
I am building a Deep Learning network looks like the figure below. I want to tie the weights of : Conv1 to Conv2; Conv3 to Conv6 and Conv4 to Conv5. Is it possible to do so in MATLAB? If yes, please help me with the code.I am building a Deep Learning network looks like the figure below. I want to tie the weights of : Conv1 to Conv2; Conv3 to Conv6 and Conv4 to Conv5. Is it possible to do so in MATLAB? If yes, please help me with the code. I am building a Deep Learning network looks like the figure below. I want to tie the weights of : Conv1 to Conv2; Conv3 to Conv6 and Conv4 to Conv5. Is it possible to do so in MATLAB? If yes, please help me with the code. weight tying, weight sharing, deep learning MATLAB Answers — New Questions
Can I combine imported geometry with basic shapes?
I have a geometry stored in an .stl file. I want to use it with importGeometry and add basic shapes to it in matlab later. How can I make it?I have a geometry stored in an .stl file. I want to use it with importGeometry and add basic shapes to it in matlab later. How can I make it? I have a geometry stored in an .stl file. I want to use it with importGeometry and add basic shapes to it in matlab later. How can I make it? pdetool MATLAB Answers — New Questions
Basic use of Interface.000208DA_0000_0000_C000_000000000046
I am at the very first use of Interface.000208DA_0000_0000_C000_000000000046, since I need to change an excel, in its fomat and contents, automatically. I have some basic questions, since I have not found clear documentation on them.
1) I know some basic commands, i.e. how to open the excel sheet via "actxserver" and "Workbooks", how to generate "Sheets" objects. I would like to know how can I copy in an excel file, once I have opned it, cells from a sheet to another sheet. These cells shall contain formulas to elaborate the contents of other column that I have generated via a routine of mine.
2) How can I insert in a cell some mixed text, like " Fuel Consumption" (where there is one character using "Symbol" font and the rest is "Calibri")?I am at the very first use of Interface.000208DA_0000_0000_C000_000000000046, since I need to change an excel, in its fomat and contents, automatically. I have some basic questions, since I have not found clear documentation on them.
1) I know some basic commands, i.e. how to open the excel sheet via "actxserver" and "Workbooks", how to generate "Sheets" objects. I would like to know how can I copy in an excel file, once I have opned it, cells from a sheet to another sheet. These cells shall contain formulas to elaborate the contents of other column that I have generated via a routine of mine.
2) How can I insert in a cell some mixed text, like " Fuel Consumption" (where there is one character using "Symbol" font and the rest is "Calibri")? I am at the very first use of Interface.000208DA_0000_0000_C000_000000000046, since I need to change an excel, in its fomat and contents, automatically. I have some basic questions, since I have not found clear documentation on them.
1) I know some basic commands, i.e. how to open the excel sheet via "actxserver" and "Workbooks", how to generate "Sheets" objects. I would like to know how can I copy in an excel file, once I have opned it, cells from a sheet to another sheet. These cells shall contain formulas to elaborate the contents of other column that I have generated via a routine of mine.
2) How can I insert in a cell some mixed text, like " Fuel Consumption" (where there is one character using "Symbol" font and the rest is "Calibri")? interface.000208da_0000_0000_c000_000000000046, copy, excel, text font in excel MATLAB Answers — New Questions
Segmention Violation Detected on Trainnet
Hello. I’m training a Convolutional Neural Network using trainnet(dsTrain,net,’mse’,options) on a gpu where dsTrain is a CombiendDatastore, and I keep getting the following error. I have tried to simplify the nn and reduce to minibatch size to 32, but I keep getting the error. I was previously using an older version of MATLAB, this is my first code with MATLAB R2024a. I have already deleted and reinstalled MathWorks Service Host.
————————————————————————
Segmentation violation detected at Sat Jun 15 22:39:27 2024
————————————————————————
Architecture : glnxa64
Processor ID : Intel(R) Xeon(R) Gold 5220 CPU @ 2.20GHz
Host Name : –
Locale : es_ES
Abnormal termination:
Segmentation violation
Current Thread: ‘FTP_2_1’ id 140126648170240
Register State (from fault):
RAX = 65532f736b726f57 RBX = 00007f71c71664f0
RCX = 0000000000000000 RDX = 0000000000000009
RSP = 00007f71c71664b0 RBP = 00007f71c7166710
RSI = 0000000000000002 RDI = 0000000000000002
R8 = 00007f71c71664f8 R9 = 0000000000000052
R10 = 00007f71ac000082 R11 = 00007f71c7166468
R12 = 00007f71c7166538 R13 = 00007f71e825bea0
R14 = 00007f71e825a8c0 R15 = 00007f71c7166550
RIP = 00007f7210c62b16 EFL = 0000000000010246
CS = 0033 FS = 0000 GS = 0000
Stack Trace (from fault):
[ 0] 0x00007f7210c62b16 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/serviceproviders/login/spf/matlabloginserviceprovider/libmwmatlabloginserviceprovider.so+00371478
[ 1] 0x00007f721053746b /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/mathworksservicehost/rcf/matlabconnector/serviceprocess/rcf/client-v1/../../../../../../../../bin/glnxa64/libmwagentspfcore.so+00152683 _ZNK5agent3spf4core16ExportedFunctionclEON10foundation10concurrent10threadpool10stop_tokenEONS1_14GenericPayloadE+00000347
[ 2] 0x00007f720340a5f6 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentspflegacyservicewrapper.so+00128502
[ 3] 0x00007f720340a681 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentspflegacyservicewrapper.so+00128641
[ 4] 0x00007f7203371060 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentnanomsgtransport.so+00082016
[ 5] 0x00007f7215a32c34 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00146484
[ 6] 0x00007f7215a37928 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00166184
[ 7] 0x00007f7215a37d54 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00167252
[ 8] 0x00007f72163fc8c3 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6+00903363
[ 9] 0x00007f721654d609 /lib/x86_64-linux-gnu/libpthread.so.0+00034313
[ 10] 0x00007f721622a353 /lib/x86_64-linux-gnu/libc.so.6+01176403 clone+00000067Hello. I’m training a Convolutional Neural Network using trainnet(dsTrain,net,’mse’,options) on a gpu where dsTrain is a CombiendDatastore, and I keep getting the following error. I have tried to simplify the nn and reduce to minibatch size to 32, but I keep getting the error. I was previously using an older version of MATLAB, this is my first code with MATLAB R2024a. I have already deleted and reinstalled MathWorks Service Host.
————————————————————————
Segmentation violation detected at Sat Jun 15 22:39:27 2024
————————————————————————
Architecture : glnxa64
Processor ID : Intel(R) Xeon(R) Gold 5220 CPU @ 2.20GHz
Host Name : –
Locale : es_ES
Abnormal termination:
Segmentation violation
Current Thread: ‘FTP_2_1’ id 140126648170240
Register State (from fault):
RAX = 65532f736b726f57 RBX = 00007f71c71664f0
RCX = 0000000000000000 RDX = 0000000000000009
RSP = 00007f71c71664b0 RBP = 00007f71c7166710
RSI = 0000000000000002 RDI = 0000000000000002
R8 = 00007f71c71664f8 R9 = 0000000000000052
R10 = 00007f71ac000082 R11 = 00007f71c7166468
R12 = 00007f71c7166538 R13 = 00007f71e825bea0
R14 = 00007f71e825a8c0 R15 = 00007f71c7166550
RIP = 00007f7210c62b16 EFL = 0000000000010246
CS = 0033 FS = 0000 GS = 0000
Stack Trace (from fault):
[ 0] 0x00007f7210c62b16 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/serviceproviders/login/spf/matlabloginserviceprovider/libmwmatlabloginserviceprovider.so+00371478
[ 1] 0x00007f721053746b /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/mathworksservicehost/rcf/matlabconnector/serviceprocess/rcf/client-v1/../../../../../../../../bin/glnxa64/libmwagentspfcore.so+00152683 _ZNK5agent3spf4core16ExportedFunctionclEON10foundation10concurrent10threadpool10stop_tokenEONS1_14GenericPayloadE+00000347
[ 2] 0x00007f720340a5f6 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentspflegacyservicewrapper.so+00128502
[ 3] 0x00007f720340a681 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentspflegacyservicewrapper.so+00128641
[ 4] 0x00007f7203371060 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentnanomsgtransport.so+00082016
[ 5] 0x00007f7215a32c34 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00146484
[ 6] 0x00007f7215a37928 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00166184
[ 7] 0x00007f7215a37d54 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00167252
[ 8] 0x00007f72163fc8c3 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6+00903363
[ 9] 0x00007f721654d609 /lib/x86_64-linux-gnu/libpthread.so.0+00034313
[ 10] 0x00007f721622a353 /lib/x86_64-linux-gnu/libc.so.6+01176403 clone+00000067 Hello. I’m training a Convolutional Neural Network using trainnet(dsTrain,net,’mse’,options) on a gpu where dsTrain is a CombiendDatastore, and I keep getting the following error. I have tried to simplify the nn and reduce to minibatch size to 32, but I keep getting the error. I was previously using an older version of MATLAB, this is my first code with MATLAB R2024a. I have already deleted and reinstalled MathWorks Service Host.
————————————————————————
Segmentation violation detected at Sat Jun 15 22:39:27 2024
————————————————————————
Architecture : glnxa64
Processor ID : Intel(R) Xeon(R) Gold 5220 CPU @ 2.20GHz
Host Name : –
Locale : es_ES
Abnormal termination:
Segmentation violation
Current Thread: ‘FTP_2_1’ id 140126648170240
Register State (from fault):
RAX = 65532f736b726f57 RBX = 00007f71c71664f0
RCX = 0000000000000000 RDX = 0000000000000009
RSP = 00007f71c71664b0 RBP = 00007f71c7166710
RSI = 0000000000000002 RDI = 0000000000000002
R8 = 00007f71c71664f8 R9 = 0000000000000052
R10 = 00007f71ac000082 R11 = 00007f71c7166468
R12 = 00007f71c7166538 R13 = 00007f71e825bea0
R14 = 00007f71e825a8c0 R15 = 00007f71c7166550
RIP = 00007f7210c62b16 EFL = 0000000000010246
CS = 0033 FS = 0000 GS = 0000
Stack Trace (from fault):
[ 0] 0x00007f7210c62b16 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/serviceproviders/login/spf/matlabloginserviceprovider/libmwmatlabloginserviceprovider.so+00371478
[ 1] 0x00007f721053746b /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/mathworksservicehost/rcf/matlabconnector/serviceprocess/rcf/client-v1/../../../../../../../../bin/glnxa64/libmwagentspfcore.so+00152683 _ZNK5agent3spf4core16ExportedFunctionclEON10foundation10concurrent10threadpool10stop_tokenEONS1_14GenericPayloadE+00000347
[ 2] 0x00007f720340a5f6 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentspflegacyservicewrapper.so+00128502
[ 3] 0x00007f720340a681 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentspflegacyservicewrapper.so+00128641
[ 4] 0x00007f7203371060 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/spf/servicepublishers/agent/spf/legacyservicepublisher/../../../../../../../bin/glnxa64/libmwagentnanomsgtransport.so+00082016
[ 5] 0x00007f7215a32c34 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00146484
[ 6] 0x00007f7215a37928 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00166184
[ 7] 0x00007f7215a37d54 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/libmwfoundation_threadpool.so+00167252
[ 8] 0x00007f72163fc8c3 /home/fran/.MathWorks/ServiceHost/-mw_shared_installs/v2024.6.0.6/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6+00903363
[ 9] 0x00007f721654d609 /lib/x86_64-linux-gnu/libpthread.so.0+00034313
[ 10] 0x00007f721622a353 /lib/x86_64-linux-gnu/libc.so.6+01176403 clone+00000067 neural network, memory MATLAB Answers — New Questions
Why doesn’t the MATLAB onramp play?
I’ve tried playing MATLAB onramp course but it doesn’t play the video at all, i’ve tried changing browsers and it didn’t work. It’d be amazing if you could help.I’ve tried playing MATLAB onramp course but it doesn’t play the video at all, i’ve tried changing browsers and it didn’t work. It’d be amazing if you could help. I’ve tried playing MATLAB onramp course but it doesn’t play the video at all, i’ve tried changing browsers and it didn’t work. It’d be amazing if you could help. matlab MATLAB Answers — New Questions
Is there a switch for simsacpe mechanical components? How to connect or disconnect certain simscape components on the fly
Hi,
I would like to simulate a scenerio that the mechanical system speed is initially fixed to certain speed. After certain designated time period, I would like to disconnect the ideal velocity source and switch to ideal torque source.
I cannot find any block to do so. There is no "MOSFET", "IGBT" type device in mechanical simscape libary.Hi,
I would like to simulate a scenerio that the mechanical system speed is initially fixed to certain speed. After certain designated time period, I would like to disconnect the ideal velocity source and switch to ideal torque source.
I cannot find any block to do so. There is no "MOSFET", "IGBT" type device in mechanical simscape libary. Hi,
I would like to simulate a scenerio that the mechanical system speed is initially fixed to certain speed. After certain designated time period, I would like to disconnect the ideal velocity source and switch to ideal torque source.
I cannot find any block to do so. There is no "MOSFET", "IGBT" type device in mechanical simscape libary. simscape, mechanical, ideal velocity source, ideal torque source, switch MATLAB Answers — New Questions
Array dimensions must match for binary array op. How to fix this thanks
These are the codes:
input_image = imread (‘C.tif’);
[M, N] = size(input_image);
FT_img = fft2(double(input_image));
n = 2;
D0 = 20;
u = 0:(M-1);
v = 0:(N-1);
idx = find(u > M/2);
u(idx) = u(idx) – M;
idy = find(v > N/2);
v(idy) = v(idy) – N;
[V, U] = meshgrid(v, u);
D = sqrt(U.^2 + V.^2);
H = 1./(1 + (D./D0).^(2*n));
G = H.*FT_img;
output_image = real(ifft2(double(G)));
subplot(2, 1, 1), imshow(input_image),
subplot(2, 1, 2), imshow(output_image, [ ]);
the command window shows that:
Array dimensions must match for binary array op.
Error in Run_1 (line 24)
G = H.*FT_img;
I looked up on other people’s questions which are similar but i still don’t get it so if anyone can fix this for me, that would be greatly appreciated.
Sorry im new and thanksThese are the codes:
input_image = imread (‘C.tif’);
[M, N] = size(input_image);
FT_img = fft2(double(input_image));
n = 2;
D0 = 20;
u = 0:(M-1);
v = 0:(N-1);
idx = find(u > M/2);
u(idx) = u(idx) – M;
idy = find(v > N/2);
v(idy) = v(idy) – N;
[V, U] = meshgrid(v, u);
D = sqrt(U.^2 + V.^2);
H = 1./(1 + (D./D0).^(2*n));
G = H.*FT_img;
output_image = real(ifft2(double(G)));
subplot(2, 1, 1), imshow(input_image),
subplot(2, 1, 2), imshow(output_image, [ ]);
the command window shows that:
Array dimensions must match for binary array op.
Error in Run_1 (line 24)
G = H.*FT_img;
I looked up on other people’s questions which are similar but i still don’t get it so if anyone can fix this for me, that would be greatly appreciated.
Sorry im new and thanks These are the codes:
input_image = imread (‘C.tif’);
[M, N] = size(input_image);
FT_img = fft2(double(input_image));
n = 2;
D0 = 20;
u = 0:(M-1);
v = 0:(N-1);
idx = find(u > M/2);
u(idx) = u(idx) – M;
idy = find(v > N/2);
v(idy) = v(idy) – N;
[V, U] = meshgrid(v, u);
D = sqrt(U.^2 + V.^2);
H = 1./(1 + (D./D0).^(2*n));
G = H.*FT_img;
output_image = real(ifft2(double(G)));
subplot(2, 1, 1), imshow(input_image),
subplot(2, 1, 2), imshow(output_image, [ ]);
the command window shows that:
Array dimensions must match for binary array op.
Error in Run_1 (line 24)
G = H.*FT_img;
I looked up on other people’s questions which are similar but i still don’t get it so if anyone can fix this for me, that would be greatly appreciated.
Sorry im new and thanks array dimension, binary array MATLAB Answers — New Questions
I need to find the index of a 2d matrix within a 3rd array which has the lowest number of NaN values.
I have a 3D array of dimensions 942x523x365 with numerical and NaN values. I would like to find the 2D slice along the 3rd Dimension with the lowest number of NaN values.I have a 3D array of dimensions 942x523x365 with numerical and NaN values. I would like to find the 2D slice along the 3rd Dimension with the lowest number of NaN values. I have a 3D array of dimensions 942x523x365 with numerical and NaN values. I would like to find the 2D slice along the 3rd Dimension with the lowest number of NaN values. find nans, 3d array, indexing MATLAB Answers — New Questions
The logical index at position 1 contains a true value outside the array boundary (Error tsVAR/estimate (line 826))
The logical index at position 1 contains a true value outside the array boundary
位置 1 处的逻辑索引包含一个在数组边界之外的 true 值。
Error tsVAR/estimate (line 826)
出错 tsVAR/estimate (第 826 行)
Ei = E(s == iii,:);
出错 TVAR_v1 (第 92 行)
EstMdl = estimate(tMdl,tt,Ye(:,1:6), Y0 = Y00(:,1:6),…
p = 4;
%%
% 加载数据
data = readtable(file_var);
year_quarter = data{:,1};
% 分解为年份和季度部分
year = floor(year_quarter);
quarter = round((year_quarter – year) * 4 + 1);
% 将季度转换为对应的月份
month = (quarter – 1) * 3 + 1;
% 创建一个 datetime 对象
dt = datetime(year, month, 1);
data{:,’time’} = dt;
data = table2timetable(data);
Y = data(:, vars);
%%
% 滤波用于判断经济周期
% one-sided HP filter
raw_data = Y; % 需滤波数据
lambda = 1600;
[Yt,Yc] = hpfilter(raw_data,lambda,FilterType="one-sided");
% 差分方法 去除趋势
Yd = diff(Y);
% 添加状态
Yd{:,"state"} = [NaN; Yc{1:end-1,"lrgdp"}];
%%
% 划分预样本和估计样本
maxp = 4;
T = height(Yd);
eT = T – maxp;
idxpre = 1:maxp;
idxest = (maxp+1):T;
Y0 = Yd(idxpre,:);
Ye = Yd(idxest,:);
%% 绘图与检验
pic = Yd(:,1:6);
tiledlayout(2,3)
for j = 1:width(pic)
nexttile
plot(pic.time,pic{:,j})
title(pic.Properties.VariableNames(j))
end
% ADF检验
% True 则可以拒绝原假设
[h, pValue] = adftest(Ye);
%% 构建模型
% 基础VAR构建
numseries = numel(vars);
Mdls = varm(Constant=NaN(numseries,1),Lags=[1 2 3 4], …
SeriesNames=vars);
% threhold
tt = threshold(0,Type = "discrete");
tt.StateNames = ["Recession" "Expansion"];
% 构建tsVAR
Mdls2 = [Mdls Mdls];
tMdl = tsVAR(tt,Mdls2);
% 转换数据类型
Y00 = table2array(Y0);
Ye = table2array(Ye);
%%
EstMdl = estimate(tMdl,tt,Ye(:,1:6), Y0 = Y00(:,1:6),…
Z=Ye(:,1),Type="exogenous",IterationPlot=false);The logical index at position 1 contains a true value outside the array boundary
位置 1 处的逻辑索引包含一个在数组边界之外的 true 值。
Error tsVAR/estimate (line 826)
出错 tsVAR/estimate (第 826 行)
Ei = E(s == iii,:);
出错 TVAR_v1 (第 92 行)
EstMdl = estimate(tMdl,tt,Ye(:,1:6), Y0 = Y00(:,1:6),…
p = 4;
%%
% 加载数据
data = readtable(file_var);
year_quarter = data{:,1};
% 分解为年份和季度部分
year = floor(year_quarter);
quarter = round((year_quarter – year) * 4 + 1);
% 将季度转换为对应的月份
month = (quarter – 1) * 3 + 1;
% 创建一个 datetime 对象
dt = datetime(year, month, 1);
data{:,’time’} = dt;
data = table2timetable(data);
Y = data(:, vars);
%%
% 滤波用于判断经济周期
% one-sided HP filter
raw_data = Y; % 需滤波数据
lambda = 1600;
[Yt,Yc] = hpfilter(raw_data,lambda,FilterType="one-sided");
% 差分方法 去除趋势
Yd = diff(Y);
% 添加状态
Yd{:,"state"} = [NaN; Yc{1:end-1,"lrgdp"}];
%%
% 划分预样本和估计样本
maxp = 4;
T = height(Yd);
eT = T – maxp;
idxpre = 1:maxp;
idxest = (maxp+1):T;
Y0 = Yd(idxpre,:);
Ye = Yd(idxest,:);
%% 绘图与检验
pic = Yd(:,1:6);
tiledlayout(2,3)
for j = 1:width(pic)
nexttile
plot(pic.time,pic{:,j})
title(pic.Properties.VariableNames(j))
end
% ADF检验
% True 则可以拒绝原假设
[h, pValue] = adftest(Ye);
%% 构建模型
% 基础VAR构建
numseries = numel(vars);
Mdls = varm(Constant=NaN(numseries,1),Lags=[1 2 3 4], …
SeriesNames=vars);
% threhold
tt = threshold(0,Type = "discrete");
tt.StateNames = ["Recession" "Expansion"];
% 构建tsVAR
Mdls2 = [Mdls Mdls];
tMdl = tsVAR(tt,Mdls2);
% 转换数据类型
Y00 = table2array(Y0);
Ye = table2array(Ye);
%%
EstMdl = estimate(tMdl,tt,Ye(:,1:6), Y0 = Y00(:,1:6),…
Z=Ye(:,1),Type="exogenous",IterationPlot=false); The logical index at position 1 contains a true value outside the array boundary
位置 1 处的逻辑索引包含一个在数组边界之外的 true 值。
Error tsVAR/estimate (line 826)
出错 tsVAR/estimate (第 826 行)
Ei = E(s == iii,:);
出错 TVAR_v1 (第 92 行)
EstMdl = estimate(tMdl,tt,Ye(:,1:6), Y0 = Y00(:,1:6),…
p = 4;
%%
% 加载数据
data = readtable(file_var);
year_quarter = data{:,1};
% 分解为年份和季度部分
year = floor(year_quarter);
quarter = round((year_quarter – year) * 4 + 1);
% 将季度转换为对应的月份
month = (quarter – 1) * 3 + 1;
% 创建一个 datetime 对象
dt = datetime(year, month, 1);
data{:,’time’} = dt;
data = table2timetable(data);
Y = data(:, vars);
%%
% 滤波用于判断经济周期
% one-sided HP filter
raw_data = Y; % 需滤波数据
lambda = 1600;
[Yt,Yc] = hpfilter(raw_data,lambda,FilterType="one-sided");
% 差分方法 去除趋势
Yd = diff(Y);
% 添加状态
Yd{:,"state"} = [NaN; Yc{1:end-1,"lrgdp"}];
%%
% 划分预样本和估计样本
maxp = 4;
T = height(Yd);
eT = T – maxp;
idxpre = 1:maxp;
idxest = (maxp+1):T;
Y0 = Yd(idxpre,:);
Ye = Yd(idxest,:);
%% 绘图与检验
pic = Yd(:,1:6);
tiledlayout(2,3)
for j = 1:width(pic)
nexttile
plot(pic.time,pic{:,j})
title(pic.Properties.VariableNames(j))
end
% ADF检验
% True 则可以拒绝原假设
[h, pValue] = adftest(Ye);
%% 构建模型
% 基础VAR构建
numseries = numel(vars);
Mdls = varm(Constant=NaN(numseries,1),Lags=[1 2 3 4], …
SeriesNames=vars);
% threhold
tt = threshold(0,Type = "discrete");
tt.StateNames = ["Recession" "Expansion"];
% 构建tsVAR
Mdls2 = [Mdls Mdls];
tMdl = tsVAR(tt,Mdls2);
% 转换数据类型
Y00 = table2array(Y0);
Ye = table2array(Ye);
%%
EstMdl = estimate(tMdl,tt,Ye(:,1:6), Y0 = Y00(:,1:6),…
Z=Ye(:,1),Type="exogenous",IterationPlot=false); estimate, tsvar MATLAB Answers — New Questions
i have error in runge kutta 4 order.
Alpha1=1;
Alpha2=2;
S=1;
omega=1
gamma=1;
Sc=1;
Pr=1.0;
f_omega=0.4;
zeta=0;
k = 0.1;
h=0.05; % step size
eta = 0:h:100; % Calculates upto y(3)
H = zeros(1,length(eta));
g = zeros(1,length(eta));
F = zeros(1,length(eta));
z = zeros(1,length(eta));
G = zeros(1,length(eta));
x = zeros(1,length(eta));
theta = zeros(1,length(eta));
y = zeros(1,length(eta));
phi = zeros(1,length(eta));
F(1) = 0;
G(1) = omega;
theta(1) = 1;
phi(1) = 1;
H(1) = S +f_omega / Sc * y(1) ;
u1 = @(eta, H) (-2*F);
u2 = @(eta,F) g;
u3 = @(eta,F,g) (g*H – G.^2 +F.^2 – S(((eta+1)/2)*g + F) + k(z.^2 -g.^2)) / (1-2*F*k);
u4 = @(eta,G) z;
u5 = @(eta,G,z) ((H*z + 2*F*G – S(((eta+1)/2)*z + G) – 2*k*g*z)/(1-2*F*k));
u6 = @(eta, theta) x;
u7 = @(eta, theta , x) (Pr*(H*x + S(((rta+1)/2)*x + alpha1*theta) – 2*zeta*F*H*x)/(1-Pr*zeta));
u8 = @(eta, phi) y ;
u9 = @(eta, phi, y) (Sc*(H*y – S(((eta+1)/2)*y + alpha2*phi) +gamma*phi));
for i=1:(length(eta)-1) % calculation loop
k_1 =u1(eta(i),H(i));
l_1 =u2(eta(i),F(i));
m_1 =u3(eta(i),F(i),g(i));
n_1 =u4(eta(i),G(i));
o_1 =u5(eta(i),G(i),z(i));
p_1 =u6(eta(i),theta(i));
q_1 =u7(eta(i),theta(i),x(i));
r_1 =u8(eta(i),phi(i));
s_1 =u9(eta(i),phi(i),y(i));
k_2 = u1(eta(i)+0.5*h,H(i)+0.5*h*k_1);
l_2 = u2(eta(i)+0.5*h,F(i)+0.5*h*l_1);
m_2 = u3(eta(i)+0.5*h,F(i)+0.5*h*l_1,g(i)+0.5*h*m_1);
n_2 = u4(eta(i)+0.5*h,G(i)+0.5*h*n_1);
o_2 = u5(eta(i)+0.5*h,G(i)+0.5*h*n_1,z(i)+0.5*h*o_1);
p_2 = u6(eta(i)+0.5*h,theta(i)+0.5*h*p_1);
q_2 = u7(eta(i)+0.5*h,theta(i)+0.5*h*p_1,x(i)+0.5*h*q_1);
r_2 = u8(eta(i)+0.5*h,phi(i)+0.5*h*r_1);
s_2 = u9(eta(i)+0.5*h,phi(i)+0.5*h*r_1,x(i)+0.5*h*s_1);
k_3 = u1(eta(i)+0.5*h,H(i)+0.5*h*k_2);
l_3 = u2(eta(i)+0.5*h,F(i)+0.5*h*l_2);
m_3 = u3(eta(i)+0.5*h,F(i)+0.5*h*l_2,g(i)+0.5*h*m_2);
n_3 = u4(eta(i)+0.5*h,G(i)+0.5*h*n_2);
o_3 = u5(eta(i)+0.5*h,G(i)+0.5*h*n_2,z(i)+0.5*h*o_2);
p_3 = u6(eta(i)+0.5*h,theta(i)+0.5*h*p_2);
q_3 = u7(eta(i)+0.5*h,theta(i)+0.5*h*p_2,x(i)+0.5*h*q_2);
r_3 = u8(eta(i)+0.5*h,phi(i)+0.5*h*r_2);
s_3 = u9(eta(i)+0.5*h,phi(i)+0.5*h*r_2,x(i)+0.5*h*s_2);
k_4 = u1(eta(i)+h,H(i)+h*k_3);
l_4 = u2(eta(i)+h,F(i)+h*l_3);
m_4 = u3(eta(i)+h,F(i)+h*l_3,g(i)+h*m_3);
n_4 = u4(eta(i)+h,G(i)+h*n_3);
o_4 = u5(eta(i)+h,G(i)+h*n_3,z(i)+h*o_3);
p_4 = u6(eta(i)+h,theta(i)+0.5*h*p_2);
q_4 = u7(eta(i)+h,theta(i)+h*p_3,x(i)+h*q_3);
r_4 = u8(eta(i)+h,phi(i)+h*r_3);
s_4 = u9(eta(i)+h,phi(i)+h*r_3,x(i)+h*s_3);
H(i+1) = H(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
g(i+1) = g(i) + (1/6)*(l_1+2*l_2+2*l_3+l_4)*h;
F(i+1) = F(i) + (1/6)*(m_1+2*m_2+2*m_3+m_4)*h;
z(i+1) = z(i) + (1/6)*(n_1+2*n_2+2*n_3+n_4)*h;
G(i+1) = G(i) + (1/6)*(o_1+2*o_2+2*o_3+o_4)*h;
x(i+1) = x(i) + (1/6)*(p_1+2*p_2+2*p_3+p_4)*h;
theta(i+1) = theta(i) + (1/6)*(q_1+2*q_2+2*q_3+q_4)*h;
y(i+1) = y(i) + (1/6)*(r_1+2*r_2+2*r_3+r_4)*h;
phi(i+1) = phi(i) + (1/6)*(s_1+2*s_2+2*s_3+s_4)*h;
end
figure();
subplot(3,2,1);
plot(eta, F);
title(‘F vs eta’);
xlabel(‘eta’);
ylabel(‘F’);
subplot(3,2,2);
plot(eta, G);
title(‘G vs eta’);
xlabel(‘eta’);
ylabel(‘G’);
subplot(3,2,3);
plot(eta, theta);
title(‘theta vs eta’);
xlabel(‘eta’);
ylabel(‘theta’);
subplot(3,2,4);
plot(eta, phi);
title(‘phi vs eta’);
xlabel(‘eta’);
ylabel(‘phi’);
subplot(3,2,5);
plot(eta, H);
title(‘H vs eta’);
xlabel(‘eta’);
ylabel(‘H’);
error
Array indices must be positive integers or logical values.Alpha1=1;
Alpha2=2;
S=1;
omega=1
gamma=1;
Sc=1;
Pr=1.0;
f_omega=0.4;
zeta=0;
k = 0.1;
h=0.05; % step size
eta = 0:h:100; % Calculates upto y(3)
H = zeros(1,length(eta));
g = zeros(1,length(eta));
F = zeros(1,length(eta));
z = zeros(1,length(eta));
G = zeros(1,length(eta));
x = zeros(1,length(eta));
theta = zeros(1,length(eta));
y = zeros(1,length(eta));
phi = zeros(1,length(eta));
F(1) = 0;
G(1) = omega;
theta(1) = 1;
phi(1) = 1;
H(1) = S +f_omega / Sc * y(1) ;
u1 = @(eta, H) (-2*F);
u2 = @(eta,F) g;
u3 = @(eta,F,g) (g*H – G.^2 +F.^2 – S(((eta+1)/2)*g + F) + k(z.^2 -g.^2)) / (1-2*F*k);
u4 = @(eta,G) z;
u5 = @(eta,G,z) ((H*z + 2*F*G – S(((eta+1)/2)*z + G) – 2*k*g*z)/(1-2*F*k));
u6 = @(eta, theta) x;
u7 = @(eta, theta , x) (Pr*(H*x + S(((rta+1)/2)*x + alpha1*theta) – 2*zeta*F*H*x)/(1-Pr*zeta));
u8 = @(eta, phi) y ;
u9 = @(eta, phi, y) (Sc*(H*y – S(((eta+1)/2)*y + alpha2*phi) +gamma*phi));
for i=1:(length(eta)-1) % calculation loop
k_1 =u1(eta(i),H(i));
l_1 =u2(eta(i),F(i));
m_1 =u3(eta(i),F(i),g(i));
n_1 =u4(eta(i),G(i));
o_1 =u5(eta(i),G(i),z(i));
p_1 =u6(eta(i),theta(i));
q_1 =u7(eta(i),theta(i),x(i));
r_1 =u8(eta(i),phi(i));
s_1 =u9(eta(i),phi(i),y(i));
k_2 = u1(eta(i)+0.5*h,H(i)+0.5*h*k_1);
l_2 = u2(eta(i)+0.5*h,F(i)+0.5*h*l_1);
m_2 = u3(eta(i)+0.5*h,F(i)+0.5*h*l_1,g(i)+0.5*h*m_1);
n_2 = u4(eta(i)+0.5*h,G(i)+0.5*h*n_1);
o_2 = u5(eta(i)+0.5*h,G(i)+0.5*h*n_1,z(i)+0.5*h*o_1);
p_2 = u6(eta(i)+0.5*h,theta(i)+0.5*h*p_1);
q_2 = u7(eta(i)+0.5*h,theta(i)+0.5*h*p_1,x(i)+0.5*h*q_1);
r_2 = u8(eta(i)+0.5*h,phi(i)+0.5*h*r_1);
s_2 = u9(eta(i)+0.5*h,phi(i)+0.5*h*r_1,x(i)+0.5*h*s_1);
k_3 = u1(eta(i)+0.5*h,H(i)+0.5*h*k_2);
l_3 = u2(eta(i)+0.5*h,F(i)+0.5*h*l_2);
m_3 = u3(eta(i)+0.5*h,F(i)+0.5*h*l_2,g(i)+0.5*h*m_2);
n_3 = u4(eta(i)+0.5*h,G(i)+0.5*h*n_2);
o_3 = u5(eta(i)+0.5*h,G(i)+0.5*h*n_2,z(i)+0.5*h*o_2);
p_3 = u6(eta(i)+0.5*h,theta(i)+0.5*h*p_2);
q_3 = u7(eta(i)+0.5*h,theta(i)+0.5*h*p_2,x(i)+0.5*h*q_2);
r_3 = u8(eta(i)+0.5*h,phi(i)+0.5*h*r_2);
s_3 = u9(eta(i)+0.5*h,phi(i)+0.5*h*r_2,x(i)+0.5*h*s_2);
k_4 = u1(eta(i)+h,H(i)+h*k_3);
l_4 = u2(eta(i)+h,F(i)+h*l_3);
m_4 = u3(eta(i)+h,F(i)+h*l_3,g(i)+h*m_3);
n_4 = u4(eta(i)+h,G(i)+h*n_3);
o_4 = u5(eta(i)+h,G(i)+h*n_3,z(i)+h*o_3);
p_4 = u6(eta(i)+h,theta(i)+0.5*h*p_2);
q_4 = u7(eta(i)+h,theta(i)+h*p_3,x(i)+h*q_3);
r_4 = u8(eta(i)+h,phi(i)+h*r_3);
s_4 = u9(eta(i)+h,phi(i)+h*r_3,x(i)+h*s_3);
H(i+1) = H(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
g(i+1) = g(i) + (1/6)*(l_1+2*l_2+2*l_3+l_4)*h;
F(i+1) = F(i) + (1/6)*(m_1+2*m_2+2*m_3+m_4)*h;
z(i+1) = z(i) + (1/6)*(n_1+2*n_2+2*n_3+n_4)*h;
G(i+1) = G(i) + (1/6)*(o_1+2*o_2+2*o_3+o_4)*h;
x(i+1) = x(i) + (1/6)*(p_1+2*p_2+2*p_3+p_4)*h;
theta(i+1) = theta(i) + (1/6)*(q_1+2*q_2+2*q_3+q_4)*h;
y(i+1) = y(i) + (1/6)*(r_1+2*r_2+2*r_3+r_4)*h;
phi(i+1) = phi(i) + (1/6)*(s_1+2*s_2+2*s_3+s_4)*h;
end
figure();
subplot(3,2,1);
plot(eta, F);
title(‘F vs eta’);
xlabel(‘eta’);
ylabel(‘F’);
subplot(3,2,2);
plot(eta, G);
title(‘G vs eta’);
xlabel(‘eta’);
ylabel(‘G’);
subplot(3,2,3);
plot(eta, theta);
title(‘theta vs eta’);
xlabel(‘eta’);
ylabel(‘theta’);
subplot(3,2,4);
plot(eta, phi);
title(‘phi vs eta’);
xlabel(‘eta’);
ylabel(‘phi’);
subplot(3,2,5);
plot(eta, H);
title(‘H vs eta’);
xlabel(‘eta’);
ylabel(‘H’);
error
Array indices must be positive integers or logical values. Alpha1=1;
Alpha2=2;
S=1;
omega=1
gamma=1;
Sc=1;
Pr=1.0;
f_omega=0.4;
zeta=0;
k = 0.1;
h=0.05; % step size
eta = 0:h:100; % Calculates upto y(3)
H = zeros(1,length(eta));
g = zeros(1,length(eta));
F = zeros(1,length(eta));
z = zeros(1,length(eta));
G = zeros(1,length(eta));
x = zeros(1,length(eta));
theta = zeros(1,length(eta));
y = zeros(1,length(eta));
phi = zeros(1,length(eta));
F(1) = 0;
G(1) = omega;
theta(1) = 1;
phi(1) = 1;
H(1) = S +f_omega / Sc * y(1) ;
u1 = @(eta, H) (-2*F);
u2 = @(eta,F) g;
u3 = @(eta,F,g) (g*H – G.^2 +F.^2 – S(((eta+1)/2)*g + F) + k(z.^2 -g.^2)) / (1-2*F*k);
u4 = @(eta,G) z;
u5 = @(eta,G,z) ((H*z + 2*F*G – S(((eta+1)/2)*z + G) – 2*k*g*z)/(1-2*F*k));
u6 = @(eta, theta) x;
u7 = @(eta, theta , x) (Pr*(H*x + S(((rta+1)/2)*x + alpha1*theta) – 2*zeta*F*H*x)/(1-Pr*zeta));
u8 = @(eta, phi) y ;
u9 = @(eta, phi, y) (Sc*(H*y – S(((eta+1)/2)*y + alpha2*phi) +gamma*phi));
for i=1:(length(eta)-1) % calculation loop
k_1 =u1(eta(i),H(i));
l_1 =u2(eta(i),F(i));
m_1 =u3(eta(i),F(i),g(i));
n_1 =u4(eta(i),G(i));
o_1 =u5(eta(i),G(i),z(i));
p_1 =u6(eta(i),theta(i));
q_1 =u7(eta(i),theta(i),x(i));
r_1 =u8(eta(i),phi(i));
s_1 =u9(eta(i),phi(i),y(i));
k_2 = u1(eta(i)+0.5*h,H(i)+0.5*h*k_1);
l_2 = u2(eta(i)+0.5*h,F(i)+0.5*h*l_1);
m_2 = u3(eta(i)+0.5*h,F(i)+0.5*h*l_1,g(i)+0.5*h*m_1);
n_2 = u4(eta(i)+0.5*h,G(i)+0.5*h*n_1);
o_2 = u5(eta(i)+0.5*h,G(i)+0.5*h*n_1,z(i)+0.5*h*o_1);
p_2 = u6(eta(i)+0.5*h,theta(i)+0.5*h*p_1);
q_2 = u7(eta(i)+0.5*h,theta(i)+0.5*h*p_1,x(i)+0.5*h*q_1);
r_2 = u8(eta(i)+0.5*h,phi(i)+0.5*h*r_1);
s_2 = u9(eta(i)+0.5*h,phi(i)+0.5*h*r_1,x(i)+0.5*h*s_1);
k_3 = u1(eta(i)+0.5*h,H(i)+0.5*h*k_2);
l_3 = u2(eta(i)+0.5*h,F(i)+0.5*h*l_2);
m_3 = u3(eta(i)+0.5*h,F(i)+0.5*h*l_2,g(i)+0.5*h*m_2);
n_3 = u4(eta(i)+0.5*h,G(i)+0.5*h*n_2);
o_3 = u5(eta(i)+0.5*h,G(i)+0.5*h*n_2,z(i)+0.5*h*o_2);
p_3 = u6(eta(i)+0.5*h,theta(i)+0.5*h*p_2);
q_3 = u7(eta(i)+0.5*h,theta(i)+0.5*h*p_2,x(i)+0.5*h*q_2);
r_3 = u8(eta(i)+0.5*h,phi(i)+0.5*h*r_2);
s_3 = u9(eta(i)+0.5*h,phi(i)+0.5*h*r_2,x(i)+0.5*h*s_2);
k_4 = u1(eta(i)+h,H(i)+h*k_3);
l_4 = u2(eta(i)+h,F(i)+h*l_3);
m_4 = u3(eta(i)+h,F(i)+h*l_3,g(i)+h*m_3);
n_4 = u4(eta(i)+h,G(i)+h*n_3);
o_4 = u5(eta(i)+h,G(i)+h*n_3,z(i)+h*o_3);
p_4 = u6(eta(i)+h,theta(i)+0.5*h*p_2);
q_4 = u7(eta(i)+h,theta(i)+h*p_3,x(i)+h*q_3);
r_4 = u8(eta(i)+h,phi(i)+h*r_3);
s_4 = u9(eta(i)+h,phi(i)+h*r_3,x(i)+h*s_3);
H(i+1) = H(i) + (1/6)*(k_1+2*k_2+2*k_3+k_4)*h;
g(i+1) = g(i) + (1/6)*(l_1+2*l_2+2*l_3+l_4)*h;
F(i+1) = F(i) + (1/6)*(m_1+2*m_2+2*m_3+m_4)*h;
z(i+1) = z(i) + (1/6)*(n_1+2*n_2+2*n_3+n_4)*h;
G(i+1) = G(i) + (1/6)*(o_1+2*o_2+2*o_3+o_4)*h;
x(i+1) = x(i) + (1/6)*(p_1+2*p_2+2*p_3+p_4)*h;
theta(i+1) = theta(i) + (1/6)*(q_1+2*q_2+2*q_3+q_4)*h;
y(i+1) = y(i) + (1/6)*(r_1+2*r_2+2*r_3+r_4)*h;
phi(i+1) = phi(i) + (1/6)*(s_1+2*s_2+2*s_3+s_4)*h;
end
figure();
subplot(3,2,1);
plot(eta, F);
title(‘F vs eta’);
xlabel(‘eta’);
ylabel(‘F’);
subplot(3,2,2);
plot(eta, G);
title(‘G vs eta’);
xlabel(‘eta’);
ylabel(‘G’);
subplot(3,2,3);
plot(eta, theta);
title(‘theta vs eta’);
xlabel(‘eta’);
ylabel(‘theta’);
subplot(3,2,4);
plot(eta, phi);
title(‘phi vs eta’);
xlabel(‘eta’);
ylabel(‘phi’);
subplot(3,2,5);
plot(eta, H);
title(‘H vs eta’);
xlabel(‘eta’);
ylabel(‘H’);
error
Array indices must be positive integers or logical values. rashmi MATLAB Answers — New Questions
please explain the function of each command used in this code. These commands are part of allan variance code.
avar = zeros(numel(m), 1);
for i = 1:numel(m)
mi = m(i);
avar(i,:) = sum((theta(1+2*mi:L) – 2*theta(1+mi:L-mi) + theta(1:L-2*mi)).^2, 1);
end
avar = avar ./ (2*tau.^2 .* (L – 2*m));
adev = sqrt(avar);avar = zeros(numel(m), 1);
for i = 1:numel(m)
mi = m(i);
avar(i,:) = sum((theta(1+2*mi:L) – 2*theta(1+mi:L-mi) + theta(1:L-2*mi)).^2, 1);
end
avar = avar ./ (2*tau.^2 .* (L – 2*m));
adev = sqrt(avar); avar = zeros(numel(m), 1);
for i = 1:numel(m)
mi = m(i);
avar(i,:) = sum((theta(1+2*mi:L) – 2*theta(1+mi:L-mi) + theta(1:L-2*mi)).^2, 1);
end
avar = avar ./ (2*tau.^2 .* (L – 2*m));
adev = sqrt(avar); algorithm, matlab function MATLAB Answers — New Questions