Category: Matlab
Category Archives: Matlab
¿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
If I change my PC, can I re-install a Matlab license in the new PC (uninstalling from the old)?
I am planning to purchase a Matlab license, and I plan to change my PC next year.
Is the MatLab license tied to a single PC?
Once installed in a PC, if I change my PC can I re-install the license in this new PC (uninstalling the licence from the old PC)?I am planning to purchase a Matlab license, and I plan to change my PC next year.
Is the MatLab license tied to a single PC?
Once installed in a PC, if I change my PC can I re-install the license in this new PC (uninstalling the licence from the old PC)? I am planning to purchase a Matlab license, and I plan to change my PC next year.
Is the MatLab license tied to a single PC?
Once installed in a PC, if I change my PC can I re-install the license in this new PC (uninstalling the licence from the old PC)? reinstall MATLAB Answers — New Questions
Fitting multiple curves with multiple data sets, partial and globally shared parameters using lsqcurvefit
Hello everyone, I hope you can help me with the following problem. I have 3 measurement data sets, consisting of x-values (e.g. x1) and 2 corresponding y-data sets (e.g. A1 and B1). The functions of these parameters have partially shared parameters. A simultaneous fit over both curves works so far. Now I want to run a global fit over all 3 measurement datasets simultaneously, where all 3 measurement datasets share one parameter (beta(10)). How do I do this? Previously, I received a value for beta (10) for each fit, but now I want to change this. My data and functions (non-linear) are very extensive, so I have created a simplified example.
b1 = 1; b2 = 0.85; b3 = 2.5;
b4 = 1.1; b5 = 2.2; b6 = 4.5;
b7 = 1.3; b8 = 7.2; b9 = 9.5;
b10 = 0.5;
%x data
x1 = linspace(0, 10, 20).’; x2 = linspace(0, 10, 23).’; x3 = linspace(0, 10, 14).’;
%constants
C1 = 3.7 ; C2 = 4.2; C3 = 20.2;
%measurement dataset 1
A1 = b1 + b2*x1 + C1 * b10 + rand(20,1);
B1 = b3 – b2*x1 + C1 * b10 + rand(20,1);
%measurement dataset 2
A2 = b4 + b5*x2 + C2 * b10 + rand(23,1);
B2 = b6 – b5*x2 + C2 * b10 + rand(23,1);
%measurement dataset 3
A3 = b7 + b8*x3 + C3 * b10 + rand(14,1);
B3 = b9 – b8*x3 + C3 * b10 + rand(14,1);
mdl1 = @(beta, x) [beta(1) + beta(2).*x + C1 .* beta(10) ,…
beta(3) – beta(2).*x + C1 .* beta(10)];
mdl2 = @(beta, x) [beta(4) + beta(5).*x + C2 .* beta(10) ,…
beta(6) – beta(5).*x + C2 .* beta(10)];
mdl3 = @(beta, x) [beta(7) + beta(8).*x + C3 .* beta(10) ,…
beta(9) – beta(8).*x + C3 .* beta(10)];
beta0 = [0.92, 0.8, 2, 0.7, 2, 4, 1, 7, 9, 1];
lb = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
ub = [15, 15, 15, 15, 15, 15, 15, 15, 15, 15];
options = optimoptions(@lsqcurvefit,’Algorithm’,’levenberg-marquardt’);
beta1 = lsqcurvefit(mdl1,beta0,x1,[A1, B1],lb,ub,options);
beta2 = lsqcurvefit(mdl2,beta0,x2,[A2, B2],lb,ub,options);
beta3 = lsqcurvefit(mdl3,beta0,x3,[A3, B3],lb,ub,options);
A1_fit = beta1(1) + beta1(2)*x1 + C1 * beta1(10);
B1_fit = beta1(3) – beta1(2)*x1 + C1 * beta1(10);
A2_fit = beta2(4) + beta2(5)*x2 + C2 * beta2(10);
B2_fit = beta2(6) – beta2(5)*x2 + C2 * beta2(10);
A3_fit = beta3(7) + beta3(8)*x3 + C3 * beta3(10);
B3_fit = beta3(9) – beta3(8)*x3 + C3 * beta3(10);
figure(1);
subplot(2,1,1);
hold on;
plot(x1, A1,’s’);
plot(x1, A1_fit);
plot(x2, A2,’d’);
plot(x2, A2_fit);
plot(x3, A3,’p’);
plot(x3, A3_fit);
subplot(2,1,2);
hold on;
plot(x1, B1,’s’);
plot(x1, B1_fit);
plot(x2, B2,’d’);
plot(x2, B2_fit);
plot(x3, B3,’p’);
plot(x3, B3_fit);
hold offHello everyone, I hope you can help me with the following problem. I have 3 measurement data sets, consisting of x-values (e.g. x1) and 2 corresponding y-data sets (e.g. A1 and B1). The functions of these parameters have partially shared parameters. A simultaneous fit over both curves works so far. Now I want to run a global fit over all 3 measurement datasets simultaneously, where all 3 measurement datasets share one parameter (beta(10)). How do I do this? Previously, I received a value for beta (10) for each fit, but now I want to change this. My data and functions (non-linear) are very extensive, so I have created a simplified example.
b1 = 1; b2 = 0.85; b3 = 2.5;
b4 = 1.1; b5 = 2.2; b6 = 4.5;
b7 = 1.3; b8 = 7.2; b9 = 9.5;
b10 = 0.5;
%x data
x1 = linspace(0, 10, 20).’; x2 = linspace(0, 10, 23).’; x3 = linspace(0, 10, 14).’;
%constants
C1 = 3.7 ; C2 = 4.2; C3 = 20.2;
%measurement dataset 1
A1 = b1 + b2*x1 + C1 * b10 + rand(20,1);
B1 = b3 – b2*x1 + C1 * b10 + rand(20,1);
%measurement dataset 2
A2 = b4 + b5*x2 + C2 * b10 + rand(23,1);
B2 = b6 – b5*x2 + C2 * b10 + rand(23,1);
%measurement dataset 3
A3 = b7 + b8*x3 + C3 * b10 + rand(14,1);
B3 = b9 – b8*x3 + C3 * b10 + rand(14,1);
mdl1 = @(beta, x) [beta(1) + beta(2).*x + C1 .* beta(10) ,…
beta(3) – beta(2).*x + C1 .* beta(10)];
mdl2 = @(beta, x) [beta(4) + beta(5).*x + C2 .* beta(10) ,…
beta(6) – beta(5).*x + C2 .* beta(10)];
mdl3 = @(beta, x) [beta(7) + beta(8).*x + C3 .* beta(10) ,…
beta(9) – beta(8).*x + C3 .* beta(10)];
beta0 = [0.92, 0.8, 2, 0.7, 2, 4, 1, 7, 9, 1];
lb = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
ub = [15, 15, 15, 15, 15, 15, 15, 15, 15, 15];
options = optimoptions(@lsqcurvefit,’Algorithm’,’levenberg-marquardt’);
beta1 = lsqcurvefit(mdl1,beta0,x1,[A1, B1],lb,ub,options);
beta2 = lsqcurvefit(mdl2,beta0,x2,[A2, B2],lb,ub,options);
beta3 = lsqcurvefit(mdl3,beta0,x3,[A3, B3],lb,ub,options);
A1_fit = beta1(1) + beta1(2)*x1 + C1 * beta1(10);
B1_fit = beta1(3) – beta1(2)*x1 + C1 * beta1(10);
A2_fit = beta2(4) + beta2(5)*x2 + C2 * beta2(10);
B2_fit = beta2(6) – beta2(5)*x2 + C2 * beta2(10);
A3_fit = beta3(7) + beta3(8)*x3 + C3 * beta3(10);
B3_fit = beta3(9) – beta3(8)*x3 + C3 * beta3(10);
figure(1);
subplot(2,1,1);
hold on;
plot(x1, A1,’s’);
plot(x1, A1_fit);
plot(x2, A2,’d’);
plot(x2, A2_fit);
plot(x3, A3,’p’);
plot(x3, A3_fit);
subplot(2,1,2);
hold on;
plot(x1, B1,’s’);
plot(x1, B1_fit);
plot(x2, B2,’d’);
plot(x2, B2_fit);
plot(x3, B3,’p’);
plot(x3, B3_fit);
hold off Hello everyone, I hope you can help me with the following problem. I have 3 measurement data sets, consisting of x-values (e.g. x1) and 2 corresponding y-data sets (e.g. A1 and B1). The functions of these parameters have partially shared parameters. A simultaneous fit over both curves works so far. Now I want to run a global fit over all 3 measurement datasets simultaneously, where all 3 measurement datasets share one parameter (beta(10)). How do I do this? Previously, I received a value for beta (10) for each fit, but now I want to change this. My data and functions (non-linear) are very extensive, so I have created a simplified example.
b1 = 1; b2 = 0.85; b3 = 2.5;
b4 = 1.1; b5 = 2.2; b6 = 4.5;
b7 = 1.3; b8 = 7.2; b9 = 9.5;
b10 = 0.5;
%x data
x1 = linspace(0, 10, 20).’; x2 = linspace(0, 10, 23).’; x3 = linspace(0, 10, 14).’;
%constants
C1 = 3.7 ; C2 = 4.2; C3 = 20.2;
%measurement dataset 1
A1 = b1 + b2*x1 + C1 * b10 + rand(20,1);
B1 = b3 – b2*x1 + C1 * b10 + rand(20,1);
%measurement dataset 2
A2 = b4 + b5*x2 + C2 * b10 + rand(23,1);
B2 = b6 – b5*x2 + C2 * b10 + rand(23,1);
%measurement dataset 3
A3 = b7 + b8*x3 + C3 * b10 + rand(14,1);
B3 = b9 – b8*x3 + C3 * b10 + rand(14,1);
mdl1 = @(beta, x) [beta(1) + beta(2).*x + C1 .* beta(10) ,…
beta(3) – beta(2).*x + C1 .* beta(10)];
mdl2 = @(beta, x) [beta(4) + beta(5).*x + C2 .* beta(10) ,…
beta(6) – beta(5).*x + C2 .* beta(10)];
mdl3 = @(beta, x) [beta(7) + beta(8).*x + C3 .* beta(10) ,…
beta(9) – beta(8).*x + C3 .* beta(10)];
beta0 = [0.92, 0.8, 2, 0.7, 2, 4, 1, 7, 9, 1];
lb = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
ub = [15, 15, 15, 15, 15, 15, 15, 15, 15, 15];
options = optimoptions(@lsqcurvefit,’Algorithm’,’levenberg-marquardt’);
beta1 = lsqcurvefit(mdl1,beta0,x1,[A1, B1],lb,ub,options);
beta2 = lsqcurvefit(mdl2,beta0,x2,[A2, B2],lb,ub,options);
beta3 = lsqcurvefit(mdl3,beta0,x3,[A3, B3],lb,ub,options);
A1_fit = beta1(1) + beta1(2)*x1 + C1 * beta1(10);
B1_fit = beta1(3) – beta1(2)*x1 + C1 * beta1(10);
A2_fit = beta2(4) + beta2(5)*x2 + C2 * beta2(10);
B2_fit = beta2(6) – beta2(5)*x2 + C2 * beta2(10);
A3_fit = beta3(7) + beta3(8)*x3 + C3 * beta3(10);
B3_fit = beta3(9) – beta3(8)*x3 + C3 * beta3(10);
figure(1);
subplot(2,1,1);
hold on;
plot(x1, A1,’s’);
plot(x1, A1_fit);
plot(x2, A2,’d’);
plot(x2, A2_fit);
plot(x3, A3,’p’);
plot(x3, A3_fit);
subplot(2,1,2);
hold on;
plot(x1, B1,’s’);
plot(x1, B1_fit);
plot(x2, B2,’d’);
plot(x2, B2_fit);
plot(x3, B3,’p’);
plot(x3, B3_fit);
hold off lsqcurvefit, fitting multiple curves MATLAB Answers — New Questions
Up-sampling in convolutional neural network
Hi everyone,
for a project at university I am trying to rebuild a NN described in a paper. It was orininally designed in Keras (I don’t have any code, only its rough describtion) and I’m struggling with one specific layer they’re using. To up-sample their data, they use a layer which takes a single entry of its input and replicates it to a 2×2-region of the output. This results in a matrix with doubled dimensions, without zero-entries (assuming there was none in input) and same entry in each 2×2-block. It is an approximation to the inverse of the maxPooling-Layer of MATLAB. It is similar, but NOT the same as maxUnpooling-Layer, which keeps the position of an maximum-entry and fills up with zeros. For this specific "up-sampling-operation", there is no explicit NN-layer in MATLAB.
Does someone have an idea how I can do this operation?
An idea I had in mind: Just using the given maxUnpooling-Layer and hope there will be no big difference. I tried this and prepared my maxPooling-Layers with "HasUnpoolingOutputs", but it seems that maxUnpooling-Layer has to follow immediately after the maxPooling-Layer. I get unused outputs for my maxPooling-Layers and missing outputs for my maxUnpooling-Layers (seen via analyzeNetwork) as I use convolution-layers in between (see code for example).
layers = [
imageInputLayer([32 32 1])
convolution2dLayer(filterSize, 32, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
maxPooling2dLayer(2,’Stride’,2,’HasUnpoolingOutputs’,true) %
convolution2dLayer(filterSize, 64, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
maxUnpooling2dLayer() %
convolution2dLayer(filterSize, 32, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
fullyConnectedLayer(32)
regressionLayer
];
So in this case, one has to bring the outputs "indices" and "size" of the maxPooling-layer to the maxUnpooling-layer. But I don’t know how this can be achieved :/
I’d be very thankful for any ideas.Hi everyone,
for a project at university I am trying to rebuild a NN described in a paper. It was orininally designed in Keras (I don’t have any code, only its rough describtion) and I’m struggling with one specific layer they’re using. To up-sample their data, they use a layer which takes a single entry of its input and replicates it to a 2×2-region of the output. This results in a matrix with doubled dimensions, without zero-entries (assuming there was none in input) and same entry in each 2×2-block. It is an approximation to the inverse of the maxPooling-Layer of MATLAB. It is similar, but NOT the same as maxUnpooling-Layer, which keeps the position of an maximum-entry and fills up with zeros. For this specific "up-sampling-operation", there is no explicit NN-layer in MATLAB.
Does someone have an idea how I can do this operation?
An idea I had in mind: Just using the given maxUnpooling-Layer and hope there will be no big difference. I tried this and prepared my maxPooling-Layers with "HasUnpoolingOutputs", but it seems that maxUnpooling-Layer has to follow immediately after the maxPooling-Layer. I get unused outputs for my maxPooling-Layers and missing outputs for my maxUnpooling-Layers (seen via analyzeNetwork) as I use convolution-layers in between (see code for example).
layers = [
imageInputLayer([32 32 1])
convolution2dLayer(filterSize, 32, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
maxPooling2dLayer(2,’Stride’,2,’HasUnpoolingOutputs’,true) %
convolution2dLayer(filterSize, 64, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
maxUnpooling2dLayer() %
convolution2dLayer(filterSize, 32, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
fullyConnectedLayer(32)
regressionLayer
];
So in this case, one has to bring the outputs "indices" and "size" of the maxPooling-layer to the maxUnpooling-layer. But I don’t know how this can be achieved :/
I’d be very thankful for any ideas. Hi everyone,
for a project at university I am trying to rebuild a NN described in a paper. It was orininally designed in Keras (I don’t have any code, only its rough describtion) and I’m struggling with one specific layer they’re using. To up-sample their data, they use a layer which takes a single entry of its input and replicates it to a 2×2-region of the output. This results in a matrix with doubled dimensions, without zero-entries (assuming there was none in input) and same entry in each 2×2-block. It is an approximation to the inverse of the maxPooling-Layer of MATLAB. It is similar, but NOT the same as maxUnpooling-Layer, which keeps the position of an maximum-entry and fills up with zeros. For this specific "up-sampling-operation", there is no explicit NN-layer in MATLAB.
Does someone have an idea how I can do this operation?
An idea I had in mind: Just using the given maxUnpooling-Layer and hope there will be no big difference. I tried this and prepared my maxPooling-Layers with "HasUnpoolingOutputs", but it seems that maxUnpooling-Layer has to follow immediately after the maxPooling-Layer. I get unused outputs for my maxPooling-Layers and missing outputs for my maxUnpooling-Layers (seen via analyzeNetwork) as I use convolution-layers in between (see code for example).
layers = [
imageInputLayer([32 32 1])
convolution2dLayer(filterSize, 32, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
maxPooling2dLayer(2,’Stride’,2,’HasUnpoolingOutputs’,true) %
convolution2dLayer(filterSize, 64, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
maxUnpooling2dLayer() %
convolution2dLayer(filterSize, 32, ‘Padding’, ‘same’)
batchNormalizationLayer()
reluLayer()
fullyConnectedLayer(32)
regressionLayer
];
So in this case, one has to bring the outputs "indices" and "size" of the maxPooling-layer to the maxUnpooling-layer. But I don’t know how this can be achieved :/
I’d be very thankful for any ideas. neural network MATLAB Answers — New Questions
Simulation Crash Issue with Current Limiter and Motor Drive System
Hello MATLAB Community,
I am currently working on a Simscape model where a battery is connected to a current limiter and subsequently to a "motor and drive" system block. I am experiencing an issue where the simulation crashes as soon as the current limiter attempts to limit the current.
Error Details:
Error:An error occurred during simulation and the simulation was terminated
Caused by:
[‘Model_Name/Solver’]: Transient initialization at time 0.04421663720467431, solving for consistent states and modes, failed to converge.
Nonlinear solver: failed to converge, residual norm too large.
Here is the set of components with unconverged equations:
‘Model_Name/Current Limiter’
Equation location is:
‘/Applications/MATLAB_R2024a.app/toolbox/physmod/elec/library/m/+ee/+semiconductors/current_limiter_base.sscp'(no line number info)
What I Have Tried
Solver Configuration: I have tried using stiff solvers such as ode15s and ode23t, and adjusted the tolerances.
Initialization: Ensured that all initial conditions are set correctly for the battery, current limiter, and motor system.
Current Limiter Settings: Reviewed and adjusted the current limiter parameters to avoid abrupt changes.
Simulation Step Size: Reduced the step size to capture transient behaviors more accurately.
Zero-Crossing Detection: Enabled zero-crossing detection to handle state changes more smoothly.
Component Parameters: Verified that all component parameters are realistic and consistent.
Protective Measures: Tried introducing capacitors and resistors to smooth out voltage drops and dampen sudden changes.
Despite these efforts, the simulation still crashes. I believe the issue might be related to the current limiter’s interaction with the motor and drive system.
Reference Model
I am using the model configuration similar to the one available here: Battery Electric Vehicle with Motor Cooling in Simscape.
Request for Assistance
I am seeking advice on how to effectively limit the current to the motor and drive system without causing the simulation to crash. Any insights or suggestions on how to resolve this issue would be greatly appreciated.
Thank you in advance for your help!
Best regards, AlexHello MATLAB Community,
I am currently working on a Simscape model where a battery is connected to a current limiter and subsequently to a "motor and drive" system block. I am experiencing an issue where the simulation crashes as soon as the current limiter attempts to limit the current.
Error Details:
Error:An error occurred during simulation and the simulation was terminated
Caused by:
[‘Model_Name/Solver’]: Transient initialization at time 0.04421663720467431, solving for consistent states and modes, failed to converge.
Nonlinear solver: failed to converge, residual norm too large.
Here is the set of components with unconverged equations:
‘Model_Name/Current Limiter’
Equation location is:
‘/Applications/MATLAB_R2024a.app/toolbox/physmod/elec/library/m/+ee/+semiconductors/current_limiter_base.sscp'(no line number info)
What I Have Tried
Solver Configuration: I have tried using stiff solvers such as ode15s and ode23t, and adjusted the tolerances.
Initialization: Ensured that all initial conditions are set correctly for the battery, current limiter, and motor system.
Current Limiter Settings: Reviewed and adjusted the current limiter parameters to avoid abrupt changes.
Simulation Step Size: Reduced the step size to capture transient behaviors more accurately.
Zero-Crossing Detection: Enabled zero-crossing detection to handle state changes more smoothly.
Component Parameters: Verified that all component parameters are realistic and consistent.
Protective Measures: Tried introducing capacitors and resistors to smooth out voltage drops and dampen sudden changes.
Despite these efforts, the simulation still crashes. I believe the issue might be related to the current limiter’s interaction with the motor and drive system.
Reference Model
I am using the model configuration similar to the one available here: Battery Electric Vehicle with Motor Cooling in Simscape.
Request for Assistance
I am seeking advice on how to effectively limit the current to the motor and drive system without causing the simulation to crash. Any insights or suggestions on how to resolve this issue would be greatly appreciated.
Thank you in advance for your help!
Best regards, Alex Hello MATLAB Community,
I am currently working on a Simscape model where a battery is connected to a current limiter and subsequently to a "motor and drive" system block. I am experiencing an issue where the simulation crashes as soon as the current limiter attempts to limit the current.
Error Details:
Error:An error occurred during simulation and the simulation was terminated
Caused by:
[‘Model_Name/Solver’]: Transient initialization at time 0.04421663720467431, solving for consistent states and modes, failed to converge.
Nonlinear solver: failed to converge, residual norm too large.
Here is the set of components with unconverged equations:
‘Model_Name/Current Limiter’
Equation location is:
‘/Applications/MATLAB_R2024a.app/toolbox/physmod/elec/library/m/+ee/+semiconductors/current_limiter_base.sscp'(no line number info)
What I Have Tried
Solver Configuration: I have tried using stiff solvers such as ode15s and ode23t, and adjusted the tolerances.
Initialization: Ensured that all initial conditions are set correctly for the battery, current limiter, and motor system.
Current Limiter Settings: Reviewed and adjusted the current limiter parameters to avoid abrupt changes.
Simulation Step Size: Reduced the step size to capture transient behaviors more accurately.
Zero-Crossing Detection: Enabled zero-crossing detection to handle state changes more smoothly.
Component Parameters: Verified that all component parameters are realistic and consistent.
Protective Measures: Tried introducing capacitors and resistors to smooth out voltage drops and dampen sudden changes.
Despite these efforts, the simulation still crashes. I believe the issue might be related to the current limiter’s interaction with the motor and drive system.
Reference Model
I am using the model configuration similar to the one available here: Battery Electric Vehicle with Motor Cooling in Simscape.
Request for Assistance
I am seeking advice on how to effectively limit the current to the motor and drive system without causing the simulation to crash. Any insights or suggestions on how to resolve this issue would be greatly appreciated.
Thank you in advance for your help!
Best regards, Alex simscape, battery_system_management MATLAB Answers — New Questions