Category: Matlab
Category Archives: Matlab
How to resolve “license file selected seems to be invalid” error
Post Content Post Content license MATLAB Answers — New Questions
How can I communicate between a Pixhawk controller and an actuator module using UAVCAN?
I am now building a UAV whose controller is Pixhawk 4X or 6X.
UAVCAN communication is available to drive the main motors.
According to the following page, UAVCAN is used to read GPS data.
https://jp.mathworks.com/help/uav/px4/ref/read-gps-uavcan-example.html
However, I cannot find the detailed configuration of the UAVCAN.
Would you tell me how to use the UAVCAN communication using some blocks in UAV Toolbox Support Package for PX4 Autopilot such as "uORB Read" block?I am now building a UAV whose controller is Pixhawk 4X or 6X.
UAVCAN communication is available to drive the main motors.
According to the following page, UAVCAN is used to read GPS data.
https://jp.mathworks.com/help/uav/px4/ref/read-gps-uavcan-example.html
However, I cannot find the detailed configuration of the UAVCAN.
Would you tell me how to use the UAVCAN communication using some blocks in UAV Toolbox Support Package for PX4 Autopilot such as "uORB Read" block? I am now building a UAV whose controller is Pixhawk 4X or 6X.
UAVCAN communication is available to drive the main motors.
According to the following page, UAVCAN is used to read GPS data.
https://jp.mathworks.com/help/uav/px4/ref/read-gps-uavcan-example.html
However, I cannot find the detailed configuration of the UAVCAN.
Would you tell me how to use the UAVCAN communication using some blocks in UAV Toolbox Support Package for PX4 Autopilot such as "uORB Read" block? uavcan, uav toolbox support package, pixhawk MATLAB Answers — New Questions
Trajectory of a 3d body
Problem Statement: –
I have a 3d body which i have launched from cruising aircraft travelling at 200m/sec at 10km altitude. The launch speed is 50m/sec and it is launched at 45degrees angle pointing downwards. I want to create the whole trajectory of the body using everything like change in pressure, density, drag, lift etc. I created a code but it is not giving the accurate answer.
the code: –
function aircraft_launch_trajectory_6DOF_advanced()
% Constants
g = 9.81; % Acceleration due to gravity (m/s^2)
% Convert given units to SI
m = 49.964 * 0.0283495; % Mass (kg) (1 ouncemass = 0.0283495 kg)
A = 68.166 * 0.00064516; % Area (m^2) (1 in^2 = 0.00064516 m^2)
Izz = 19.58 * 0.0283495 * 0.0254^2; % Moment of inertia (kg*m^2)
% Body dimensions
length = 1.80 * 0.0254; % Length (m)
width = 3.30 * 0.0254; % Width (m)
height = 8.00 * 0.0254; % Height (m)
% Center of mass location (assuming from the base of the body)
cm_z = 1.708 * 0.0254; % (m)
% Assumed center of pressure location (you may need to adjust this)
cp_z = 4.5 * 0.0254; % (m)
% Distance between center of mass and center of pressure
d_cp_cm = cp_z – cm_z;
% Initial conditions
h0 = 10000; % Initial height (m)
v0_aircraft = 200; % Aircraft velocity (m/s)
v0_launch = 50; % Launch velocity (m/s)
angle = -45; % Launch angle (degrees)
omega0 = 0; % Initial angular velocity (rad/s)
% Calculate initial velocity components
v0x = v0_aircraft – v0_launch * cosd(angle);
v0y = -v0_launch * sind(angle);
% Initial state vector [x, y, vx, vy, theta, omega]
y0 = [0; h0; v0x; v0y; deg2rad(angle); omega0];
% Time settings
tspan = [0 300]; % Time span for integration
% ODE solver options
options = odeset(‘Events’, @ground_impact, ‘RelTol’, 1e-6, ‘AbsTol’, 1e-6);
% Solve ODE using ode45 (4th order Runge-Kutta)
[t, y] = ode45(@(t, y) equations_of_motion_6DOF_advanced(t, y, m, Izz, A, d_cp_cm, length), tspan, y0, options);
% Extract results
x = y(:, 1);
h = y(:, 2);
vx = y(:, 3);
vy = y(:, 4);
theta = y(:, 5);
omega = y(:, 6);
% Calculate velocity magnitude
v = sqrt(vx.^2 + vy.^2);
% Plot trajectory
figure;
plot(x/1000, h/1000);
xlabel(‘Horizontal distance (km)’);
ylabel(‘Altitude (km)’);
title(‘2D Trajectory of Body (Advanced 6DOF Simulation)’);
grid on;
% Plot velocity
figure;
plot(t, v);
xlabel(‘Time (s)’);
ylabel(‘Velocity (m/s)’);
title(‘Velocity vs Time’);
grid on;
% Plot angular position and velocity
figure;
subplot(2,1,1);
plot(t, rad2deg(theta));
ylabel(‘Angular Position (degrees)’);
title(‘Angular Motion’);
grid on;
subplot(2,1,2);
plot(t, rad2deg(omega));
xlabel(‘Time (s)’);
ylabel(‘Angular Velocity (deg/s)’);
grid on;
% Display results
disp([‘Time of flight: ‘, num2str(t(end)), ‘ s’]);
disp([‘Horizontal distance traveled: ‘, num2str(x(end)/1000), ‘ km’]);
disp([‘Impact velocity: ‘, num2str(v(end)), ‘ m/s’]);
disp([‘Final angle: ‘, num2str(rad2deg(theta(end))), ‘ degrees’]);
disp([‘Max altitude: ‘, num2str(max(h)/1000), ‘ km’]);
disp([‘Max velocity: ‘, num2str(max(v)), ‘ m/s’]);
% Output state at specific times for debugging
debug_times = [0, 5, 10, 30, 60, 120];
for debug_time = debug_times
idx = find(t >= debug_time, 1);
if ~isempty(idx)
disp([‘State at t = ‘, num2str(t(idx)), ‘ s:’]);
disp([‘ Position: (‘, num2str(x(idx)/1000), ‘ km, ‘, num2str(h(idx)/1000), ‘ km)’]);
disp([‘ Velocity: ‘, num2str(v(idx)), ‘ m/s’]);
disp([‘ Angle: ‘, num2str(rad2deg(theta(idx))), ‘ degrees’]);
end
end
end
function dydt = equations_of_motion_6DOF_advanced(t, y, m, Izz, A, d_cp_cm, length)
% Unpack state vector
x = y(1);
h = y(2);
vx = y(3);
vy = y(4);
theta = y(5);
omega = y(6);
% Calculate velocity magnitude and angle of attack
v = sqrt(vx^2 + vy^2);
alpha = atan2(vy, vx) – theta;
% Calculate air density and speed of sound using improved atmospheric model
[rho, a] = atmosphere_model(h);
% Calculate Mach number
M = v / a;
% Get aerodynamic coefficients based on angle of attack and Mach number
[Cd, Cl, Cm] = aero_coefficients(alpha, M);
% Calculate aerodynamic forces and moment
q = 0.5 * rho * v^2; % Dynamic pressure
Fd = q * Cd * A; % Drag force
Fl = q * Cl * A; % Lift force
M_aero = q * Cm * A * length; % Aerodynamic moment
% Add moment due to center of pressure offset
M_total = M_aero + Fl * d_cp_cm;
% Apply initial boost for first 7 seconds
boost_duration = 7; % seconds
if t <= boost_duration
boost_force = m * 200 / boost_duration; % Force to achieve 200 m/s in 7 seconds
boost_fx = boost_force * cos(theta);
boost_fy = boost_force * sin(theta);
else
boost_fx = 0;
boost_fy = 0;
end
% Calculate accelerations
ax = (-Fd * cos(theta) + Fl * sin(theta) + boost_fx) / m;
ay = -9.81 + (-Fd * sin(theta) – Fl * cos(theta) + boost_fy) / m;
alpha_dot = M_total / Izz; % Angular acceleration
% Return state derivatives
dydt = [vx; vy; ax; ay; omega; alpha_dot];
end
function [rho, a] = atmosphere_model(h)
% Constants
R = 287.05; % Specific gas constant for air (J/(kg*K))
g0 = 9.80665; % Standard gravity (m/s^2)
gamma = 1.4; % Ratio of specific heats for air
% Sea level conditions
T0 = 288.15; % Temperature at sea level (K)
P0 = 101325; % Pressure at sea level (Pa)
if h < 11000 % Troposphere
T = T0 – 0.0065 * h;
P = P0 * (T / T0)^(g0 / (R * 0.0065));
elseif h < 20000 % Lower Stratosphere
T = 216.65;
P = 22632.1 * exp(-g0 * (h – 11000) / (R * T));
else % Upper Stratosphere
T = 216.65 + 0.001 * (h – 20000);
P = 5474.89 * (216.65 / T)^(34.1632);
end
rho = P / (R * T);
a = sqrt(gamma * R * T); % Speed of sound
end
function [Cd, Cl, Cm] = aero_coefficients(alpha, M)
% This function returns aerodynamic coefficients based on angle of attack and Mach number
% Note: These are simplified models and should be replaced with actual data or more complex models
% Convert alpha to degrees for easier calculations
alpha_deg = rad2deg(alpha);
% Drag coefficient
Cd0 = 0.1 + 0.1 * M; % Base drag increases with Mach number
Cdi = 0.01 * alpha_deg^2; % Induced drag
Cd = Cd0 + Cdi;
% Lift coefficient
Cl_slope = 0.1; % Lift curve slope
Cl = Cl_slope * alpha_deg * (1 – M^2/4)^(-0.5); % Prandtl-Glauert correction for compressibility
% Moment coefficient
Cm0 = -0.05; % Zero-lift moment coefficient
Cm_alpha = -0.01; % Moment curve slope
Cm = Cm0 + Cm_alpha * alpha_deg;
% Limit coefficients to realistic ranges
Cd = max(0, min(Cd, 2));
Cl = max(-2, min(Cl, 2));
Cm = max(-1, min(Cm, 1));
end
function [position, isterminal, direction] = ground_impact(t, y)
position = y(2); % Height
isterminal = 1; % Stop integration when ground is reached
direction = -1; % Negative direction (approaching ground)
endProblem Statement: –
I have a 3d body which i have launched from cruising aircraft travelling at 200m/sec at 10km altitude. The launch speed is 50m/sec and it is launched at 45degrees angle pointing downwards. I want to create the whole trajectory of the body using everything like change in pressure, density, drag, lift etc. I created a code but it is not giving the accurate answer.
the code: –
function aircraft_launch_trajectory_6DOF_advanced()
% Constants
g = 9.81; % Acceleration due to gravity (m/s^2)
% Convert given units to SI
m = 49.964 * 0.0283495; % Mass (kg) (1 ouncemass = 0.0283495 kg)
A = 68.166 * 0.00064516; % Area (m^2) (1 in^2 = 0.00064516 m^2)
Izz = 19.58 * 0.0283495 * 0.0254^2; % Moment of inertia (kg*m^2)
% Body dimensions
length = 1.80 * 0.0254; % Length (m)
width = 3.30 * 0.0254; % Width (m)
height = 8.00 * 0.0254; % Height (m)
% Center of mass location (assuming from the base of the body)
cm_z = 1.708 * 0.0254; % (m)
% Assumed center of pressure location (you may need to adjust this)
cp_z = 4.5 * 0.0254; % (m)
% Distance between center of mass and center of pressure
d_cp_cm = cp_z – cm_z;
% Initial conditions
h0 = 10000; % Initial height (m)
v0_aircraft = 200; % Aircraft velocity (m/s)
v0_launch = 50; % Launch velocity (m/s)
angle = -45; % Launch angle (degrees)
omega0 = 0; % Initial angular velocity (rad/s)
% Calculate initial velocity components
v0x = v0_aircraft – v0_launch * cosd(angle);
v0y = -v0_launch * sind(angle);
% Initial state vector [x, y, vx, vy, theta, omega]
y0 = [0; h0; v0x; v0y; deg2rad(angle); omega0];
% Time settings
tspan = [0 300]; % Time span for integration
% ODE solver options
options = odeset(‘Events’, @ground_impact, ‘RelTol’, 1e-6, ‘AbsTol’, 1e-6);
% Solve ODE using ode45 (4th order Runge-Kutta)
[t, y] = ode45(@(t, y) equations_of_motion_6DOF_advanced(t, y, m, Izz, A, d_cp_cm, length), tspan, y0, options);
% Extract results
x = y(:, 1);
h = y(:, 2);
vx = y(:, 3);
vy = y(:, 4);
theta = y(:, 5);
omega = y(:, 6);
% Calculate velocity magnitude
v = sqrt(vx.^2 + vy.^2);
% Plot trajectory
figure;
plot(x/1000, h/1000);
xlabel(‘Horizontal distance (km)’);
ylabel(‘Altitude (km)’);
title(‘2D Trajectory of Body (Advanced 6DOF Simulation)’);
grid on;
% Plot velocity
figure;
plot(t, v);
xlabel(‘Time (s)’);
ylabel(‘Velocity (m/s)’);
title(‘Velocity vs Time’);
grid on;
% Plot angular position and velocity
figure;
subplot(2,1,1);
plot(t, rad2deg(theta));
ylabel(‘Angular Position (degrees)’);
title(‘Angular Motion’);
grid on;
subplot(2,1,2);
plot(t, rad2deg(omega));
xlabel(‘Time (s)’);
ylabel(‘Angular Velocity (deg/s)’);
grid on;
% Display results
disp([‘Time of flight: ‘, num2str(t(end)), ‘ s’]);
disp([‘Horizontal distance traveled: ‘, num2str(x(end)/1000), ‘ km’]);
disp([‘Impact velocity: ‘, num2str(v(end)), ‘ m/s’]);
disp([‘Final angle: ‘, num2str(rad2deg(theta(end))), ‘ degrees’]);
disp([‘Max altitude: ‘, num2str(max(h)/1000), ‘ km’]);
disp([‘Max velocity: ‘, num2str(max(v)), ‘ m/s’]);
% Output state at specific times for debugging
debug_times = [0, 5, 10, 30, 60, 120];
for debug_time = debug_times
idx = find(t >= debug_time, 1);
if ~isempty(idx)
disp([‘State at t = ‘, num2str(t(idx)), ‘ s:’]);
disp([‘ Position: (‘, num2str(x(idx)/1000), ‘ km, ‘, num2str(h(idx)/1000), ‘ km)’]);
disp([‘ Velocity: ‘, num2str(v(idx)), ‘ m/s’]);
disp([‘ Angle: ‘, num2str(rad2deg(theta(idx))), ‘ degrees’]);
end
end
end
function dydt = equations_of_motion_6DOF_advanced(t, y, m, Izz, A, d_cp_cm, length)
% Unpack state vector
x = y(1);
h = y(2);
vx = y(3);
vy = y(4);
theta = y(5);
omega = y(6);
% Calculate velocity magnitude and angle of attack
v = sqrt(vx^2 + vy^2);
alpha = atan2(vy, vx) – theta;
% Calculate air density and speed of sound using improved atmospheric model
[rho, a] = atmosphere_model(h);
% Calculate Mach number
M = v / a;
% Get aerodynamic coefficients based on angle of attack and Mach number
[Cd, Cl, Cm] = aero_coefficients(alpha, M);
% Calculate aerodynamic forces and moment
q = 0.5 * rho * v^2; % Dynamic pressure
Fd = q * Cd * A; % Drag force
Fl = q * Cl * A; % Lift force
M_aero = q * Cm * A * length; % Aerodynamic moment
% Add moment due to center of pressure offset
M_total = M_aero + Fl * d_cp_cm;
% Apply initial boost for first 7 seconds
boost_duration = 7; % seconds
if t <= boost_duration
boost_force = m * 200 / boost_duration; % Force to achieve 200 m/s in 7 seconds
boost_fx = boost_force * cos(theta);
boost_fy = boost_force * sin(theta);
else
boost_fx = 0;
boost_fy = 0;
end
% Calculate accelerations
ax = (-Fd * cos(theta) + Fl * sin(theta) + boost_fx) / m;
ay = -9.81 + (-Fd * sin(theta) – Fl * cos(theta) + boost_fy) / m;
alpha_dot = M_total / Izz; % Angular acceleration
% Return state derivatives
dydt = [vx; vy; ax; ay; omega; alpha_dot];
end
function [rho, a] = atmosphere_model(h)
% Constants
R = 287.05; % Specific gas constant for air (J/(kg*K))
g0 = 9.80665; % Standard gravity (m/s^2)
gamma = 1.4; % Ratio of specific heats for air
% Sea level conditions
T0 = 288.15; % Temperature at sea level (K)
P0 = 101325; % Pressure at sea level (Pa)
if h < 11000 % Troposphere
T = T0 – 0.0065 * h;
P = P0 * (T / T0)^(g0 / (R * 0.0065));
elseif h < 20000 % Lower Stratosphere
T = 216.65;
P = 22632.1 * exp(-g0 * (h – 11000) / (R * T));
else % Upper Stratosphere
T = 216.65 + 0.001 * (h – 20000);
P = 5474.89 * (216.65 / T)^(34.1632);
end
rho = P / (R * T);
a = sqrt(gamma * R * T); % Speed of sound
end
function [Cd, Cl, Cm] = aero_coefficients(alpha, M)
% This function returns aerodynamic coefficients based on angle of attack and Mach number
% Note: These are simplified models and should be replaced with actual data or more complex models
% Convert alpha to degrees for easier calculations
alpha_deg = rad2deg(alpha);
% Drag coefficient
Cd0 = 0.1 + 0.1 * M; % Base drag increases with Mach number
Cdi = 0.01 * alpha_deg^2; % Induced drag
Cd = Cd0 + Cdi;
% Lift coefficient
Cl_slope = 0.1; % Lift curve slope
Cl = Cl_slope * alpha_deg * (1 – M^2/4)^(-0.5); % Prandtl-Glauert correction for compressibility
% Moment coefficient
Cm0 = -0.05; % Zero-lift moment coefficient
Cm_alpha = -0.01; % Moment curve slope
Cm = Cm0 + Cm_alpha * alpha_deg;
% Limit coefficients to realistic ranges
Cd = max(0, min(Cd, 2));
Cl = max(-2, min(Cl, 2));
Cm = max(-1, min(Cm, 1));
end
function [position, isterminal, direction] = ground_impact(t, y)
position = y(2); % Height
isterminal = 1; % Stop integration when ground is reached
direction = -1; % Negative direction (approaching ground)
end Problem Statement: –
I have a 3d body which i have launched from cruising aircraft travelling at 200m/sec at 10km altitude. The launch speed is 50m/sec and it is launched at 45degrees angle pointing downwards. I want to create the whole trajectory of the body using everything like change in pressure, density, drag, lift etc. I created a code but it is not giving the accurate answer.
the code: –
function aircraft_launch_trajectory_6DOF_advanced()
% Constants
g = 9.81; % Acceleration due to gravity (m/s^2)
% Convert given units to SI
m = 49.964 * 0.0283495; % Mass (kg) (1 ouncemass = 0.0283495 kg)
A = 68.166 * 0.00064516; % Area (m^2) (1 in^2 = 0.00064516 m^2)
Izz = 19.58 * 0.0283495 * 0.0254^2; % Moment of inertia (kg*m^2)
% Body dimensions
length = 1.80 * 0.0254; % Length (m)
width = 3.30 * 0.0254; % Width (m)
height = 8.00 * 0.0254; % Height (m)
% Center of mass location (assuming from the base of the body)
cm_z = 1.708 * 0.0254; % (m)
% Assumed center of pressure location (you may need to adjust this)
cp_z = 4.5 * 0.0254; % (m)
% Distance between center of mass and center of pressure
d_cp_cm = cp_z – cm_z;
% Initial conditions
h0 = 10000; % Initial height (m)
v0_aircraft = 200; % Aircraft velocity (m/s)
v0_launch = 50; % Launch velocity (m/s)
angle = -45; % Launch angle (degrees)
omega0 = 0; % Initial angular velocity (rad/s)
% Calculate initial velocity components
v0x = v0_aircraft – v0_launch * cosd(angle);
v0y = -v0_launch * sind(angle);
% Initial state vector [x, y, vx, vy, theta, omega]
y0 = [0; h0; v0x; v0y; deg2rad(angle); omega0];
% Time settings
tspan = [0 300]; % Time span for integration
% ODE solver options
options = odeset(‘Events’, @ground_impact, ‘RelTol’, 1e-6, ‘AbsTol’, 1e-6);
% Solve ODE using ode45 (4th order Runge-Kutta)
[t, y] = ode45(@(t, y) equations_of_motion_6DOF_advanced(t, y, m, Izz, A, d_cp_cm, length), tspan, y0, options);
% Extract results
x = y(:, 1);
h = y(:, 2);
vx = y(:, 3);
vy = y(:, 4);
theta = y(:, 5);
omega = y(:, 6);
% Calculate velocity magnitude
v = sqrt(vx.^2 + vy.^2);
% Plot trajectory
figure;
plot(x/1000, h/1000);
xlabel(‘Horizontal distance (km)’);
ylabel(‘Altitude (km)’);
title(‘2D Trajectory of Body (Advanced 6DOF Simulation)’);
grid on;
% Plot velocity
figure;
plot(t, v);
xlabel(‘Time (s)’);
ylabel(‘Velocity (m/s)’);
title(‘Velocity vs Time’);
grid on;
% Plot angular position and velocity
figure;
subplot(2,1,1);
plot(t, rad2deg(theta));
ylabel(‘Angular Position (degrees)’);
title(‘Angular Motion’);
grid on;
subplot(2,1,2);
plot(t, rad2deg(omega));
xlabel(‘Time (s)’);
ylabel(‘Angular Velocity (deg/s)’);
grid on;
% Display results
disp([‘Time of flight: ‘, num2str(t(end)), ‘ s’]);
disp([‘Horizontal distance traveled: ‘, num2str(x(end)/1000), ‘ km’]);
disp([‘Impact velocity: ‘, num2str(v(end)), ‘ m/s’]);
disp([‘Final angle: ‘, num2str(rad2deg(theta(end))), ‘ degrees’]);
disp([‘Max altitude: ‘, num2str(max(h)/1000), ‘ km’]);
disp([‘Max velocity: ‘, num2str(max(v)), ‘ m/s’]);
% Output state at specific times for debugging
debug_times = [0, 5, 10, 30, 60, 120];
for debug_time = debug_times
idx = find(t >= debug_time, 1);
if ~isempty(idx)
disp([‘State at t = ‘, num2str(t(idx)), ‘ s:’]);
disp([‘ Position: (‘, num2str(x(idx)/1000), ‘ km, ‘, num2str(h(idx)/1000), ‘ km)’]);
disp([‘ Velocity: ‘, num2str(v(idx)), ‘ m/s’]);
disp([‘ Angle: ‘, num2str(rad2deg(theta(idx))), ‘ degrees’]);
end
end
end
function dydt = equations_of_motion_6DOF_advanced(t, y, m, Izz, A, d_cp_cm, length)
% Unpack state vector
x = y(1);
h = y(2);
vx = y(3);
vy = y(4);
theta = y(5);
omega = y(6);
% Calculate velocity magnitude and angle of attack
v = sqrt(vx^2 + vy^2);
alpha = atan2(vy, vx) – theta;
% Calculate air density and speed of sound using improved atmospheric model
[rho, a] = atmosphere_model(h);
% Calculate Mach number
M = v / a;
% Get aerodynamic coefficients based on angle of attack and Mach number
[Cd, Cl, Cm] = aero_coefficients(alpha, M);
% Calculate aerodynamic forces and moment
q = 0.5 * rho * v^2; % Dynamic pressure
Fd = q * Cd * A; % Drag force
Fl = q * Cl * A; % Lift force
M_aero = q * Cm * A * length; % Aerodynamic moment
% Add moment due to center of pressure offset
M_total = M_aero + Fl * d_cp_cm;
% Apply initial boost for first 7 seconds
boost_duration = 7; % seconds
if t <= boost_duration
boost_force = m * 200 / boost_duration; % Force to achieve 200 m/s in 7 seconds
boost_fx = boost_force * cos(theta);
boost_fy = boost_force * sin(theta);
else
boost_fx = 0;
boost_fy = 0;
end
% Calculate accelerations
ax = (-Fd * cos(theta) + Fl * sin(theta) + boost_fx) / m;
ay = -9.81 + (-Fd * sin(theta) – Fl * cos(theta) + boost_fy) / m;
alpha_dot = M_total / Izz; % Angular acceleration
% Return state derivatives
dydt = [vx; vy; ax; ay; omega; alpha_dot];
end
function [rho, a] = atmosphere_model(h)
% Constants
R = 287.05; % Specific gas constant for air (J/(kg*K))
g0 = 9.80665; % Standard gravity (m/s^2)
gamma = 1.4; % Ratio of specific heats for air
% Sea level conditions
T0 = 288.15; % Temperature at sea level (K)
P0 = 101325; % Pressure at sea level (Pa)
if h < 11000 % Troposphere
T = T0 – 0.0065 * h;
P = P0 * (T / T0)^(g0 / (R * 0.0065));
elseif h < 20000 % Lower Stratosphere
T = 216.65;
P = 22632.1 * exp(-g0 * (h – 11000) / (R * T));
else % Upper Stratosphere
T = 216.65 + 0.001 * (h – 20000);
P = 5474.89 * (216.65 / T)^(34.1632);
end
rho = P / (R * T);
a = sqrt(gamma * R * T); % Speed of sound
end
function [Cd, Cl, Cm] = aero_coefficients(alpha, M)
% This function returns aerodynamic coefficients based on angle of attack and Mach number
% Note: These are simplified models and should be replaced with actual data or more complex models
% Convert alpha to degrees for easier calculations
alpha_deg = rad2deg(alpha);
% Drag coefficient
Cd0 = 0.1 + 0.1 * M; % Base drag increases with Mach number
Cdi = 0.01 * alpha_deg^2; % Induced drag
Cd = Cd0 + Cdi;
% Lift coefficient
Cl_slope = 0.1; % Lift curve slope
Cl = Cl_slope * alpha_deg * (1 – M^2/4)^(-0.5); % Prandtl-Glauert correction for compressibility
% Moment coefficient
Cm0 = -0.05; % Zero-lift moment coefficient
Cm_alpha = -0.01; % Moment curve slope
Cm = Cm0 + Cm_alpha * alpha_deg;
% Limit coefficients to realistic ranges
Cd = max(0, min(Cd, 2));
Cl = max(-2, min(Cl, 2));
Cm = max(-1, min(Cm, 1));
end
function [position, isterminal, direction] = ground_impact(t, y)
position = y(2); % Height
isterminal = 1; % Stop integration when ground is reached
direction = -1; % Negative direction (approaching ground)
end trajectory, aerospace MATLAB Answers — New Questions
Initial position detection of sensor less BLDC motor drive
my research is sensor less speed control of BLDC motor drive, it’s possible to detect ZCD of line voltage. but initial starting speed zero time cont detect ZCD points, if start open loop v/f mean rotor will rotate wrong direction at initial.
any body help me to detect the initial rotor position detection and speed control starting correct direction of sensor less speed control of BLDC motor drive?
if you able pls contact me..
thank you,
Reg,
R.Manikandan,M.E.,(Ph.D).,
AP / Department of EEE,
The Kavery Engineering College,
Mecheri (po), Salem(dt), pin:636453
Tamil Nadu, India.
Cell: 9944270473
Email: electricmani@yahoo.co.inmy research is sensor less speed control of BLDC motor drive, it’s possible to detect ZCD of line voltage. but initial starting speed zero time cont detect ZCD points, if start open loop v/f mean rotor will rotate wrong direction at initial.
any body help me to detect the initial rotor position detection and speed control starting correct direction of sensor less speed control of BLDC motor drive?
if you able pls contact me..
thank you,
Reg,
R.Manikandan,M.E.,(Ph.D).,
AP / Department of EEE,
The Kavery Engineering College,
Mecheri (po), Salem(dt), pin:636453
Tamil Nadu, India.
Cell: 9944270473
Email: electricmani@yahoo.co.in my research is sensor less speed control of BLDC motor drive, it’s possible to detect ZCD of line voltage. but initial starting speed zero time cont detect ZCD points, if start open loop v/f mean rotor will rotate wrong direction at initial.
any body help me to detect the initial rotor position detection and speed control starting correct direction of sensor less speed control of BLDC motor drive?
if you able pls contact me..
thank you,
Reg,
R.Manikandan,M.E.,(Ph.D).,
AP / Department of EEE,
The Kavery Engineering College,
Mecheri (po), Salem(dt), pin:636453
Tamil Nadu, India.
Cell: 9944270473
Email: electricmani@yahoo.co.in bldc, simpowersystems, sensor less drive, power_electronics_control, electric_motor_control MATLAB Answers — New Questions
How to do feature extraction using wavelet scattering and then perform neural network classification?
% I want to do feature extraction for signals and then apply ANN classification on them,, can you help please?
Fs = 50;
sf = waveletScattering(‘SignalLength’, 4950, ‘SamplingFrequency’, Fs) ;
s = cell(120,1);
parfor j = 1:120;
r = featureMatrix(sf, f(j, :)) ;
s{j, 1} = r;
end
h = cell2mat(s) ;
b = cell2table(s) ;
c = table2dataset(b);
%the single signal was in one row, but after this it becomes 202rows×10columns, and I can’t apply ANN like this
Any ideas?% I want to do feature extraction for signals and then apply ANN classification on them,, can you help please?
Fs = 50;
sf = waveletScattering(‘SignalLength’, 4950, ‘SamplingFrequency’, Fs) ;
s = cell(120,1);
parfor j = 1:120;
r = featureMatrix(sf, f(j, :)) ;
s{j, 1} = r;
end
h = cell2mat(s) ;
b = cell2table(s) ;
c = table2dataset(b);
%the single signal was in one row, but after this it becomes 202rows×10columns, and I can’t apply ANN like this
Any ideas? % I want to do feature extraction for signals and then apply ANN classification on them,, can you help please?
Fs = 50;
sf = waveletScattering(‘SignalLength’, 4950, ‘SamplingFrequency’, Fs) ;
s = cell(120,1);
parfor j = 1:120;
r = featureMatrix(sf, f(j, :)) ;
s{j, 1} = r;
end
h = cell2mat(s) ;
b = cell2table(s) ;
c = table2dataset(b);
%the single signal was in one row, but after this it becomes 202rows×10columns, and I can’t apply ANN like this
Any ideas? feature extraction, neural network, classification, wavelet, wavelet scattering, ecg signals, ecg recognition, ecg as signature, deep learning, machine learning MATLAB Answers — New Questions
Explore DFT Resolution, need help with answer interpretation
Hello there, I’m relatively new to Matlab and Digital Signal Processing. I’m trying to analyze the frequency resolution of the DFT as a function of the DFT size assuming a rectangular window. Using the a sum of sinusoids sampled at 5 kHz vary the frequency spacing
of the sinusoids to show the frequency resolution for at least 4 different DFT lengths, 256, 512, 1024, and 4096.
I got two versions of code from chatgpt. But I don’t know how to interpret them.
1st version
% MATLAB code to analyze the frequency resolution of the DFT using dftmtx and a rectangular window
fs = 5000; % Sampling frequency (5 kHz)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% DFT sizes to analyze
N_dft = [256, 512, 1024, 4096];
% Frequencies of the sum of sinusoids (vary frequency spacing)
f1 = 1000; % Frequency of the first sinusoid (1 kHz)
f_spacing = [1, 5, 10, 20]; % Frequency spacing between the two sinusoids
f_end = f1 + f_spacing; % Frequency of the second sinusoid
% Prepare figure
figure;
hold on;
for N = N_dft
figure; % Create a new figure for each DFT size
hold on;
for spacing = f_spacing
f2 = f1 + spacing; % Second sinusoid frequency
% Generate the sum of two sinusoids with frequencies f1 and f2
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
% Apply rectangular window (by taking the first N samples)
x_windowed = x(1:N); % Select the first N samples for DFT calculation
% Generate DFT matrix for size N using dftmtx
DFT_matrix = dftmtx(N);
% Manually compute the DFT using the DFT matrix
X = DFT_matrix * x_windowed(:); % Compute DFT of the windowed signal
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Plot the magnitude of the DFT
plot(freq_axis, abs(X), ‘DisplayName’, [‘Spacing = ‘, num2str(spacing), ‘ Hz’]);
end
% Add labels and legend
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title([‘DFT Magnitude Spectrum (N = ‘, num2str(N), ‘)’]);
legend(‘show’);
grid on;
hold off;
end
which gives me these resulted figures.
All the peaks are so similar that I can’t distinguish them at all.
2nd version of code is here:
% Parameters
fs = 5000; % Sampling frequency (Hz)
T = 1; % Signal duration (seconds)
t = 0:1/fs:T-1/fs; % Time vector
% Sinusoids: Frequencies and amplitudes
f1 = 400; % Frequency of first sinusoid (Hz)
f2 = 450; % Frequency of second sinusoid (Hz)
f3 = 500; % Frequency of third sinusoid (Hz)
% Create the signal: sum of three sinusoids
x = sin(2*pi*f1*t) + sin(2*pi*f2*t) + sin(2*pi*f3*t);
% Define DFT lengths
DFT_lengths = [256, 512, 1024, 4096];
% Plot frequency resolution for each DFT length using a rectangular window
figure;
for i = 1:length(DFT_lengths)
N = DFT_lengths(i); % DFT size
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
% Manually compute the DFT
% Compute the N-point DFT
X = (dftmtx(N)*x_windowed(:)).’; % Compute the N-point DFT
X_mag = abs(X); % Magnitude of DFT
% Frequency vector
f = (0:N-1) * (fs / N);
% Plot the DFT magnitude (first half)
subplot(length(DFT_lengths), 1, i);
plot(f(1:N/2), X_mag(1:N/2));
title([‘DFT Magnitude Spectrum with Rectangular Window, N = ‘, num2str(N)]);
xlabel(‘Frequency (Hz)’);
ylabel(‘|X(f)|’);
grid on;
end
% Adjust plot layout
sgtitle(‘Frequency Resolution for Different DFT Sizes Using Rectangular Window’);
%Part 5
% MATLAB code to analyze zero-padding in the DFT using a rectangular window
fs = 5000; % Sampling frequency (5 kHz)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% Window sizes to analyze
window_sizes = [256, 512];
% Zero-padded DFT sizes to analyze
N_dft = [1024, 2048, 4096];
% Frequencies of the sum of sinusoids (vary frequency spacing)
f1 = 1000; % Frequency of the first sinusoid (1 kHz)
f_spacing = [5, 10]; % Frequency spacing between the two sinusoids
f_end = f1 + f_spacing; % Frequency of the second sinusoid
% Prepare figure
for window_size = window_sizes
figure; % Create a new figure for each window size
hold on;
for N = N_dft
for spacing = f_spacing
f2 = f1 + spacing; % Second sinusoid frequency
% Generate the sum of two sinusoids with frequencies f1 and f2
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
% Apply rectangular window (by taking the first window_size samples)
x_windowed = x(1:window_size); % Select the first window_size samples
% Zero-pad the signal if DFT size is larger than window size
x_padded = [x_windowed, zeros(1, N – window_size)];
% Generate DFT matrix for size N using dftmtx
DFT_matrix = dftmtx(N);
% Manually compute the DFT using the DFT matrix
X = DFT_matrix * x_padded(:); % Compute DFT of the windowed and zero-padded signal
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Plot the magnitude of the DFT
plot(freq_axis, abs(X), ‘DisplayName’, [‘Spacing = ‘, num2str(spacing), ‘ Hz, N = ‘, num2str(N)]);
end
end
% Add labels and legend
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title([‘Zero-Padded DFT Magnitude Spectrum (Window Size = ‘, num2str(window_size), ‘)’]);
legend(‘show’);
grid on;
hold off;
end
with the second version of code I can see the differences among different sample sizes, as more sampling yields more sharp signals, but why is that and what differences it will make?Hello there, I’m relatively new to Matlab and Digital Signal Processing. I’m trying to analyze the frequency resolution of the DFT as a function of the DFT size assuming a rectangular window. Using the a sum of sinusoids sampled at 5 kHz vary the frequency spacing
of the sinusoids to show the frequency resolution for at least 4 different DFT lengths, 256, 512, 1024, and 4096.
I got two versions of code from chatgpt. But I don’t know how to interpret them.
1st version
% MATLAB code to analyze the frequency resolution of the DFT using dftmtx and a rectangular window
fs = 5000; % Sampling frequency (5 kHz)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% DFT sizes to analyze
N_dft = [256, 512, 1024, 4096];
% Frequencies of the sum of sinusoids (vary frequency spacing)
f1 = 1000; % Frequency of the first sinusoid (1 kHz)
f_spacing = [1, 5, 10, 20]; % Frequency spacing between the two sinusoids
f_end = f1 + f_spacing; % Frequency of the second sinusoid
% Prepare figure
figure;
hold on;
for N = N_dft
figure; % Create a new figure for each DFT size
hold on;
for spacing = f_spacing
f2 = f1 + spacing; % Second sinusoid frequency
% Generate the sum of two sinusoids with frequencies f1 and f2
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
% Apply rectangular window (by taking the first N samples)
x_windowed = x(1:N); % Select the first N samples for DFT calculation
% Generate DFT matrix for size N using dftmtx
DFT_matrix = dftmtx(N);
% Manually compute the DFT using the DFT matrix
X = DFT_matrix * x_windowed(:); % Compute DFT of the windowed signal
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Plot the magnitude of the DFT
plot(freq_axis, abs(X), ‘DisplayName’, [‘Spacing = ‘, num2str(spacing), ‘ Hz’]);
end
% Add labels and legend
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title([‘DFT Magnitude Spectrum (N = ‘, num2str(N), ‘)’]);
legend(‘show’);
grid on;
hold off;
end
which gives me these resulted figures.
All the peaks are so similar that I can’t distinguish them at all.
2nd version of code is here:
% Parameters
fs = 5000; % Sampling frequency (Hz)
T = 1; % Signal duration (seconds)
t = 0:1/fs:T-1/fs; % Time vector
% Sinusoids: Frequencies and amplitudes
f1 = 400; % Frequency of first sinusoid (Hz)
f2 = 450; % Frequency of second sinusoid (Hz)
f3 = 500; % Frequency of third sinusoid (Hz)
% Create the signal: sum of three sinusoids
x = sin(2*pi*f1*t) + sin(2*pi*f2*t) + sin(2*pi*f3*t);
% Define DFT lengths
DFT_lengths = [256, 512, 1024, 4096];
% Plot frequency resolution for each DFT length using a rectangular window
figure;
for i = 1:length(DFT_lengths)
N = DFT_lengths(i); % DFT size
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
% Manually compute the DFT
% Compute the N-point DFT
X = (dftmtx(N)*x_windowed(:)).’; % Compute the N-point DFT
X_mag = abs(X); % Magnitude of DFT
% Frequency vector
f = (0:N-1) * (fs / N);
% Plot the DFT magnitude (first half)
subplot(length(DFT_lengths), 1, i);
plot(f(1:N/2), X_mag(1:N/2));
title([‘DFT Magnitude Spectrum with Rectangular Window, N = ‘, num2str(N)]);
xlabel(‘Frequency (Hz)’);
ylabel(‘|X(f)|’);
grid on;
end
% Adjust plot layout
sgtitle(‘Frequency Resolution for Different DFT Sizes Using Rectangular Window’);
%Part 5
% MATLAB code to analyze zero-padding in the DFT using a rectangular window
fs = 5000; % Sampling frequency (5 kHz)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% Window sizes to analyze
window_sizes = [256, 512];
% Zero-padded DFT sizes to analyze
N_dft = [1024, 2048, 4096];
% Frequencies of the sum of sinusoids (vary frequency spacing)
f1 = 1000; % Frequency of the first sinusoid (1 kHz)
f_spacing = [5, 10]; % Frequency spacing between the two sinusoids
f_end = f1 + f_spacing; % Frequency of the second sinusoid
% Prepare figure
for window_size = window_sizes
figure; % Create a new figure for each window size
hold on;
for N = N_dft
for spacing = f_spacing
f2 = f1 + spacing; % Second sinusoid frequency
% Generate the sum of two sinusoids with frequencies f1 and f2
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
% Apply rectangular window (by taking the first window_size samples)
x_windowed = x(1:window_size); % Select the first window_size samples
% Zero-pad the signal if DFT size is larger than window size
x_padded = [x_windowed, zeros(1, N – window_size)];
% Generate DFT matrix for size N using dftmtx
DFT_matrix = dftmtx(N);
% Manually compute the DFT using the DFT matrix
X = DFT_matrix * x_padded(:); % Compute DFT of the windowed and zero-padded signal
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Plot the magnitude of the DFT
plot(freq_axis, abs(X), ‘DisplayName’, [‘Spacing = ‘, num2str(spacing), ‘ Hz, N = ‘, num2str(N)]);
end
end
% Add labels and legend
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title([‘Zero-Padded DFT Magnitude Spectrum (Window Size = ‘, num2str(window_size), ‘)’]);
legend(‘show’);
grid on;
hold off;
end
with the second version of code I can see the differences among different sample sizes, as more sampling yields more sharp signals, but why is that and what differences it will make? Hello there, I’m relatively new to Matlab and Digital Signal Processing. I’m trying to analyze the frequency resolution of the DFT as a function of the DFT size assuming a rectangular window. Using the a sum of sinusoids sampled at 5 kHz vary the frequency spacing
of the sinusoids to show the frequency resolution for at least 4 different DFT lengths, 256, 512, 1024, and 4096.
I got two versions of code from chatgpt. But I don’t know how to interpret them.
1st version
% MATLAB code to analyze the frequency resolution of the DFT using dftmtx and a rectangular window
fs = 5000; % Sampling frequency (5 kHz)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% DFT sizes to analyze
N_dft = [256, 512, 1024, 4096];
% Frequencies of the sum of sinusoids (vary frequency spacing)
f1 = 1000; % Frequency of the first sinusoid (1 kHz)
f_spacing = [1, 5, 10, 20]; % Frequency spacing between the two sinusoids
f_end = f1 + f_spacing; % Frequency of the second sinusoid
% Prepare figure
figure;
hold on;
for N = N_dft
figure; % Create a new figure for each DFT size
hold on;
for spacing = f_spacing
f2 = f1 + spacing; % Second sinusoid frequency
% Generate the sum of two sinusoids with frequencies f1 and f2
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
% Apply rectangular window (by taking the first N samples)
x_windowed = x(1:N); % Select the first N samples for DFT calculation
% Generate DFT matrix for size N using dftmtx
DFT_matrix = dftmtx(N);
% Manually compute the DFT using the DFT matrix
X = DFT_matrix * x_windowed(:); % Compute DFT of the windowed signal
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Plot the magnitude of the DFT
plot(freq_axis, abs(X), ‘DisplayName’, [‘Spacing = ‘, num2str(spacing), ‘ Hz’]);
end
% Add labels and legend
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title([‘DFT Magnitude Spectrum (N = ‘, num2str(N), ‘)’]);
legend(‘show’);
grid on;
hold off;
end
which gives me these resulted figures.
All the peaks are so similar that I can’t distinguish them at all.
2nd version of code is here:
% Parameters
fs = 5000; % Sampling frequency (Hz)
T = 1; % Signal duration (seconds)
t = 0:1/fs:T-1/fs; % Time vector
% Sinusoids: Frequencies and amplitudes
f1 = 400; % Frequency of first sinusoid (Hz)
f2 = 450; % Frequency of second sinusoid (Hz)
f3 = 500; % Frequency of third sinusoid (Hz)
% Create the signal: sum of three sinusoids
x = sin(2*pi*f1*t) + sin(2*pi*f2*t) + sin(2*pi*f3*t);
% Define DFT lengths
DFT_lengths = [256, 512, 1024, 4096];
% Plot frequency resolution for each DFT length using a rectangular window
figure;
for i = 1:length(DFT_lengths)
N = DFT_lengths(i); % DFT size
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
% Manually compute the DFT
% Compute the N-point DFT
X = (dftmtx(N)*x_windowed(:)).’; % Compute the N-point DFT
X_mag = abs(X); % Magnitude of DFT
% Frequency vector
f = (0:N-1) * (fs / N);
% Plot the DFT magnitude (first half)
subplot(length(DFT_lengths), 1, i);
plot(f(1:N/2), X_mag(1:N/2));
title([‘DFT Magnitude Spectrum with Rectangular Window, N = ‘, num2str(N)]);
xlabel(‘Frequency (Hz)’);
ylabel(‘|X(f)|’);
grid on;
end
% Adjust plot layout
sgtitle(‘Frequency Resolution for Different DFT Sizes Using Rectangular Window’);
%Part 5
% MATLAB code to analyze zero-padding in the DFT using a rectangular window
fs = 5000; % Sampling frequency (5 kHz)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% Window sizes to analyze
window_sizes = [256, 512];
% Zero-padded DFT sizes to analyze
N_dft = [1024, 2048, 4096];
% Frequencies of the sum of sinusoids (vary frequency spacing)
f1 = 1000; % Frequency of the first sinusoid (1 kHz)
f_spacing = [5, 10]; % Frequency spacing between the two sinusoids
f_end = f1 + f_spacing; % Frequency of the second sinusoid
% Prepare figure
for window_size = window_sizes
figure; % Create a new figure for each window size
hold on;
for N = N_dft
for spacing = f_spacing
f2 = f1 + spacing; % Second sinusoid frequency
% Generate the sum of two sinusoids with frequencies f1 and f2
x = sin(2*pi*f1*t) + sin(2*pi*f2*t);
% Apply rectangular window (by taking the first window_size samples)
x_windowed = x(1:window_size); % Select the first window_size samples
% Zero-pad the signal if DFT size is larger than window size
x_padded = [x_windowed, zeros(1, N – window_size)];
% Generate DFT matrix for size N using dftmtx
DFT_matrix = dftmtx(N);
% Manually compute the DFT using the DFT matrix
X = DFT_matrix * x_padded(:); % Compute DFT of the windowed and zero-padded signal
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Plot the magnitude of the DFT
plot(freq_axis, abs(X), ‘DisplayName’, [‘Spacing = ‘, num2str(spacing), ‘ Hz, N = ‘, num2str(N)]);
end
end
% Add labels and legend
xlabel(‘Frequency (Hz)’);
ylabel(‘Magnitude’);
title([‘Zero-Padded DFT Magnitude Spectrum (Window Size = ‘, num2str(window_size), ‘)’]);
legend(‘show’);
grid on;
hold off;
end
with the second version of code I can see the differences among different sample sizes, as more sampling yields more sharp signals, but why is that and what differences it will make? dft, frequency resolution, digital signal processing, matlab MATLAB Answers — New Questions
How to find the sensitivity of the model output if it is a variable for repeated assignment?
Hi,
I want to find the sensitivity of model output which is a tissue mass for models parameters. I received an red flag that I can’t do that for repeaded variable.
How can I handle that?
Thank you.Hi,
I want to find the sensitivity of model output which is a tissue mass for models parameters. I received an red flag that I can’t do that for repeaded variable.
How can I handle that?
Thank you. Hi,
I want to find the sensitivity of model output which is a tissue mass for models parameters. I received an red flag that I can’t do that for repeaded variable.
How can I handle that?
Thank you. sensitivity MATLAB Answers — New Questions
Error using delaunayTriangulation when calling mesh() on a pcbStack
Hi! this is the first time I ask a question here I hope im doing everthing right. Well, I’m trying to simulate the EH fields of a 2 layer pcb coil, I import the files and make the pcbStack with the following code:
P = gerberRead("gerber/6L_planar_transformerv3-F_Cu.gbr", …
"gerber/6L_planar_transformerv3-In1_Cu.gbr", …
"gerber/6L_planar_transformerv3-PTH.drl");
pb2 = pcbStack(P);
f_cu=pb2.Layers{2};
in1_cu=pb2.Layers{4};
p = pcbStack;
p.BoardThickness=0.203e-3*1+1e-3;
p.ViaDiameter=0.1e-3;
d1 = dielectric("FR4");
d1.Thickness = 0.203e-3;
air = dielectric("Air");
air.Thickness = 1e-3;
p.BoardShape = antenna.Rectangle(Length=60e-3, Width=60e-3,Center=[0.1187 -0.0775]);
%p.Layers = {f_cu,d1,in1_cu,d1,in2_cu,d1,in3_cu,d1,d1,in4_cu,d1,b_cu};
p.Layers={air,f_cu,d1,in1_cu,air}
p.FeedDiameter = 0.1e-3;
p.FeedLocations = [146.1e-3 -72e-3 2;]
p.ViaLocations = [143e-3 -77.5e-3 2 4;
117.5e-3 -77.5e-3 2 4]
show(p)
The reason I’m importing the pcbStack like that is that I’m planning on simulating a planar transformer EH fields and the gerberRead() only allows for 2 layered pcb, this way i can add more layers by importing more gerber files. However when I run
mesh(p)
After some 20 minutes of the program running, it returns the following errors:
Error using delaunayTriangulation
Enforcing Delaunay constraints leads to unstable repeated constraint intersections.
This may be due to near coincident intersecting constraints or near duplicate points.
Error in em.internal.meshprinting.inter6_full_mesh
Error in em.internal.meshprinting.multiLayerMetalImprint
Error in em.PCBStructures/generateMeshForStripFeedAndVia
Error in pcbStack/meshGenerator (line 1340)
Mesh = generateMeshForStripFeedAndVia(obj,mesherInput);
Error in em.MeshGeometry/updateMeshForPcbStack
Error in em.MeshGeometry/protectedmesh
Error in em.MeshGeometryAnalysis/mesh (line 66)
protectedmesh(obj,varargin{:});
And since some functions of the RF toolbox like current() EHFields() first call mesh() I cant run simulations of my design. I don’t know if the size could be the reason of the delaunayTriangulation failure or something is wrong with my setupHi! this is the first time I ask a question here I hope im doing everthing right. Well, I’m trying to simulate the EH fields of a 2 layer pcb coil, I import the files and make the pcbStack with the following code:
P = gerberRead("gerber/6L_planar_transformerv3-F_Cu.gbr", …
"gerber/6L_planar_transformerv3-In1_Cu.gbr", …
"gerber/6L_planar_transformerv3-PTH.drl");
pb2 = pcbStack(P);
f_cu=pb2.Layers{2};
in1_cu=pb2.Layers{4};
p = pcbStack;
p.BoardThickness=0.203e-3*1+1e-3;
p.ViaDiameter=0.1e-3;
d1 = dielectric("FR4");
d1.Thickness = 0.203e-3;
air = dielectric("Air");
air.Thickness = 1e-3;
p.BoardShape = antenna.Rectangle(Length=60e-3, Width=60e-3,Center=[0.1187 -0.0775]);
%p.Layers = {f_cu,d1,in1_cu,d1,in2_cu,d1,in3_cu,d1,d1,in4_cu,d1,b_cu};
p.Layers={air,f_cu,d1,in1_cu,air}
p.FeedDiameter = 0.1e-3;
p.FeedLocations = [146.1e-3 -72e-3 2;]
p.ViaLocations = [143e-3 -77.5e-3 2 4;
117.5e-3 -77.5e-3 2 4]
show(p)
The reason I’m importing the pcbStack like that is that I’m planning on simulating a planar transformer EH fields and the gerberRead() only allows for 2 layered pcb, this way i can add more layers by importing more gerber files. However when I run
mesh(p)
After some 20 minutes of the program running, it returns the following errors:
Error using delaunayTriangulation
Enforcing Delaunay constraints leads to unstable repeated constraint intersections.
This may be due to near coincident intersecting constraints or near duplicate points.
Error in em.internal.meshprinting.inter6_full_mesh
Error in em.internal.meshprinting.multiLayerMetalImprint
Error in em.PCBStructures/generateMeshForStripFeedAndVia
Error in pcbStack/meshGenerator (line 1340)
Mesh = generateMeshForStripFeedAndVia(obj,mesherInput);
Error in em.MeshGeometry/updateMeshForPcbStack
Error in em.MeshGeometry/protectedmesh
Error in em.MeshGeometryAnalysis/mesh (line 66)
protectedmesh(obj,varargin{:});
And since some functions of the RF toolbox like current() EHFields() first call mesh() I cant run simulations of my design. I don’t know if the size could be the reason of the delaunayTriangulation failure or something is wrong with my setup Hi! this is the first time I ask a question here I hope im doing everthing right. Well, I’m trying to simulate the EH fields of a 2 layer pcb coil, I import the files and make the pcbStack with the following code:
P = gerberRead("gerber/6L_planar_transformerv3-F_Cu.gbr", …
"gerber/6L_planar_transformerv3-In1_Cu.gbr", …
"gerber/6L_planar_transformerv3-PTH.drl");
pb2 = pcbStack(P);
f_cu=pb2.Layers{2};
in1_cu=pb2.Layers{4};
p = pcbStack;
p.BoardThickness=0.203e-3*1+1e-3;
p.ViaDiameter=0.1e-3;
d1 = dielectric("FR4");
d1.Thickness = 0.203e-3;
air = dielectric("Air");
air.Thickness = 1e-3;
p.BoardShape = antenna.Rectangle(Length=60e-3, Width=60e-3,Center=[0.1187 -0.0775]);
%p.Layers = {f_cu,d1,in1_cu,d1,in2_cu,d1,in3_cu,d1,d1,in4_cu,d1,b_cu};
p.Layers={air,f_cu,d1,in1_cu,air}
p.FeedDiameter = 0.1e-3;
p.FeedLocations = [146.1e-3 -72e-3 2;]
p.ViaLocations = [143e-3 -77.5e-3 2 4;
117.5e-3 -77.5e-3 2 4]
show(p)
The reason I’m importing the pcbStack like that is that I’m planning on simulating a planar transformer EH fields and the gerberRead() only allows for 2 layered pcb, this way i can add more layers by importing more gerber files. However when I run
mesh(p)
After some 20 minutes of the program running, it returns the following errors:
Error using delaunayTriangulation
Enforcing Delaunay constraints leads to unstable repeated constraint intersections.
This may be due to near coincident intersecting constraints or near duplicate points.
Error in em.internal.meshprinting.inter6_full_mesh
Error in em.internal.meshprinting.multiLayerMetalImprint
Error in em.PCBStructures/generateMeshForStripFeedAndVia
Error in pcbStack/meshGenerator (line 1340)
Mesh = generateMeshForStripFeedAndVia(obj,mesherInput);
Error in em.MeshGeometry/updateMeshForPcbStack
Error in em.MeshGeometry/protectedmesh
Error in em.MeshGeometryAnalysis/mesh (line 66)
protectedmesh(obj,varargin{:});
And since some functions of the RF toolbox like current() EHFields() first call mesh() I cant run simulations of my design. I don’t know if the size could be the reason of the delaunayTriangulation failure or something is wrong with my setup pcb, rf-toolbox, pcbstack, delaunaytriangulation MATLAB Answers — New Questions
set the tick format of y axis
How can I set the format of the ticks of the y axis?
I want to change the upper one to the lower one, as the former is too wide in space.How can I set the format of the ticks of the y axis?
I want to change the upper one to the lower one, as the former is too wide in space. How can I set the format of the ticks of the y axis?
I want to change the upper one to the lower one, as the former is too wide in space. plotting MATLAB Answers — New Questions
Smoothing data without span
By how many samples will the data be smoothed if no span is used?By how many samples will the data be smoothed if no span is used? By how many samples will the data be smoothed if no span is used? smooth, span MATLAB Answers — New Questions
Explore DFT frequency accuracy, got stuck
I’m trying to analyze the frequency accuracy of the DFT as a function of DFT size assuming a rectangular
window. Using single sinusoidal waveform sampled at 5 kHz vary its frequency in small
increments to show the how the frequency accuracy changes for at least 4 different DFT length,
256, 512, 1024, and 4096.
Here is my code:
%Part 1
% MATLAB code to analyze the frequency accuracy of the DFT manually
fs = 5000; % Sampling frequency 5 kHz
f_start = 1000; % Start frequency of sinusoid (1 kHz)
f_end = 1050; % End frequency of sinusoid (1.05 kHz)
f_step = 1; % Frequency step size (small increments)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% DFT sizes to analyze
N_dft = [256, 512, 1024, 4096];
% Prepare figure
figure;
hold on;
for N = N_dft
freq_accuracy = []; % Store accuracy results for each DFT size
for f = f_start:f_step:f_end
% Generate sinusoidal waveform
x = sin(2*pi*f*t);
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
% Manually compute the DFT
X = x_windowed*dftmtx(N);
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Find the index of the peak in the magnitude of the DFT
[~, peak_idx] = max(abs(X));
% Estimated frequency from the DFT
f_estimated = freq_axis(peak_idx);
% Store the frequency error (absolute difference between true and estimated frequency)
freq_error = abs(f_estimated – f);
freq_accuracy = [freq_accuracy, freq_error];
end
% Plot the frequency accuracy for the current DFT size
plot(f_start:f_step:f_end, freq_accuracy, ‘DisplayName’, [‘N = ‘, num2str(N)]);
end
% Add labels and legend
xlabel(‘True Frequency (Hz)’);
ylabel(‘Frequency Error (Hz)’);
title(‘Frequency Accuracy of the DFT for Different DFT Sizes (Manual DFT)’);
legend(‘show’);
grid on;
hold off;
However, the result I got is really weird.
At some frequency the estimate error between true frequency can be 3000, while most of the time it’s under 1.
However, it I substitue this line: X = x_windowed*dftmtx(N);
with this line: X = fft(x_windowed, N);
Then I got this image
It seems that this is the correct figure.
I read from this website that fft and dftmtx function can be interchangeble
https://www.mathworks.com/help/signal/ref/dftmtx.html
But my results doesn’t approve it. I want to know why.
Besides, am I applying windowing function in a correct way?
The code is as following:
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;I’m trying to analyze the frequency accuracy of the DFT as a function of DFT size assuming a rectangular
window. Using single sinusoidal waveform sampled at 5 kHz vary its frequency in small
increments to show the how the frequency accuracy changes for at least 4 different DFT length,
256, 512, 1024, and 4096.
Here is my code:
%Part 1
% MATLAB code to analyze the frequency accuracy of the DFT manually
fs = 5000; % Sampling frequency 5 kHz
f_start = 1000; % Start frequency of sinusoid (1 kHz)
f_end = 1050; % End frequency of sinusoid (1.05 kHz)
f_step = 1; % Frequency step size (small increments)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% DFT sizes to analyze
N_dft = [256, 512, 1024, 4096];
% Prepare figure
figure;
hold on;
for N = N_dft
freq_accuracy = []; % Store accuracy results for each DFT size
for f = f_start:f_step:f_end
% Generate sinusoidal waveform
x = sin(2*pi*f*t);
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
% Manually compute the DFT
X = x_windowed*dftmtx(N);
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Find the index of the peak in the magnitude of the DFT
[~, peak_idx] = max(abs(X));
% Estimated frequency from the DFT
f_estimated = freq_axis(peak_idx);
% Store the frequency error (absolute difference between true and estimated frequency)
freq_error = abs(f_estimated – f);
freq_accuracy = [freq_accuracy, freq_error];
end
% Plot the frequency accuracy for the current DFT size
plot(f_start:f_step:f_end, freq_accuracy, ‘DisplayName’, [‘N = ‘, num2str(N)]);
end
% Add labels and legend
xlabel(‘True Frequency (Hz)’);
ylabel(‘Frequency Error (Hz)’);
title(‘Frequency Accuracy of the DFT for Different DFT Sizes (Manual DFT)’);
legend(‘show’);
grid on;
hold off;
However, the result I got is really weird.
At some frequency the estimate error between true frequency can be 3000, while most of the time it’s under 1.
However, it I substitue this line: X = x_windowed*dftmtx(N);
with this line: X = fft(x_windowed, N);
Then I got this image
It seems that this is the correct figure.
I read from this website that fft and dftmtx function can be interchangeble
https://www.mathworks.com/help/signal/ref/dftmtx.html
But my results doesn’t approve it. I want to know why.
Besides, am I applying windowing function in a correct way?
The code is as following:
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window; I’m trying to analyze the frequency accuracy of the DFT as a function of DFT size assuming a rectangular
window. Using single sinusoidal waveform sampled at 5 kHz vary its frequency in small
increments to show the how the frequency accuracy changes for at least 4 different DFT length,
256, 512, 1024, and 4096.
Here is my code:
%Part 1
% MATLAB code to analyze the frequency accuracy of the DFT manually
fs = 5000; % Sampling frequency 5 kHz
f_start = 1000; % Start frequency of sinusoid (1 kHz)
f_end = 1050; % End frequency of sinusoid (1.05 kHz)
f_step = 1; % Frequency step size (small increments)
t_duration = 1; % Signal duration in seconds
t = 0:1/fs:t_duration-1/fs; % Time vector
% DFT sizes to analyze
N_dft = [256, 512, 1024, 4096];
% Prepare figure
figure;
hold on;
for N = N_dft
freq_accuracy = []; % Store accuracy results for each DFT size
for f = f_start:f_step:f_end
% Generate sinusoidal waveform
x = sin(2*pi*f*t);
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window;
% Manually compute the DFT
X = x_windowed*dftmtx(N);
% Compute the frequency axis for the current DFT
freq_axis = (0:N-1)*(fs/N);
% Find the index of the peak in the magnitude of the DFT
[~, peak_idx] = max(abs(X));
% Estimated frequency from the DFT
f_estimated = freq_axis(peak_idx);
% Store the frequency error (absolute difference between true and estimated frequency)
freq_error = abs(f_estimated – f);
freq_accuracy = [freq_accuracy, freq_error];
end
% Plot the frequency accuracy for the current DFT size
plot(f_start:f_step:f_end, freq_accuracy, ‘DisplayName’, [‘N = ‘, num2str(N)]);
end
% Add labels and legend
xlabel(‘True Frequency (Hz)’);
ylabel(‘Frequency Error (Hz)’);
title(‘Frequency Accuracy of the DFT for Different DFT Sizes (Manual DFT)’);
legend(‘show’);
grid on;
hold off;
However, the result I got is really weird.
At some frequency the estimate error between true frequency can be 3000, while most of the time it’s under 1.
However, it I substitue this line: X = x_windowed*dftmtx(N);
with this line: X = fft(x_windowed, N);
Then I got this image
It seems that this is the correct figure.
I read from this website that fft and dftmtx function can be interchangeble
https://www.mathworks.com/help/signal/ref/dftmtx.html
But my results doesn’t approve it. I want to know why.
Besides, am I applying windowing function in a correct way?
The code is as following:
rectangular_window = rectwin(N)’;
% Apply rectangular window (implicitly applied since no windowing function)
% Select only the first N samples for each DFT calculation
x_windowed = x(1:N).*rectangular_window; dft, discrete fourier transform, matlab, digital signal processing MATLAB Answers — New Questions
How to convert from FORTRAN TO MATLAB
Dear all,
Please am working on a project and now found a FORTRAN code to speed up my research but I having been using MATLAB and so, I need to convert the newly found FORTRAN code to MATLAB. Please kindly help me out on this conversion or give a detail explanation on how best I can convert from FORTRAN to MATLAB. The FORTRAN code is in the attachment. Thanks in anticipation!Dear all,
Please am working on a project and now found a FORTRAN code to speed up my research but I having been using MATLAB and so, I need to convert the newly found FORTRAN code to MATLAB. Please kindly help me out on this conversion or give a detail explanation on how best I can convert from FORTRAN to MATLAB. The FORTRAN code is in the attachment. Thanks in anticipation! Dear all,
Please am working on a project and now found a FORTRAN code to speed up my research but I having been using MATLAB and so, I need to convert the newly found FORTRAN code to MATLAB. Please kindly help me out on this conversion or give a detail explanation on how best I can convert from FORTRAN to MATLAB. The FORTRAN code is in the attachment. Thanks in anticipation! fortran code MATLAB Answers — New Questions
Hi,I tray RUN this code but i get tis error ( below the code)
% Please note that this section requires the toolbox m_map
% Now we would like to know the mean states and annual trends of MHW
% frequency, i.e. how many MHW events would be detected per year and how it
% changes with time.
[mean_freq,annual_freq,trend_freq,p_freq]=mean_and_trend_new(MHW,mhw_ts,1982,’Metric’,’Frequency’);
% These four outputs separately represent the total mean, annual mean,
% annual trend and associated p value of frequency.
% This function could detect mean states and trends for six different
% variables (Frequency, mean intensity, max intensity, duration and total
% MHW/MCs days).
metric_used={‘Frequency’,’MeanInt’,’MaxInt’,’CumInt’,’Duration’,’Days’};
for i=1:6;
eval([‘[mean_’ metric_used{i} ‘,annual_’ metric_used{i} ‘,trend_’ metric_used{i} ‘,p_’ metric_used{i} ‘]=mean_and_trend_new(MHW,mhw_ts,1982,’ ”” ‘Metric’ ”” ‘,’ ‘metric_used{i}’ ‘);’])
end
% plot mean and trend
% It could be detected that, as a global hotspot, the oceanic region off
% eastern Tasmania exhibits significant positive trends of MHW metrics.
figure(‘pos’,[10 10 1500 1500]);
m_proj(‘mercator’,’lat’,[-45 -37],’lon’,[147 155]);
for i=1:6;
subplot(2,6,i);
eval([‘mean_here=mean_’ metric_used{i} ‘;’]);
eval([‘t_here=trend_’ metric_used{i} ‘;’]);
m_pcolor(lon_used,lat_used,mean_here’);
shading interp
m_coast(‘patch’,[0.7 0.7 0.7]);
m_grid;
colormap(jet);
s=colorbar(‘location’,’southoutside’);
title(metric_used{i},’fontname’,’consolas’,’fontsize’,12);
subplot(2,6,i+6);
eval([‘mean_here=mean_’ metric_used{i} ‘;’]);
eval([‘t_here=trend_’ metric_used{i} ‘;’]);
m_pcolor(lon_used,lat_used,t_here’);
shading interp
m_coast(‘patch’,[0.7 0.7 0.7]);
m_grid;
colormap(jet);
s=colorbar(‘location’,’southoutside’);
title([‘Trend-‘ metric_used{i}],’fontname’,’consolas’,’fontsize’,12);
end
%% 5. Applying cluster algoirthm to MHW – A kmeans example.
% We get so many MHWs now…. Could we distinguish them into different
% gropus based on their metrics?
% Change it to matrix;
MHW_m=MHW{:,:};
% Extract mean, max, cumulative intensity and duration.
MHW_m=MHW_m(:,[3 4 5 7]);
[data_for_k,mu,sd]=zscore(MHW_m);
% Determine suitable groups of kmeans cluster.
index_full=[];
cor_full=[];
for i=2:20;
k=kmeans(data_for_k,i,’Distance’,’cityblock’,’maxiter’,200);
k_full=[];
for j=1:i;
k_full=[k_full;nanmean(data_for_k(k==j,:))];
end
k_cor=k_full(k,:);
k_cor=k_cor(:);
[c,p]=corr([data_for_k(:) k_cor]);
index_full=[index_full;2];
cor_full=[cor_full;c(1,2)];
end
figure(‘pos’,[10 10 1500 1500]);
subplot(1,2,1);
plot(2:20,cor_full,’linewidth’,2);
hold on
plot(9*ones(1000,1),linspace(0.6,1,1000),’r–‘);
xlabel(‘Number of Groups’,’fontsize’,16,’fontweight’,’bold’);
ylabel(‘Correlation’,’fontsize’,16,’fontweight’,’bold’);
title(‘Correlation’,’fontsize’,16);
set(gca,’xtick’,[5 9 10 15 20],’fontsize’,16);
subplot(1,2,2);
plot(3:20,diff(cor_full),’linewidth’,2);
hold on
plot(9*ones(1000,1),linspace(-0.02,0.14,1000),’r–‘);
xlabel(‘Number of Groups’,’fontsize’,16,’fontweight’,’bold’);
ylabel(‘First difference of Correlation’,’fontsize’,16,’fontweight’,’bold’);
title(‘First Difference of Correlation’,’fontsize’,16);
set(gca,’fontsize’,16);
% Use 9 groups.
k=kmeans(data_for_k,9,’Distance’,’cityblock’,’maxiter’,200);
k_9=[];
prop_9=[];
for i=1:9;
data_here=data_for_k(k==i,:);
data_here=nanmean(data_here);
data_here=data_here.*sd+mu;
k_9=[k_9;data_here];
prop_9=[prop_9;nansum(k==i)./size(data_for_k,1)];
end
loc_x=[1.5 1.5 1.5 2.5 2.5 2.5 3.5 3.5 3.5];
loc_y=[1.5 2.5 3.5 1.5 2.5 3.5 1.5 2.5 3.5];
text_used={[‘1: ‘ num2str(round(prop_9(1)*100)) ‘%’],[‘2: ‘ num2str(round(prop_9(2)*100)) ‘%’],[‘3: ‘ num2str(round(prop_9(3)*100)) ‘%’],…
[‘4: ‘ num2str(round(prop_9(4)*100)) ‘%’],[‘5: ‘ num2str(round(prop_9(5)*100)) ‘%’],[‘6: ‘ num2str(round(prop_9(6)*100)) ‘%’],…
[‘7: ‘ num2str(round(prop_9(7)*100)) ‘%’],[‘8: ‘ num2str(round(prop_9(8)*100)) ‘%’],[‘9: ‘ num2str(round(prop_9(9)*100)) ‘%’]};
figure(‘pos’,[10 10 1500 1500]);
h=subplot(2,2,1);
data_here=k_9(:,1);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
set(h,’ydir’,’reverse’);
axis off
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar;
title(‘Durations’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,2);
data_here=k_9(:,2);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
axis off
set(h,’ydir’,’reverse’);
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘MaxInt’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,3);
data_here=k_9(:,3);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
axis off
set(h,’ydir’,’reverse’);
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘MeanInt’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,4);
data_here=k_9(:,4);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
[x,y]=meshgrid(1:4,1:4);
pcolor(1:4,1:4,data_here);
set(h,’ydir’,’reverse’);
axis off
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘CumInt’,’fontsize’,16,’fontweight’,’bold’);
% Their associated SSTA patterns
% Calculate SSTA
time_used=datevec(datenum(1982,1,1):datenum(2016,12,31));
m_d_unique=unique(time_used(:,2:3),’rows’);
ssta_full=NaN(size(sst_full));
for i=1:size(m_d_unique);
date_here=m_d_unique(i,:);
index_here=find(time_used(:,2)==date_here(1) & time_used(:,3)==date_here(2));
ssta_full(:,:,index_here)=sst_full(:,:,index_here)-nanmean(sst_full(:,:,index_here),3);
end
sst_1993_2016=ssta_full(:,:,(datenum(1993,1,1):datenum(2016,12,31))-datenum(1982,1,1)+1);
time_used=MHW{:,:};
time_used=time_used(:,1:2);
start_full=datenum(num2str(time_used(:,1)),’yyyymmdd’)-datenum(1993,1,1)+1;
end_full=datenum(num2str(time_used(:,2)),’yyyymmdd’)-datenum(1993,1,1)+1;
for i=1:9;
start_here=start_full(k==i);
end_here=end_full(k==i);
index_here=[];
for j=1:length(start_here);
period_here=start_here(j):end_here(j);
index_here=[index_here;period_here(:)];
end
eval([‘sst_’ num2str(i) ‘=nanmean(sst_1993_2016(:,:,index_here),3);’])
end
color_used=hot;
color_used=color_used(end:-1:1,:);
figure(‘pos’,[10 10 1500 1500]);
plot_index=[1 4 7 2 5 8 3 6 9];
for i=1:9;
eval([‘plot_here=sst_’ num2str(i) ‘;’]);
subplot(3,3,plot_index(i));
eval([‘data_here=sst_’ num2str(i) ‘;’])
m_contourf(lon_used,lat_used,data_here’,-3:0.1:3,’linestyle’,’none’);
if i~=3;
m_grid(‘xtick’,[],’ytick’,[]);
else;
m_grid(‘linestyle’,’none’);
end
m_gshhs_h(‘patch’,[0 0 0]);
colormap(color_used);
caxis([0 2]);
title([‘Group (‘ num2str(i) ‘):’ num2str(round(prop_9(i)*100)) ‘%’],’fontsize’,16);
end
hp4=get(subplot(3,3,9),’Position’);
s=colorbar(‘Position’, [hp4(1)+hp4(3)+0.025 hp4(2) 0.025 0.85],’fontsize’,14);
s.Label.String=’^{o}C’;
Index exceeds the number of array elements. Index must not exceed 12784.
Error in event_line (line 84)
y1=m90_plot(x1-datenum(data_start,1,1)+1);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in an_example2 (line 53)
event_line(sst_full,MHW,mclim,m90,[1 2],1982,[2015 9 1],[2016 5 1]);% Please note that this section requires the toolbox m_map
% Now we would like to know the mean states and annual trends of MHW
% frequency, i.e. how many MHW events would be detected per year and how it
% changes with time.
[mean_freq,annual_freq,trend_freq,p_freq]=mean_and_trend_new(MHW,mhw_ts,1982,’Metric’,’Frequency’);
% These four outputs separately represent the total mean, annual mean,
% annual trend and associated p value of frequency.
% This function could detect mean states and trends for six different
% variables (Frequency, mean intensity, max intensity, duration and total
% MHW/MCs days).
metric_used={‘Frequency’,’MeanInt’,’MaxInt’,’CumInt’,’Duration’,’Days’};
for i=1:6;
eval([‘[mean_’ metric_used{i} ‘,annual_’ metric_used{i} ‘,trend_’ metric_used{i} ‘,p_’ metric_used{i} ‘]=mean_and_trend_new(MHW,mhw_ts,1982,’ ”” ‘Metric’ ”” ‘,’ ‘metric_used{i}’ ‘);’])
end
% plot mean and trend
% It could be detected that, as a global hotspot, the oceanic region off
% eastern Tasmania exhibits significant positive trends of MHW metrics.
figure(‘pos’,[10 10 1500 1500]);
m_proj(‘mercator’,’lat’,[-45 -37],’lon’,[147 155]);
for i=1:6;
subplot(2,6,i);
eval([‘mean_here=mean_’ metric_used{i} ‘;’]);
eval([‘t_here=trend_’ metric_used{i} ‘;’]);
m_pcolor(lon_used,lat_used,mean_here’);
shading interp
m_coast(‘patch’,[0.7 0.7 0.7]);
m_grid;
colormap(jet);
s=colorbar(‘location’,’southoutside’);
title(metric_used{i},’fontname’,’consolas’,’fontsize’,12);
subplot(2,6,i+6);
eval([‘mean_here=mean_’ metric_used{i} ‘;’]);
eval([‘t_here=trend_’ metric_used{i} ‘;’]);
m_pcolor(lon_used,lat_used,t_here’);
shading interp
m_coast(‘patch’,[0.7 0.7 0.7]);
m_grid;
colormap(jet);
s=colorbar(‘location’,’southoutside’);
title([‘Trend-‘ metric_used{i}],’fontname’,’consolas’,’fontsize’,12);
end
%% 5. Applying cluster algoirthm to MHW – A kmeans example.
% We get so many MHWs now…. Could we distinguish them into different
% gropus based on their metrics?
% Change it to matrix;
MHW_m=MHW{:,:};
% Extract mean, max, cumulative intensity and duration.
MHW_m=MHW_m(:,[3 4 5 7]);
[data_for_k,mu,sd]=zscore(MHW_m);
% Determine suitable groups of kmeans cluster.
index_full=[];
cor_full=[];
for i=2:20;
k=kmeans(data_for_k,i,’Distance’,’cityblock’,’maxiter’,200);
k_full=[];
for j=1:i;
k_full=[k_full;nanmean(data_for_k(k==j,:))];
end
k_cor=k_full(k,:);
k_cor=k_cor(:);
[c,p]=corr([data_for_k(:) k_cor]);
index_full=[index_full;2];
cor_full=[cor_full;c(1,2)];
end
figure(‘pos’,[10 10 1500 1500]);
subplot(1,2,1);
plot(2:20,cor_full,’linewidth’,2);
hold on
plot(9*ones(1000,1),linspace(0.6,1,1000),’r–‘);
xlabel(‘Number of Groups’,’fontsize’,16,’fontweight’,’bold’);
ylabel(‘Correlation’,’fontsize’,16,’fontweight’,’bold’);
title(‘Correlation’,’fontsize’,16);
set(gca,’xtick’,[5 9 10 15 20],’fontsize’,16);
subplot(1,2,2);
plot(3:20,diff(cor_full),’linewidth’,2);
hold on
plot(9*ones(1000,1),linspace(-0.02,0.14,1000),’r–‘);
xlabel(‘Number of Groups’,’fontsize’,16,’fontweight’,’bold’);
ylabel(‘First difference of Correlation’,’fontsize’,16,’fontweight’,’bold’);
title(‘First Difference of Correlation’,’fontsize’,16);
set(gca,’fontsize’,16);
% Use 9 groups.
k=kmeans(data_for_k,9,’Distance’,’cityblock’,’maxiter’,200);
k_9=[];
prop_9=[];
for i=1:9;
data_here=data_for_k(k==i,:);
data_here=nanmean(data_here);
data_here=data_here.*sd+mu;
k_9=[k_9;data_here];
prop_9=[prop_9;nansum(k==i)./size(data_for_k,1)];
end
loc_x=[1.5 1.5 1.5 2.5 2.5 2.5 3.5 3.5 3.5];
loc_y=[1.5 2.5 3.5 1.5 2.5 3.5 1.5 2.5 3.5];
text_used={[‘1: ‘ num2str(round(prop_9(1)*100)) ‘%’],[‘2: ‘ num2str(round(prop_9(2)*100)) ‘%’],[‘3: ‘ num2str(round(prop_9(3)*100)) ‘%’],…
[‘4: ‘ num2str(round(prop_9(4)*100)) ‘%’],[‘5: ‘ num2str(round(prop_9(5)*100)) ‘%’],[‘6: ‘ num2str(round(prop_9(6)*100)) ‘%’],…
[‘7: ‘ num2str(round(prop_9(7)*100)) ‘%’],[‘8: ‘ num2str(round(prop_9(8)*100)) ‘%’],[‘9: ‘ num2str(round(prop_9(9)*100)) ‘%’]};
figure(‘pos’,[10 10 1500 1500]);
h=subplot(2,2,1);
data_here=k_9(:,1);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
set(h,’ydir’,’reverse’);
axis off
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar;
title(‘Durations’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,2);
data_here=k_9(:,2);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
axis off
set(h,’ydir’,’reverse’);
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘MaxInt’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,3);
data_here=k_9(:,3);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
axis off
set(h,’ydir’,’reverse’);
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘MeanInt’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,4);
data_here=k_9(:,4);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
[x,y]=meshgrid(1:4,1:4);
pcolor(1:4,1:4,data_here);
set(h,’ydir’,’reverse’);
axis off
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘CumInt’,’fontsize’,16,’fontweight’,’bold’);
% Their associated SSTA patterns
% Calculate SSTA
time_used=datevec(datenum(1982,1,1):datenum(2016,12,31));
m_d_unique=unique(time_used(:,2:3),’rows’);
ssta_full=NaN(size(sst_full));
for i=1:size(m_d_unique);
date_here=m_d_unique(i,:);
index_here=find(time_used(:,2)==date_here(1) & time_used(:,3)==date_here(2));
ssta_full(:,:,index_here)=sst_full(:,:,index_here)-nanmean(sst_full(:,:,index_here),3);
end
sst_1993_2016=ssta_full(:,:,(datenum(1993,1,1):datenum(2016,12,31))-datenum(1982,1,1)+1);
time_used=MHW{:,:};
time_used=time_used(:,1:2);
start_full=datenum(num2str(time_used(:,1)),’yyyymmdd’)-datenum(1993,1,1)+1;
end_full=datenum(num2str(time_used(:,2)),’yyyymmdd’)-datenum(1993,1,1)+1;
for i=1:9;
start_here=start_full(k==i);
end_here=end_full(k==i);
index_here=[];
for j=1:length(start_here);
period_here=start_here(j):end_here(j);
index_here=[index_here;period_here(:)];
end
eval([‘sst_’ num2str(i) ‘=nanmean(sst_1993_2016(:,:,index_here),3);’])
end
color_used=hot;
color_used=color_used(end:-1:1,:);
figure(‘pos’,[10 10 1500 1500]);
plot_index=[1 4 7 2 5 8 3 6 9];
for i=1:9;
eval([‘plot_here=sst_’ num2str(i) ‘;’]);
subplot(3,3,plot_index(i));
eval([‘data_here=sst_’ num2str(i) ‘;’])
m_contourf(lon_used,lat_used,data_here’,-3:0.1:3,’linestyle’,’none’);
if i~=3;
m_grid(‘xtick’,[],’ytick’,[]);
else;
m_grid(‘linestyle’,’none’);
end
m_gshhs_h(‘patch’,[0 0 0]);
colormap(color_used);
caxis([0 2]);
title([‘Group (‘ num2str(i) ‘):’ num2str(round(prop_9(i)*100)) ‘%’],’fontsize’,16);
end
hp4=get(subplot(3,3,9),’Position’);
s=colorbar(‘Position’, [hp4(1)+hp4(3)+0.025 hp4(2) 0.025 0.85],’fontsize’,14);
s.Label.String=’^{o}C’;
Index exceeds the number of array elements. Index must not exceed 12784.
Error in event_line (line 84)
y1=m90_plot(x1-datenum(data_start,1,1)+1);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in an_example2 (line 53)
event_line(sst_full,MHW,mclim,m90,[1 2],1982,[2015 9 1],[2016 5 1]); % Please note that this section requires the toolbox m_map
% Now we would like to know the mean states and annual trends of MHW
% frequency, i.e. how many MHW events would be detected per year and how it
% changes with time.
[mean_freq,annual_freq,trend_freq,p_freq]=mean_and_trend_new(MHW,mhw_ts,1982,’Metric’,’Frequency’);
% These four outputs separately represent the total mean, annual mean,
% annual trend and associated p value of frequency.
% This function could detect mean states and trends for six different
% variables (Frequency, mean intensity, max intensity, duration and total
% MHW/MCs days).
metric_used={‘Frequency’,’MeanInt’,’MaxInt’,’CumInt’,’Duration’,’Days’};
for i=1:6;
eval([‘[mean_’ metric_used{i} ‘,annual_’ metric_used{i} ‘,trend_’ metric_used{i} ‘,p_’ metric_used{i} ‘]=mean_and_trend_new(MHW,mhw_ts,1982,’ ”” ‘Metric’ ”” ‘,’ ‘metric_used{i}’ ‘);’])
end
% plot mean and trend
% It could be detected that, as a global hotspot, the oceanic region off
% eastern Tasmania exhibits significant positive trends of MHW metrics.
figure(‘pos’,[10 10 1500 1500]);
m_proj(‘mercator’,’lat’,[-45 -37],’lon’,[147 155]);
for i=1:6;
subplot(2,6,i);
eval([‘mean_here=mean_’ metric_used{i} ‘;’]);
eval([‘t_here=trend_’ metric_used{i} ‘;’]);
m_pcolor(lon_used,lat_used,mean_here’);
shading interp
m_coast(‘patch’,[0.7 0.7 0.7]);
m_grid;
colormap(jet);
s=colorbar(‘location’,’southoutside’);
title(metric_used{i},’fontname’,’consolas’,’fontsize’,12);
subplot(2,6,i+6);
eval([‘mean_here=mean_’ metric_used{i} ‘;’]);
eval([‘t_here=trend_’ metric_used{i} ‘;’]);
m_pcolor(lon_used,lat_used,t_here’);
shading interp
m_coast(‘patch’,[0.7 0.7 0.7]);
m_grid;
colormap(jet);
s=colorbar(‘location’,’southoutside’);
title([‘Trend-‘ metric_used{i}],’fontname’,’consolas’,’fontsize’,12);
end
%% 5. Applying cluster algoirthm to MHW – A kmeans example.
% We get so many MHWs now…. Could we distinguish them into different
% gropus based on their metrics?
% Change it to matrix;
MHW_m=MHW{:,:};
% Extract mean, max, cumulative intensity and duration.
MHW_m=MHW_m(:,[3 4 5 7]);
[data_for_k,mu,sd]=zscore(MHW_m);
% Determine suitable groups of kmeans cluster.
index_full=[];
cor_full=[];
for i=2:20;
k=kmeans(data_for_k,i,’Distance’,’cityblock’,’maxiter’,200);
k_full=[];
for j=1:i;
k_full=[k_full;nanmean(data_for_k(k==j,:))];
end
k_cor=k_full(k,:);
k_cor=k_cor(:);
[c,p]=corr([data_for_k(:) k_cor]);
index_full=[index_full;2];
cor_full=[cor_full;c(1,2)];
end
figure(‘pos’,[10 10 1500 1500]);
subplot(1,2,1);
plot(2:20,cor_full,’linewidth’,2);
hold on
plot(9*ones(1000,1),linspace(0.6,1,1000),’r–‘);
xlabel(‘Number of Groups’,’fontsize’,16,’fontweight’,’bold’);
ylabel(‘Correlation’,’fontsize’,16,’fontweight’,’bold’);
title(‘Correlation’,’fontsize’,16);
set(gca,’xtick’,[5 9 10 15 20],’fontsize’,16);
subplot(1,2,2);
plot(3:20,diff(cor_full),’linewidth’,2);
hold on
plot(9*ones(1000,1),linspace(-0.02,0.14,1000),’r–‘);
xlabel(‘Number of Groups’,’fontsize’,16,’fontweight’,’bold’);
ylabel(‘First difference of Correlation’,’fontsize’,16,’fontweight’,’bold’);
title(‘First Difference of Correlation’,’fontsize’,16);
set(gca,’fontsize’,16);
% Use 9 groups.
k=kmeans(data_for_k,9,’Distance’,’cityblock’,’maxiter’,200);
k_9=[];
prop_9=[];
for i=1:9;
data_here=data_for_k(k==i,:);
data_here=nanmean(data_here);
data_here=data_here.*sd+mu;
k_9=[k_9;data_here];
prop_9=[prop_9;nansum(k==i)./size(data_for_k,1)];
end
loc_x=[1.5 1.5 1.5 2.5 2.5 2.5 3.5 3.5 3.5];
loc_y=[1.5 2.5 3.5 1.5 2.5 3.5 1.5 2.5 3.5];
text_used={[‘1: ‘ num2str(round(prop_9(1)*100)) ‘%’],[‘2: ‘ num2str(round(prop_9(2)*100)) ‘%’],[‘3: ‘ num2str(round(prop_9(3)*100)) ‘%’],…
[‘4: ‘ num2str(round(prop_9(4)*100)) ‘%’],[‘5: ‘ num2str(round(prop_9(5)*100)) ‘%’],[‘6: ‘ num2str(round(prop_9(6)*100)) ‘%’],…
[‘7: ‘ num2str(round(prop_9(7)*100)) ‘%’],[‘8: ‘ num2str(round(prop_9(8)*100)) ‘%’],[‘9: ‘ num2str(round(prop_9(9)*100)) ‘%’]};
figure(‘pos’,[10 10 1500 1500]);
h=subplot(2,2,1);
data_here=k_9(:,1);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
set(h,’ydir’,’reverse’);
axis off
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar;
title(‘Durations’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,2);
data_here=k_9(:,2);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
axis off
set(h,’ydir’,’reverse’);
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘MaxInt’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,3);
data_here=k_9(:,3);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
pcolor(1:4,1:4,data_here);
axis off
set(h,’ydir’,’reverse’);
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘MeanInt’,’fontsize’,16,’fontweight’,’bold’);
h=subplot(2,2,4);
data_here=k_9(:,4);
data_here=reshape(data_here,3,3);
data_here(:,end+1)=data_here(:,end);
data_here(end+1,:)=data_here(end,:);
[x,y]=meshgrid(1:4,1:4);
pcolor(1:4,1:4,data_here);
set(h,’ydir’,’reverse’);
axis off
colormap(jet);
text(loc_x,loc_y,text_used,’fontsize’,16,’horiz’,’center’,’fontweight’,’bold’);
colorbar
title(‘CumInt’,’fontsize’,16,’fontweight’,’bold’);
% Their associated SSTA patterns
% Calculate SSTA
time_used=datevec(datenum(1982,1,1):datenum(2016,12,31));
m_d_unique=unique(time_used(:,2:3),’rows’);
ssta_full=NaN(size(sst_full));
for i=1:size(m_d_unique);
date_here=m_d_unique(i,:);
index_here=find(time_used(:,2)==date_here(1) & time_used(:,3)==date_here(2));
ssta_full(:,:,index_here)=sst_full(:,:,index_here)-nanmean(sst_full(:,:,index_here),3);
end
sst_1993_2016=ssta_full(:,:,(datenum(1993,1,1):datenum(2016,12,31))-datenum(1982,1,1)+1);
time_used=MHW{:,:};
time_used=time_used(:,1:2);
start_full=datenum(num2str(time_used(:,1)),’yyyymmdd’)-datenum(1993,1,1)+1;
end_full=datenum(num2str(time_used(:,2)),’yyyymmdd’)-datenum(1993,1,1)+1;
for i=1:9;
start_here=start_full(k==i);
end_here=end_full(k==i);
index_here=[];
for j=1:length(start_here);
period_here=start_here(j):end_here(j);
index_here=[index_here;period_here(:)];
end
eval([‘sst_’ num2str(i) ‘=nanmean(sst_1993_2016(:,:,index_here),3);’])
end
color_used=hot;
color_used=color_used(end:-1:1,:);
figure(‘pos’,[10 10 1500 1500]);
plot_index=[1 4 7 2 5 8 3 6 9];
for i=1:9;
eval([‘plot_here=sst_’ num2str(i) ‘;’]);
subplot(3,3,plot_index(i));
eval([‘data_here=sst_’ num2str(i) ‘;’])
m_contourf(lon_used,lat_used,data_here’,-3:0.1:3,’linestyle’,’none’);
if i~=3;
m_grid(‘xtick’,[],’ytick’,[]);
else;
m_grid(‘linestyle’,’none’);
end
m_gshhs_h(‘patch’,[0 0 0]);
colormap(color_used);
caxis([0 2]);
title([‘Group (‘ num2str(i) ‘):’ num2str(round(prop_9(i)*100)) ‘%’],’fontsize’,16);
end
hp4=get(subplot(3,3,9),’Position’);
s=colorbar(‘Position’, [hp4(1)+hp4(3)+0.025 hp4(2) 0.025 0.85],’fontsize’,14);
s.Label.String=’^{o}C’;
Index exceeds the number of array elements. Index must not exceed 12784.
Error in event_line (line 84)
y1=m90_plot(x1-datenum(data_start,1,1)+1);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in an_example2 (line 53)
event_line(sst_full,MHW,mclim,m90,[1 2],1982,[2015 9 1],[2016 5 1]); error, heat MATLAB Answers — New Questions
field weakening of induction machine
Hello. Has anyone done flux weakening control of an induction machine? How is the maximum current calculated?Hello. Has anyone done flux weakening control of an induction machine? How is the maximum current calculated? Hello. Has anyone done flux weakening control of an induction machine? How is the maximum current calculated? field weakening control MATLAB Answers — New Questions
how to use categorical in uitable
hi, I want to choose as value in a table field ‘Fil’ or ‘Stat’
cat=categorical({‘Fil’;’Stat’});
name={‘A’,’B’};
nrows=numel(name);
VNAMES={‘Draw’;’Filt_Stat’};
VTYPES=[{‘logical’},{cat}];
T=table(‘Size’,[nrows,numel(VNAMES)],’VariableTypes’,VTYPES,’VariableNames’,VNAMES); % empty t
T.Draw=repmat({true},nrows,1);
ct=cell(1, numel(name));
ct(:) = {cat{2}};
T.Filt_Stat=ct’;
app.Portfolio_UITable.Data=T;
i get this error:
Error using table
Specify variable types as a string array or a cell array of character
vectors, such as ["string", "datetime", "double"].hi, I want to choose as value in a table field ‘Fil’ or ‘Stat’
cat=categorical({‘Fil’;’Stat’});
name={‘A’,’B’};
nrows=numel(name);
VNAMES={‘Draw’;’Filt_Stat’};
VTYPES=[{‘logical’},{cat}];
T=table(‘Size’,[nrows,numel(VNAMES)],’VariableTypes’,VTYPES,’VariableNames’,VNAMES); % empty t
T.Draw=repmat({true},nrows,1);
ct=cell(1, numel(name));
ct(:) = {cat{2}};
T.Filt_Stat=ct’;
app.Portfolio_UITable.Data=T;
i get this error:
Error using table
Specify variable types as a string array or a cell array of character
vectors, such as ["string", "datetime", "double"]. hi, I want to choose as value in a table field ‘Fil’ or ‘Stat’
cat=categorical({‘Fil’;’Stat’});
name={‘A’,’B’};
nrows=numel(name);
VNAMES={‘Draw’;’Filt_Stat’};
VTYPES=[{‘logical’},{cat}];
T=table(‘Size’,[nrows,numel(VNAMES)],’VariableTypes’,VTYPES,’VariableNames’,VNAMES); % empty t
T.Draw=repmat({true},nrows,1);
ct=cell(1, numel(name));
ct(:) = {cat{2}};
T.Filt_Stat=ct’;
app.Portfolio_UITable.Data=T;
i get this error:
Error using table
Specify variable types as a string array or a cell array of character
vectors, such as ["string", "datetime", "double"]. how to use categorical in uitable MATLAB Answers — New Questions
PointNet++ training problem
I want to train my own XYZL (L-label) data with PointNet++. I couldn’t do it in any way. What codes can I use to do this in order?
The label data consists of five classes (1,2,3,4, and 5), and the point cloud consists of 500,000 points.
Similarly, I am having trouble with PointNet. When I use the pre-trained model, the process can be run, but the class labels I want are not there either.
Thanks!I want to train my own XYZL (L-label) data with PointNet++. I couldn’t do it in any way. What codes can I use to do this in order?
The label data consists of five classes (1,2,3,4, and 5), and the point cloud consists of 500,000 points.
Similarly, I am having trouble with PointNet. When I use the pre-trained model, the process can be run, but the class labels I want are not there either.
Thanks! I want to train my own XYZL (L-label) data with PointNet++. I couldn’t do it in any way. What codes can I use to do this in order?
The label data consists of five classes (1,2,3,4, and 5), and the point cloud consists of 500,000 points.
Similarly, I am having trouble with PointNet. When I use the pre-trained model, the process can be run, but the class labels I want are not there either.
Thanks! pointnet, pointnet++ MATLAB Answers — New Questions
Arduino writePWMDutyCycle not performing the cycle
Hi,
I am having a weird issue with the Arduino via Matlab code.
this is the simple code I have
a = arduino
configurePin(a,’D12′,’PWM’)
writePWMVoltage(a,’D12′,3)
writePWMDutyCycle(a,’D12′,0.5)
When I run this code, it is just outputting 1.65V which is 0.5 of 3.3V (Due) instead of doing the cycle of the voltage.
Anyone made this cycle to work?Hi,
I am having a weird issue with the Arduino via Matlab code.
this is the simple code I have
a = arduino
configurePin(a,’D12′,’PWM’)
writePWMVoltage(a,’D12′,3)
writePWMDutyCycle(a,’D12′,0.5)
When I run this code, it is just outputting 1.65V which is 0.5 of 3.3V (Due) instead of doing the cycle of the voltage.
Anyone made this cycle to work? Hi,
I am having a weird issue with the Arduino via Matlab code.
this is the simple code I have
a = arduino
configurePin(a,’D12′,’PWM’)
writePWMVoltage(a,’D12′,3)
writePWMDutyCycle(a,’D12′,0.5)
When I run this code, it is just outputting 1.65V which is 0.5 of 3.3V (Due) instead of doing the cycle of the voltage.
Anyone made this cycle to work? arduino, matlab, pwm MATLAB Answers — New Questions
scale/normalize parameter vector for optimization
In my optim problem, the parameters naturally vary by several orders of magnitude because they represent interpolation values of a B-Spline function F = spapi(k,x,y). For instance, may be close to zero and . The step tolerance is just a constant and does not account for these differences in scale between the parameters. In my case, the objective function changes differently w.r.t changes in the "smaller" y’s than in larger y’s, making parameter scaling or normalization potentially beneficial.
1. In machine learning literature, I often encounter [0,1] scaling as a common technique. Would this approach be suitable for my problem as well? Or can you suggest more appropriate scaling techniques given the parameters represent interpolation values?
2. This might be a separate question, but also relates to parameter scaling/transformation. My Jacobian matrix J (hence, Hessian approx J^T*J) tends to be poorly conditioned. I have considered to switching to a different basis for the parameter vector. So far, my parameters are multipliers for the unit vectors : . I vaguely recall a discussion where a teacher suggested using the normalized eigenvectors of the Hessian as the unit vectors: where are the (normalized) eigenvectors of the Hessian and are the new parameters.
My questions are: In theory, would parameterization in terms of the eigenvectors be effective in improving the conditioning of the problem? If so, is this approach compatible with the presence of bounds and linear constraints on the parameters?
Thank you!In my optim problem, the parameters naturally vary by several orders of magnitude because they represent interpolation values of a B-Spline function F = spapi(k,x,y). For instance, may be close to zero and . The step tolerance is just a constant and does not account for these differences in scale between the parameters. In my case, the objective function changes differently w.r.t changes in the "smaller" y’s than in larger y’s, making parameter scaling or normalization potentially beneficial.
1. In machine learning literature, I often encounter [0,1] scaling as a common technique. Would this approach be suitable for my problem as well? Or can you suggest more appropriate scaling techniques given the parameters represent interpolation values?
2. This might be a separate question, but also relates to parameter scaling/transformation. My Jacobian matrix J (hence, Hessian approx J^T*J) tends to be poorly conditioned. I have considered to switching to a different basis for the parameter vector. So far, my parameters are multipliers for the unit vectors : . I vaguely recall a discussion where a teacher suggested using the normalized eigenvectors of the Hessian as the unit vectors: where are the (normalized) eigenvectors of the Hessian and are the new parameters.
My questions are: In theory, would parameterization in terms of the eigenvectors be effective in improving the conditioning of the problem? If so, is this approach compatible with the presence of bounds and linear constraints on the parameters?
Thank you! In my optim problem, the parameters naturally vary by several orders of magnitude because they represent interpolation values of a B-Spline function F = spapi(k,x,y). For instance, may be close to zero and . The step tolerance is just a constant and does not account for these differences in scale between the parameters. In my case, the objective function changes differently w.r.t changes in the "smaller" y’s than in larger y’s, making parameter scaling or normalization potentially beneficial.
1. In machine learning literature, I often encounter [0,1] scaling as a common technique. Would this approach be suitable for my problem as well? Or can you suggest more appropriate scaling techniques given the parameters represent interpolation values?
2. This might be a separate question, but also relates to parameter scaling/transformation. My Jacobian matrix J (hence, Hessian approx J^T*J) tends to be poorly conditioned. I have considered to switching to a different basis for the parameter vector. So far, my parameters are multipliers for the unit vectors : . I vaguely recall a discussion where a teacher suggested using the normalized eigenvectors of the Hessian as the unit vectors: where are the (normalized) eigenvectors of the Hessian and are the new parameters.
My questions are: In theory, would parameterization in terms of the eigenvectors be effective in improving the conditioning of the problem? If so, is this approach compatible with the presence of bounds and linear constraints on the parameters?
Thank you! optimization, interpolation, scaling, fmincon MATLAB Answers — New Questions
How do I name a variable in Simulink so that I can later use it to compute a value, such as sin(psi) or cos(phi) or tan(theta).
How do I name a variable in simulink so that i can later use it to compute a value based on it, such sin(psi) or cos(phi) or tan(theta)?How do I name a variable in simulink so that i can later use it to compute a value based on it, such sin(psi) or cos(phi) or tan(theta)? How do I name a variable in simulink so that i can later use it to compute a value based on it, such sin(psi) or cos(phi) or tan(theta)? simulink names variables MATLAB Answers — New Questions
How to use fzero with arrayfun or cell fun?
Hi there,
I have the piece of code that you see at the bottom. In short,
I have a function whose form I don’t know but I know it is smooth and I can interpolated it.
I create a function function that accepts a cell as an input and has 2 variables.
I create a new function to three variables, the previous 2 + 1, so that I can minimise it useing fzero
I would like to use arrayfun or cellfun (or any other trick) to evaluate fzero over several pairs of inputs all at once to avoid looping.
I would appreciate if someone could put me on the right track.
miny = setting.Y.miny;
maxy = y(end);
xrep = reshape(repmat(x’, [y_sz 1]),[x_sz*y_sz 1]);
yrep = repmat(y, [x_sz 1]);
xy = mat2cell(num2cell([xrep yrep]), ones([x_sz*y_sz 1]), 2);
Fmin_bar = MW_mw.Fmin_bar;
Smin = griddedInterpolant({x,y},MW_mw.S_xy_min,"linear","spline");
dSdy =@(c) (Smin({c{1},c{2}+1e-9})-Smin(c))./1e-9.*MS_tilde_f(c{:});
t_thres =@(t,c) dSdy(c) – c{1}./(r+delta+s.*lamb_min.*Fmin_bar(t));d
tr = fzero(@(t) t_thres(t,c),[miny maxy*10]);
tr = zeros(4000,1);
tic
for i = 1:4000
z = xy{i,:};
try
tr(i) = fzero(@(t) t_thres(t,z),[miny maxy*10]);
catch
tr(i) = NaN;
end
end
Best,
RubenHi there,
I have the piece of code that you see at the bottom. In short,
I have a function whose form I don’t know but I know it is smooth and I can interpolated it.
I create a function function that accepts a cell as an input and has 2 variables.
I create a new function to three variables, the previous 2 + 1, so that I can minimise it useing fzero
I would like to use arrayfun or cellfun (or any other trick) to evaluate fzero over several pairs of inputs all at once to avoid looping.
I would appreciate if someone could put me on the right track.
miny = setting.Y.miny;
maxy = y(end);
xrep = reshape(repmat(x’, [y_sz 1]),[x_sz*y_sz 1]);
yrep = repmat(y, [x_sz 1]);
xy = mat2cell(num2cell([xrep yrep]), ones([x_sz*y_sz 1]), 2);
Fmin_bar = MW_mw.Fmin_bar;
Smin = griddedInterpolant({x,y},MW_mw.S_xy_min,"linear","spline");
dSdy =@(c) (Smin({c{1},c{2}+1e-9})-Smin(c))./1e-9.*MS_tilde_f(c{:});
t_thres =@(t,c) dSdy(c) – c{1}./(r+delta+s.*lamb_min.*Fmin_bar(t));d
tr = fzero(@(t) t_thres(t,c),[miny maxy*10]);
tr = zeros(4000,1);
tic
for i = 1:4000
z = xy{i,:};
try
tr(i) = fzero(@(t) t_thres(t,z),[miny maxy*10]);
catch
tr(i) = NaN;
end
end
Best,
Ruben Hi there,
I have the piece of code that you see at the bottom. In short,
I have a function whose form I don’t know but I know it is smooth and I can interpolated it.
I create a function function that accepts a cell as an input and has 2 variables.
I create a new function to three variables, the previous 2 + 1, so that I can minimise it useing fzero
I would like to use arrayfun or cellfun (or any other trick) to evaluate fzero over several pairs of inputs all at once to avoid looping.
I would appreciate if someone could put me on the right track.
miny = setting.Y.miny;
maxy = y(end);
xrep = reshape(repmat(x’, [y_sz 1]),[x_sz*y_sz 1]);
yrep = repmat(y, [x_sz 1]);
xy = mat2cell(num2cell([xrep yrep]), ones([x_sz*y_sz 1]), 2);
Fmin_bar = MW_mw.Fmin_bar;
Smin = griddedInterpolant({x,y},MW_mw.S_xy_min,"linear","spline");
dSdy =@(c) (Smin({c{1},c{2}+1e-9})-Smin(c))./1e-9.*MS_tilde_f(c{:});
t_thres =@(t,c) dSdy(c) – c{1}./(r+delta+s.*lamb_min.*Fmin_bar(t));d
tr = fzero(@(t) t_thres(t,c),[miny maxy*10]);
tr = zeros(4000,1);
tic
for i = 1:4000
z = xy{i,:};
try
tr(i) = fzero(@(t) t_thres(t,z),[miny maxy*10]);
catch
tr(i) = NaN;
end
end
Best,
Ruben arrayfun, cellfun, fzero MATLAB Answers — New Questions