Category: Matlab
Category Archives: Matlab
How to create a time serie with daily data
Please i am trying to make a time series with daily financial datas.
The datas are observed daily except on weekends.
My main concern is that i am trying to set a moving starting (02 of january 2017) date with the function dattetime but i am having an error message. Please could you tell me what i did wrong?
M
Also , can you tell me how i can account for the weekly two days break in the time series.
RegardsPlease i am trying to make a time series with daily financial datas.
The datas are observed daily except on weekends.
My main concern is that i am trying to set a moving starting (02 of january 2017) date with the function dattetime but i am having an error message. Please could you tell me what i did wrong?
M
Also , can you tell me how i can account for the weekly two days break in the time series.
Regards Please i am trying to make a time series with daily financial datas.
The datas are observed daily except on weekends.
My main concern is that i am trying to set a moving starting (02 of january 2017) date with the function dattetime but i am having an error message. Please could you tell me what i did wrong?
M
Also , can you tell me how i can account for the weekly two days break in the time series.
Regards daily time series MATLAB Answers — New Questions
Intermittent error on Linux: ‘Launching updater executable’
I’m running a piece of code using the following cli commands
matlab -nodisplay -r "scriptname(‘input1’, ‘input2’); quit"
And every so often, when I sun this, it gets stuck on a terminal prompt which states
‘Launching updater executable’I’m running a piece of code using the following cli commands
matlab -nodisplay -r "scriptname(‘input1’, ‘input2’); quit"
And every so often, when I sun this, it gets stuck on a terminal prompt which states
‘Launching updater executable’ I’m running a piece of code using the following cli commands
matlab -nodisplay -r "scriptname(‘input1’, ‘input2’); quit"
And every so often, when I sun this, it gets stuck on a terminal prompt which states
‘Launching updater executable’ matlab, linux MATLAB Answers — New Questions
Connection and Communication Initialization issue with Simulink model(2024b) and Ardupilot through SITL
I have imported a 3D CAD model of a quadcopter into Simulink Multibody and am working to connect the Simulink model to ArduPilot using SITL. To achieve this, I am using an S-Function block that is designed to send input data from Simulink to ArduPilot and receive output data from ArduPilot back into Simulink, forming a closed-loop system.
The model compiles and runs without errors, but it fails to establish a connection or communication with ArduPilot. When I hit the run button, the simulation starts immediately without waiting for ArduPilot to connect. I’m unable to identify why this is happening. The code for my S-Function is attached. Could someone please help me troubleshoot this issue?
#define S_FUNCTION_NAME sil_connector_new1
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
#include <iostream>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include "C:/Users/tihan/Desktop/ardupilot/build/sitl/libraries/GCS_MAVLink/include/mavlink/v2.0/ardupilotmega/mavlink.h"
#pragma comment(lib, "ws2_32.lib")
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 5760
class UDPConnector {
public:
UDPConnector(const char* ip, int port) : server_ip(ip), server_port(port), sockfd(-1) {}
bool initialize() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed with error: " << WSAGetLastError() << std::endl;
return false;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == INVALID_SOCKET) {
std::cerr << "Socket creation failed with error: " << WSAGetLastError() << std::endl;
return false;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
server_addr.sin_addr.s_addr = inet_addr(server_ip);
// Try to connect to SITL
std::cout << "Waiting for ArduPilot SITL connection…" << std::endl;
for (int attempt = 0; attempt < 10; ++attempt) {
if (test_connection()) {
std::cout << "Connection established to ArduPilot SITL on " << server_ip << ":" << server_port << std::endl;
return true;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cerr << "Failed to establish connection to ArduPilot SITL." << std::endl;
return false;
}
bool send_message(const uint8_t* buffer, size_t length) {
if (sendto(sockfd, (const char*)buffer, length, 0, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
std::cerr << "Failed to send message with error: " << WSAGetLastError() << std::endl;
return false;
}
return true;
}
~UDPConnector() {
if (sockfd != INVALID_SOCKET) {
closesocket(sockfd);
}
WSACleanup();
}
private:
const char* server_ip;
int server_port;
SOCKET sockfd;
struct sockaddr_in server_addr;
bool test_connection() {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
// Send a heartbeat message to test the connection
mavlink_msg_heartbeat_pack(1, 200, &msg, MAV_TYPE_ONBOARD_CONTROLLER, MAV_AUTOPILOT_INVALID, 0, 0, 0);
size_t len = mavlink_msg_to_send_buffer(buf, &msg);
if (!send_message(buf, len)) {
return false;
}
// Non-blocking receive to verify response
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
if (select(0, &readfds, NULL, NULL, &timeout) > 0) {
char recv_buf[1024];
int recv_len = recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, NULL, NULL);
if (recv_len > 0) {
std::cout << "Heartbeat received from SITL." << std::endl;
return true;
}
}
return false;
}
};
UDPConnector connector(SERVER_IP, SERVER_PORT);
void wait_for_ardupilot_connection(SimStruct *S) {
// Wait for connection with ArduPilot
if (!connector.initialize()) {
ssSetErrorStatus(S, "Unable to establish UDP connection to ArduPilot SITL.");
return;
}
}
void mdlInitializeSizes(SimStruct *S) {
ssSetNumInputPorts(S, 7); // 7 inputs: 6 vectors + 1 constant (time)
ssSetNumOutputPorts(S, 4); // 4 outputs for the 4 motor PWM signals
// 6 input ports for sensor data as [1×3] vectors
for (int i = 0; i < 6; ++i) { // 6 inputs for acceleration, gyro, position, velocity, attitude, magnetometer
ssSetInputPortWidth(S, i, 3); // Each sensor input is a [1×3] vector
ssSetInputPortDirectFeedThrough(S, i, 1); // Declare direct feedthrough
}
// Time input (constant scalar)
ssSetInputPortWidth(S, 6, 1); // Time as constant (scalar)
ssSetInputPortDirectFeedThrough(S, 6, 1); // Declare direct feedthrough for time input
// 4 output ports for motor PWM signals
for (int i = 0; i < 4; ++i) {
ssSetOutputPortWidth(S, i, 1); // Output for each motor PWM signal
}
ssSetNumSampleTimes(S, 1);
}
void mdlInitializeSampleTimes(SimStruct *S) {
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
}
void mdlStart(SimStruct *S) {
// Initialize the UDP connection to ArduPilot SITL
wait_for_ardupilot_connection(S);
}
void send_mavlink_command(SimStruct *S, uint8_t command, float param1, float param2, float param3) {
mavlink_message_t msg;
uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
// Construct the COMMAND_LONG message
mavlink_msg_command_long_pack(1, 200, &msg, 1, 1, command, 0, param1, param2, param3, 0, 0, 0, 0);
// Send the command to ArduPilot via UDP
uint16_t len = mavlink_msg_to_send_buffer(buffer, &msg);
connector.send_message(buffer, len);
}
void mdlOutputs(SimStruct *S, int_T tid) {
const real_T *accel = ssGetInputPortRealSignal(S, 0); // [1×3] vector for acceleration
const real_T *gyro = ssGetInputPortRealSignal(S, 1); // [1×3] vector for gyro data
const real_T *position = ssGetInputPortRealSignal(S, 2); // [1×3] vector for position
const real_T *velocity = ssGetInputPortRealSignal(S, 3); // [1×3] vector for velocity
const real_T *attitude = ssGetInputPortRealSignal(S, 4); // [1×3] vector for attitude (phi, theta, psi)
const real_T *mag = ssGetInputPortRealSignal(S, 5); // [1×3] vector for magnetometer data
const real_T *timestamp = ssGetInputPortRealSignal(S, 6); // Scalar for time input (constant)
// Send a "Takeoff" command if requested
if (position[2] < 10.0) { // Check if altitude is below the desired takeoff height (e.g., 10m)
send_mavlink_command(S, MAV_CMD_NAV_TAKEOFF, 0, 10.0, 0); // Takeoff to 10 meters altitude
}
// Send a "Land" command if requested
if (position[2] > 10.0) { // Check if altitude is above the desired landing height (e.g., 10m)
send_mavlink_command(S, MAV_CMD_NAV_LAND, 0, 0, 0); // Land at current location
}
// Send PWM control data to ArduPilot for four motors (adjust as needed)
mavlink_message_t msg;
uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
uint16_t len = mavlink_msg_scaled_imu_pack(1, 200, &msg,
static_cast<uint32_t>(*timestamp),
static_cast<int16_t>(accel[0] * 1000), static_cast<int16_t>(accel[1] * 1000), static_cast<int16_t>(accel[2] * 1000),
static_cast<int16_t>(gyro[0] * 1000), static_cast<int16_t>(gyro[1] * 1000), static_cast<int16_t>(gyro[2] * 1000),
static_cast<int16_t>(mag[0] * 1000), static_cast<int16_t>(mag[1] * 1000), static_cast<int16_t>(mag[2] * 1000),
0); // Default temperature value of 0
len = mavlink_msg_to_send_buffer(buffer, &msg);
connector.send_message(buffer, len);
// Receive PWM signals for all four motors from ArduPilot
int pwm_signal[4] = {0, 0, 0, 0}; // Array to hold PWM signals for four motors
int ret = recvfrom(connector.sockfd, (char *)pwm_signal, sizeof(pwm_signal), 0, NULL, NULL);
if (ret > 0) {
real_T *output_pwm1 = ssGetOutputPortRealSignal(S, 0);
real_T *output_pwm2 = ssGetOutputPortRealSignal(S, 1);
real_T *output_pwm3 = ssGetOutputPortRealSignal(S, 2);
real_T *output_pwm4 = ssGetOutputPortRealSignal(S, 3);
// Map PWM signals for each motor to angular velocities
double min_pwm = 1000.0;
double max_pwm = 2000.0;
double min_angular_velocity = 0.0; // Minimum angular velocity (0 rad/s)
double max_angular_velocity = 10.0; // Maximum angular velocity (10 rad/s)
// Map each PWM signal to an angular velocity
*output_pwm1 = min_angular_velocity + (pwm_signal[0] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm2 = min_angular_velocity + (pwm_signal[1] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm3 = min_angular_velocity + (pwm_signal[2] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm4 = min_angular_velocity + (pwm_signal[3] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
}
}
void mdlTerminate(SimStruct *S) {
connector.~UDPConnector();
}
#ifdef MATLAB_MEX_FILE
#include "simulink.c"
#else
#include "cg_sfun.h"
#endifI have imported a 3D CAD model of a quadcopter into Simulink Multibody and am working to connect the Simulink model to ArduPilot using SITL. To achieve this, I am using an S-Function block that is designed to send input data from Simulink to ArduPilot and receive output data from ArduPilot back into Simulink, forming a closed-loop system.
The model compiles and runs without errors, but it fails to establish a connection or communication with ArduPilot. When I hit the run button, the simulation starts immediately without waiting for ArduPilot to connect. I’m unable to identify why this is happening. The code for my S-Function is attached. Could someone please help me troubleshoot this issue?
#define S_FUNCTION_NAME sil_connector_new1
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
#include <iostream>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include "C:/Users/tihan/Desktop/ardupilot/build/sitl/libraries/GCS_MAVLink/include/mavlink/v2.0/ardupilotmega/mavlink.h"
#pragma comment(lib, "ws2_32.lib")
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 5760
class UDPConnector {
public:
UDPConnector(const char* ip, int port) : server_ip(ip), server_port(port), sockfd(-1) {}
bool initialize() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed with error: " << WSAGetLastError() << std::endl;
return false;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == INVALID_SOCKET) {
std::cerr << "Socket creation failed with error: " << WSAGetLastError() << std::endl;
return false;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
server_addr.sin_addr.s_addr = inet_addr(server_ip);
// Try to connect to SITL
std::cout << "Waiting for ArduPilot SITL connection…" << std::endl;
for (int attempt = 0; attempt < 10; ++attempt) {
if (test_connection()) {
std::cout << "Connection established to ArduPilot SITL on " << server_ip << ":" << server_port << std::endl;
return true;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cerr << "Failed to establish connection to ArduPilot SITL." << std::endl;
return false;
}
bool send_message(const uint8_t* buffer, size_t length) {
if (sendto(sockfd, (const char*)buffer, length, 0, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
std::cerr << "Failed to send message with error: " << WSAGetLastError() << std::endl;
return false;
}
return true;
}
~UDPConnector() {
if (sockfd != INVALID_SOCKET) {
closesocket(sockfd);
}
WSACleanup();
}
private:
const char* server_ip;
int server_port;
SOCKET sockfd;
struct sockaddr_in server_addr;
bool test_connection() {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
// Send a heartbeat message to test the connection
mavlink_msg_heartbeat_pack(1, 200, &msg, MAV_TYPE_ONBOARD_CONTROLLER, MAV_AUTOPILOT_INVALID, 0, 0, 0);
size_t len = mavlink_msg_to_send_buffer(buf, &msg);
if (!send_message(buf, len)) {
return false;
}
// Non-blocking receive to verify response
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
if (select(0, &readfds, NULL, NULL, &timeout) > 0) {
char recv_buf[1024];
int recv_len = recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, NULL, NULL);
if (recv_len > 0) {
std::cout << "Heartbeat received from SITL." << std::endl;
return true;
}
}
return false;
}
};
UDPConnector connector(SERVER_IP, SERVER_PORT);
void wait_for_ardupilot_connection(SimStruct *S) {
// Wait for connection with ArduPilot
if (!connector.initialize()) {
ssSetErrorStatus(S, "Unable to establish UDP connection to ArduPilot SITL.");
return;
}
}
void mdlInitializeSizes(SimStruct *S) {
ssSetNumInputPorts(S, 7); // 7 inputs: 6 vectors + 1 constant (time)
ssSetNumOutputPorts(S, 4); // 4 outputs for the 4 motor PWM signals
// 6 input ports for sensor data as [1×3] vectors
for (int i = 0; i < 6; ++i) { // 6 inputs for acceleration, gyro, position, velocity, attitude, magnetometer
ssSetInputPortWidth(S, i, 3); // Each sensor input is a [1×3] vector
ssSetInputPortDirectFeedThrough(S, i, 1); // Declare direct feedthrough
}
// Time input (constant scalar)
ssSetInputPortWidth(S, 6, 1); // Time as constant (scalar)
ssSetInputPortDirectFeedThrough(S, 6, 1); // Declare direct feedthrough for time input
// 4 output ports for motor PWM signals
for (int i = 0; i < 4; ++i) {
ssSetOutputPortWidth(S, i, 1); // Output for each motor PWM signal
}
ssSetNumSampleTimes(S, 1);
}
void mdlInitializeSampleTimes(SimStruct *S) {
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
}
void mdlStart(SimStruct *S) {
// Initialize the UDP connection to ArduPilot SITL
wait_for_ardupilot_connection(S);
}
void send_mavlink_command(SimStruct *S, uint8_t command, float param1, float param2, float param3) {
mavlink_message_t msg;
uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
// Construct the COMMAND_LONG message
mavlink_msg_command_long_pack(1, 200, &msg, 1, 1, command, 0, param1, param2, param3, 0, 0, 0, 0);
// Send the command to ArduPilot via UDP
uint16_t len = mavlink_msg_to_send_buffer(buffer, &msg);
connector.send_message(buffer, len);
}
void mdlOutputs(SimStruct *S, int_T tid) {
const real_T *accel = ssGetInputPortRealSignal(S, 0); // [1×3] vector for acceleration
const real_T *gyro = ssGetInputPortRealSignal(S, 1); // [1×3] vector for gyro data
const real_T *position = ssGetInputPortRealSignal(S, 2); // [1×3] vector for position
const real_T *velocity = ssGetInputPortRealSignal(S, 3); // [1×3] vector for velocity
const real_T *attitude = ssGetInputPortRealSignal(S, 4); // [1×3] vector for attitude (phi, theta, psi)
const real_T *mag = ssGetInputPortRealSignal(S, 5); // [1×3] vector for magnetometer data
const real_T *timestamp = ssGetInputPortRealSignal(S, 6); // Scalar for time input (constant)
// Send a "Takeoff" command if requested
if (position[2] < 10.0) { // Check if altitude is below the desired takeoff height (e.g., 10m)
send_mavlink_command(S, MAV_CMD_NAV_TAKEOFF, 0, 10.0, 0); // Takeoff to 10 meters altitude
}
// Send a "Land" command if requested
if (position[2] > 10.0) { // Check if altitude is above the desired landing height (e.g., 10m)
send_mavlink_command(S, MAV_CMD_NAV_LAND, 0, 0, 0); // Land at current location
}
// Send PWM control data to ArduPilot for four motors (adjust as needed)
mavlink_message_t msg;
uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
uint16_t len = mavlink_msg_scaled_imu_pack(1, 200, &msg,
static_cast<uint32_t>(*timestamp),
static_cast<int16_t>(accel[0] * 1000), static_cast<int16_t>(accel[1] * 1000), static_cast<int16_t>(accel[2] * 1000),
static_cast<int16_t>(gyro[0] * 1000), static_cast<int16_t>(gyro[1] * 1000), static_cast<int16_t>(gyro[2] * 1000),
static_cast<int16_t>(mag[0] * 1000), static_cast<int16_t>(mag[1] * 1000), static_cast<int16_t>(mag[2] * 1000),
0); // Default temperature value of 0
len = mavlink_msg_to_send_buffer(buffer, &msg);
connector.send_message(buffer, len);
// Receive PWM signals for all four motors from ArduPilot
int pwm_signal[4] = {0, 0, 0, 0}; // Array to hold PWM signals for four motors
int ret = recvfrom(connector.sockfd, (char *)pwm_signal, sizeof(pwm_signal), 0, NULL, NULL);
if (ret > 0) {
real_T *output_pwm1 = ssGetOutputPortRealSignal(S, 0);
real_T *output_pwm2 = ssGetOutputPortRealSignal(S, 1);
real_T *output_pwm3 = ssGetOutputPortRealSignal(S, 2);
real_T *output_pwm4 = ssGetOutputPortRealSignal(S, 3);
// Map PWM signals for each motor to angular velocities
double min_pwm = 1000.0;
double max_pwm = 2000.0;
double min_angular_velocity = 0.0; // Minimum angular velocity (0 rad/s)
double max_angular_velocity = 10.0; // Maximum angular velocity (10 rad/s)
// Map each PWM signal to an angular velocity
*output_pwm1 = min_angular_velocity + (pwm_signal[0] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm2 = min_angular_velocity + (pwm_signal[1] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm3 = min_angular_velocity + (pwm_signal[2] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm4 = min_angular_velocity + (pwm_signal[3] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
}
}
void mdlTerminate(SimStruct *S) {
connector.~UDPConnector();
}
#ifdef MATLAB_MEX_FILE
#include "simulink.c"
#else
#include "cg_sfun.h"
#endif I have imported a 3D CAD model of a quadcopter into Simulink Multibody and am working to connect the Simulink model to ArduPilot using SITL. To achieve this, I am using an S-Function block that is designed to send input data from Simulink to ArduPilot and receive output data from ArduPilot back into Simulink, forming a closed-loop system.
The model compiles and runs without errors, but it fails to establish a connection or communication with ArduPilot. When I hit the run button, the simulation starts immediately without waiting for ArduPilot to connect. I’m unable to identify why this is happening. The code for my S-Function is attached. Could someone please help me troubleshoot this issue?
#define S_FUNCTION_NAME sil_connector_new1
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
#include <iostream>
#include <winsock2.h>
#include <Ws2tcpip.h>
#include "C:/Users/tihan/Desktop/ardupilot/build/sitl/libraries/GCS_MAVLink/include/mavlink/v2.0/ardupilotmega/mavlink.h"
#pragma comment(lib, "ws2_32.lib")
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 5760
class UDPConnector {
public:
UDPConnector(const char* ip, int port) : server_ip(ip), server_port(port), sockfd(-1) {}
bool initialize() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed with error: " << WSAGetLastError() << std::endl;
return false;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == INVALID_SOCKET) {
std::cerr << "Socket creation failed with error: " << WSAGetLastError() << std::endl;
return false;
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
server_addr.sin_addr.s_addr = inet_addr(server_ip);
// Try to connect to SITL
std::cout << "Waiting for ArduPilot SITL connection…" << std::endl;
for (int attempt = 0; attempt < 10; ++attempt) {
if (test_connection()) {
std::cout << "Connection established to ArduPilot SITL on " << server_ip << ":" << server_port << std::endl;
return true;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cerr << "Failed to establish connection to ArduPilot SITL." << std::endl;
return false;
}
bool send_message(const uint8_t* buffer, size_t length) {
if (sendto(sockfd, (const char*)buffer, length, 0, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
std::cerr << "Failed to send message with error: " << WSAGetLastError() << std::endl;
return false;
}
return true;
}
~UDPConnector() {
if (sockfd != INVALID_SOCKET) {
closesocket(sockfd);
}
WSACleanup();
}
private:
const char* server_ip;
int server_port;
SOCKET sockfd;
struct sockaddr_in server_addr;
bool test_connection() {
mavlink_message_t msg;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
// Send a heartbeat message to test the connection
mavlink_msg_heartbeat_pack(1, 200, &msg, MAV_TYPE_ONBOARD_CONTROLLER, MAV_AUTOPILOT_INVALID, 0, 0, 0);
size_t len = mavlink_msg_to_send_buffer(buf, &msg);
if (!send_message(buf, len)) {
return false;
}
// Non-blocking receive to verify response
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(sockfd, &readfds);
struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
if (select(0, &readfds, NULL, NULL, &timeout) > 0) {
char recv_buf[1024];
int recv_len = recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, NULL, NULL);
if (recv_len > 0) {
std::cout << "Heartbeat received from SITL." << std::endl;
return true;
}
}
return false;
}
};
UDPConnector connector(SERVER_IP, SERVER_PORT);
void wait_for_ardupilot_connection(SimStruct *S) {
// Wait for connection with ArduPilot
if (!connector.initialize()) {
ssSetErrorStatus(S, "Unable to establish UDP connection to ArduPilot SITL.");
return;
}
}
void mdlInitializeSizes(SimStruct *S) {
ssSetNumInputPorts(S, 7); // 7 inputs: 6 vectors + 1 constant (time)
ssSetNumOutputPorts(S, 4); // 4 outputs for the 4 motor PWM signals
// 6 input ports for sensor data as [1×3] vectors
for (int i = 0; i < 6; ++i) { // 6 inputs for acceleration, gyro, position, velocity, attitude, magnetometer
ssSetInputPortWidth(S, i, 3); // Each sensor input is a [1×3] vector
ssSetInputPortDirectFeedThrough(S, i, 1); // Declare direct feedthrough
}
// Time input (constant scalar)
ssSetInputPortWidth(S, 6, 1); // Time as constant (scalar)
ssSetInputPortDirectFeedThrough(S, 6, 1); // Declare direct feedthrough for time input
// 4 output ports for motor PWM signals
for (int i = 0; i < 4; ++i) {
ssSetOutputPortWidth(S, i, 1); // Output for each motor PWM signal
}
ssSetNumSampleTimes(S, 1);
}
void mdlInitializeSampleTimes(SimStruct *S) {
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
}
void mdlStart(SimStruct *S) {
// Initialize the UDP connection to ArduPilot SITL
wait_for_ardupilot_connection(S);
}
void send_mavlink_command(SimStruct *S, uint8_t command, float param1, float param2, float param3) {
mavlink_message_t msg;
uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
// Construct the COMMAND_LONG message
mavlink_msg_command_long_pack(1, 200, &msg, 1, 1, command, 0, param1, param2, param3, 0, 0, 0, 0);
// Send the command to ArduPilot via UDP
uint16_t len = mavlink_msg_to_send_buffer(buffer, &msg);
connector.send_message(buffer, len);
}
void mdlOutputs(SimStruct *S, int_T tid) {
const real_T *accel = ssGetInputPortRealSignal(S, 0); // [1×3] vector for acceleration
const real_T *gyro = ssGetInputPortRealSignal(S, 1); // [1×3] vector for gyro data
const real_T *position = ssGetInputPortRealSignal(S, 2); // [1×3] vector for position
const real_T *velocity = ssGetInputPortRealSignal(S, 3); // [1×3] vector for velocity
const real_T *attitude = ssGetInputPortRealSignal(S, 4); // [1×3] vector for attitude (phi, theta, psi)
const real_T *mag = ssGetInputPortRealSignal(S, 5); // [1×3] vector for magnetometer data
const real_T *timestamp = ssGetInputPortRealSignal(S, 6); // Scalar for time input (constant)
// Send a "Takeoff" command if requested
if (position[2] < 10.0) { // Check if altitude is below the desired takeoff height (e.g., 10m)
send_mavlink_command(S, MAV_CMD_NAV_TAKEOFF, 0, 10.0, 0); // Takeoff to 10 meters altitude
}
// Send a "Land" command if requested
if (position[2] > 10.0) { // Check if altitude is above the desired landing height (e.g., 10m)
send_mavlink_command(S, MAV_CMD_NAV_LAND, 0, 0, 0); // Land at current location
}
// Send PWM control data to ArduPilot for four motors (adjust as needed)
mavlink_message_t msg;
uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
uint16_t len = mavlink_msg_scaled_imu_pack(1, 200, &msg,
static_cast<uint32_t>(*timestamp),
static_cast<int16_t>(accel[0] * 1000), static_cast<int16_t>(accel[1] * 1000), static_cast<int16_t>(accel[2] * 1000),
static_cast<int16_t>(gyro[0] * 1000), static_cast<int16_t>(gyro[1] * 1000), static_cast<int16_t>(gyro[2] * 1000),
static_cast<int16_t>(mag[0] * 1000), static_cast<int16_t>(mag[1] * 1000), static_cast<int16_t>(mag[2] * 1000),
0); // Default temperature value of 0
len = mavlink_msg_to_send_buffer(buffer, &msg);
connector.send_message(buffer, len);
// Receive PWM signals for all four motors from ArduPilot
int pwm_signal[4] = {0, 0, 0, 0}; // Array to hold PWM signals for four motors
int ret = recvfrom(connector.sockfd, (char *)pwm_signal, sizeof(pwm_signal), 0, NULL, NULL);
if (ret > 0) {
real_T *output_pwm1 = ssGetOutputPortRealSignal(S, 0);
real_T *output_pwm2 = ssGetOutputPortRealSignal(S, 1);
real_T *output_pwm3 = ssGetOutputPortRealSignal(S, 2);
real_T *output_pwm4 = ssGetOutputPortRealSignal(S, 3);
// Map PWM signals for each motor to angular velocities
double min_pwm = 1000.0;
double max_pwm = 2000.0;
double min_angular_velocity = 0.0; // Minimum angular velocity (0 rad/s)
double max_angular_velocity = 10.0; // Maximum angular velocity (10 rad/s)
// Map each PWM signal to an angular velocity
*output_pwm1 = min_angular_velocity + (pwm_signal[0] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm2 = min_angular_velocity + (pwm_signal[1] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm3 = min_angular_velocity + (pwm_signal[2] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
*output_pwm4 = min_angular_velocity + (pwm_signal[3] – min_pwm) * (max_angular_velocity – min_angular_velocity) / (max_pwm – min_pwm);
}
}
void mdlTerminate(SimStruct *S) {
connector.~UDPConnector();
}
#ifdef MATLAB_MEX_FILE
#include "simulink.c"
#else
#include "cg_sfun.h"
#endif initialization, simulink model, ardupilot, s function block, sitl, connection, communicationissue MATLAB Answers — New Questions
Finding axial, radial velocity and core radius of a 3D vortex from PTV data
I have obtained PTV data and would like to calculate various components of the vortex, is there a better code than the one i have used below.Not certain about the accuracy of the code.
% select a CSV file to import
[file, path] = uigetfile(‘*.csv’, ‘Select the CSV file to import’);
if file == 0
return; % user canceled file selection
end
%Load the data from the CSV file
data = readmatrix(fullfile(path, file), ‘HeaderLines’, 1);
% x,y coordinate vectors (mm) and Vx and Vy fields (m/s)
x = data(:, 1);
y = data(:, 2);
z = data(:, 3);
u = data(:, 4);
v = data(:, 5);
w = data(:, 6);
vorticity =data(:,20);
% Example data (replace these with your actual data)
% Example data (replace these with your actual data)
y = linspace(-5, 5, 100) / 1000; % y-coordinates (converted to meters)
z = linspace(-5, 5, 100) / 1000; % z-coordinates (converted to meters)
x = linspace(-5, 5, 100) / 1000; % x-coordinates (converted to meters)
[Y, Z, X] = meshgrid(y, z, x); % Create meshgrid for y, z, x
% Step 1: Calculate the vorticity magnitude
vorticity_magnitude=max(abs(vorticity(:)));
% Step 2: Define the threshold for vortex core (e.g., 10% of max vorticity)
max_vorticity = max(vorticity_magnitude(:));
threshold = 0.1 * max_vorticity; % Threshold for vortex core (10% of max vo
% Step 3: Find the vortex core radius (where vorticity exceeds threshold)
% Compute the radial distance from the center (0, 0, 0)
radius = sqrt(X.^2 + Y.^2 + Z.^2); % Radial distance in 3D
% Identify the region where vorticity exceeds threshold
core_radius = max(radius(vorticity_magnitude >= threshold)); % Vortex core radius
% Step 4: Find the location of maximum vorticity (core of the vortex)
[~, core_idx] = max(vorticity_magnitude(:)); % Find the index of max vorticity
[core_x, core_y, core_z] = ind2sub(size(vorticity_magnitude), core_idx); % Get the coordinates of the core
% Step 5: Radial and Axial Velocities at the vortex core
% The radial velocity is the component of velocity in the direction of the radial vector
% The axial velocity is the component of velocity along the axis of the vortex (e.g., the x-axis)
% Calculate the radial velocity at the core
r_vec = [X(core_x, core_y, core_z), Y(core_x, core_y, core_z), Z(core_x, core_y, core_z)]; % Position vector at core
r_mag = norm(r_vec); % Magnitude of position vector
% Calculate the radial velocity at core
radial_velocity = (u(core_x, core_y, core_z) * r_vec(1) + …
v(core_x, core_y, core_z) * r_vec(2) + …
w(core_x, core_y, core_z) * r_vec(3)) / r_mag; % Dot product of velocity and radial direction
% The axial velocity is the velocity component along the x-axis (assuming the vortex is aligned with the x-axis)
axial_velocity = u(core_x, core_y, core_z); % Axial velocity along x-axis at the core
% Step 6: Find the velocity at the outer boundary (where radius is maximum)
% Find the index at the outermost boundary (max radial distance)
[~, boundary_idx] = min(abs(radius(:) – max(radius(:)))); % Find the outer boundary index
[boundary_x, boundary_y, boundary_z] = ind2sub(size(radius), boundary_idx); % Get boundary coordinates
boundary_velocity = sqrt(u(boundary_x, boundary_y, boundary_z)^2 + v(boundary_x, boundary_y, boundary_z)^2 + w(boundary_x, boundary_y, boundary_z)^2);
% Display Results
fprintf(‘Vortex core radius: %.4f metersn’, core_radius);
fprintf(‘Radial velocity at the core: %.4f m/sn’, radial_velocity);
fprintf(‘Axial velocity at the core: %.4f m/sn’, axial_velocity);
%I have obtained PTV data and would like to calculate various components of the vortex, is there a better code than the one i have used below.Not certain about the accuracy of the code.
% select a CSV file to import
[file, path] = uigetfile(‘*.csv’, ‘Select the CSV file to import’);
if file == 0
return; % user canceled file selection
end
%Load the data from the CSV file
data = readmatrix(fullfile(path, file), ‘HeaderLines’, 1);
% x,y coordinate vectors (mm) and Vx and Vy fields (m/s)
x = data(:, 1);
y = data(:, 2);
z = data(:, 3);
u = data(:, 4);
v = data(:, 5);
w = data(:, 6);
vorticity =data(:,20);
% Example data (replace these with your actual data)
% Example data (replace these with your actual data)
y = linspace(-5, 5, 100) / 1000; % y-coordinates (converted to meters)
z = linspace(-5, 5, 100) / 1000; % z-coordinates (converted to meters)
x = linspace(-5, 5, 100) / 1000; % x-coordinates (converted to meters)
[Y, Z, X] = meshgrid(y, z, x); % Create meshgrid for y, z, x
% Step 1: Calculate the vorticity magnitude
vorticity_magnitude=max(abs(vorticity(:)));
% Step 2: Define the threshold for vortex core (e.g., 10% of max vorticity)
max_vorticity = max(vorticity_magnitude(:));
threshold = 0.1 * max_vorticity; % Threshold for vortex core (10% of max vo
% Step 3: Find the vortex core radius (where vorticity exceeds threshold)
% Compute the radial distance from the center (0, 0, 0)
radius = sqrt(X.^2 + Y.^2 + Z.^2); % Radial distance in 3D
% Identify the region where vorticity exceeds threshold
core_radius = max(radius(vorticity_magnitude >= threshold)); % Vortex core radius
% Step 4: Find the location of maximum vorticity (core of the vortex)
[~, core_idx] = max(vorticity_magnitude(:)); % Find the index of max vorticity
[core_x, core_y, core_z] = ind2sub(size(vorticity_magnitude), core_idx); % Get the coordinates of the core
% Step 5: Radial and Axial Velocities at the vortex core
% The radial velocity is the component of velocity in the direction of the radial vector
% The axial velocity is the component of velocity along the axis of the vortex (e.g., the x-axis)
% Calculate the radial velocity at the core
r_vec = [X(core_x, core_y, core_z), Y(core_x, core_y, core_z), Z(core_x, core_y, core_z)]; % Position vector at core
r_mag = norm(r_vec); % Magnitude of position vector
% Calculate the radial velocity at core
radial_velocity = (u(core_x, core_y, core_z) * r_vec(1) + …
v(core_x, core_y, core_z) * r_vec(2) + …
w(core_x, core_y, core_z) * r_vec(3)) / r_mag; % Dot product of velocity and radial direction
% The axial velocity is the velocity component along the x-axis (assuming the vortex is aligned with the x-axis)
axial_velocity = u(core_x, core_y, core_z); % Axial velocity along x-axis at the core
% Step 6: Find the velocity at the outer boundary (where radius is maximum)
% Find the index at the outermost boundary (max radial distance)
[~, boundary_idx] = min(abs(radius(:) – max(radius(:)))); % Find the outer boundary index
[boundary_x, boundary_y, boundary_z] = ind2sub(size(radius), boundary_idx); % Get boundary coordinates
boundary_velocity = sqrt(u(boundary_x, boundary_y, boundary_z)^2 + v(boundary_x, boundary_y, boundary_z)^2 + w(boundary_x, boundary_y, boundary_z)^2);
% Display Results
fprintf(‘Vortex core radius: %.4f metersn’, core_radius);
fprintf(‘Radial velocity at the core: %.4f m/sn’, radial_velocity);
fprintf(‘Axial velocity at the core: %.4f m/sn’, axial_velocity);
% I have obtained PTV data and would like to calculate various components of the vortex, is there a better code than the one i have used below.Not certain about the accuracy of the code.
% select a CSV file to import
[file, path] = uigetfile(‘*.csv’, ‘Select the CSV file to import’);
if file == 0
return; % user canceled file selection
end
%Load the data from the CSV file
data = readmatrix(fullfile(path, file), ‘HeaderLines’, 1);
% x,y coordinate vectors (mm) and Vx and Vy fields (m/s)
x = data(:, 1);
y = data(:, 2);
z = data(:, 3);
u = data(:, 4);
v = data(:, 5);
w = data(:, 6);
vorticity =data(:,20);
% Example data (replace these with your actual data)
% Example data (replace these with your actual data)
y = linspace(-5, 5, 100) / 1000; % y-coordinates (converted to meters)
z = linspace(-5, 5, 100) / 1000; % z-coordinates (converted to meters)
x = linspace(-5, 5, 100) / 1000; % x-coordinates (converted to meters)
[Y, Z, X] = meshgrid(y, z, x); % Create meshgrid for y, z, x
% Step 1: Calculate the vorticity magnitude
vorticity_magnitude=max(abs(vorticity(:)));
% Step 2: Define the threshold for vortex core (e.g., 10% of max vorticity)
max_vorticity = max(vorticity_magnitude(:));
threshold = 0.1 * max_vorticity; % Threshold for vortex core (10% of max vo
% Step 3: Find the vortex core radius (where vorticity exceeds threshold)
% Compute the radial distance from the center (0, 0, 0)
radius = sqrt(X.^2 + Y.^2 + Z.^2); % Radial distance in 3D
% Identify the region where vorticity exceeds threshold
core_radius = max(radius(vorticity_magnitude >= threshold)); % Vortex core radius
% Step 4: Find the location of maximum vorticity (core of the vortex)
[~, core_idx] = max(vorticity_magnitude(:)); % Find the index of max vorticity
[core_x, core_y, core_z] = ind2sub(size(vorticity_magnitude), core_idx); % Get the coordinates of the core
% Step 5: Radial and Axial Velocities at the vortex core
% The radial velocity is the component of velocity in the direction of the radial vector
% The axial velocity is the component of velocity along the axis of the vortex (e.g., the x-axis)
% Calculate the radial velocity at the core
r_vec = [X(core_x, core_y, core_z), Y(core_x, core_y, core_z), Z(core_x, core_y, core_z)]; % Position vector at core
r_mag = norm(r_vec); % Magnitude of position vector
% Calculate the radial velocity at core
radial_velocity = (u(core_x, core_y, core_z) * r_vec(1) + …
v(core_x, core_y, core_z) * r_vec(2) + …
w(core_x, core_y, core_z) * r_vec(3)) / r_mag; % Dot product of velocity and radial direction
% The axial velocity is the velocity component along the x-axis (assuming the vortex is aligned with the x-axis)
axial_velocity = u(core_x, core_y, core_z); % Axial velocity along x-axis at the core
% Step 6: Find the velocity at the outer boundary (where radius is maximum)
% Find the index at the outermost boundary (max radial distance)
[~, boundary_idx] = min(abs(radius(:) – max(radius(:)))); % Find the outer boundary index
[boundary_x, boundary_y, boundary_z] = ind2sub(size(radius), boundary_idx); % Get boundary coordinates
boundary_velocity = sqrt(u(boundary_x, boundary_y, boundary_z)^2 + v(boundary_x, boundary_y, boundary_z)^2 + w(boundary_x, boundary_y, boundary_z)^2);
% Display Results
fprintf(‘Vortex core radius: %.4f metersn’, core_radius);
fprintf(‘Radial velocity at the core: %.4f m/sn’, radial_velocity);
fprintf(‘Axial velocity at the core: %.4f m/sn’, axial_velocity);
% 3d vortex, ptv, matlab MATLAB Answers — New Questions
how do I implement a real time FFT in simulink?
I need to implement a real time FFT of the signal in the attached simulink model in order to detect the frequency and phase of the highest peak (it’s a single sinusoid, so it shouldn’t be an issue). As you can see, I’ve set the simulation step to 1/48000. I would like the detection update rate to be 40Hz, so the FFT is run 40 times a second. I’d like the FFT to be run on the newest samples (i.e. 48000/40) plus an overlap of 50% of the previous set (48000/80), so in other words, the latest 1800 samples. I’d like to zero pad this up to the next power of 2.
I was trying to figure out how to do a FIFO buffer that saves the last 1800 samples, but I couldn’t figure that out, and I couldn’t advance past that stage.
In case it helps, here’s what I have:
Simulink Version 24.2 (R2024b)
Control System Toolbox Version 24.2 (R2024b)
DSP System Toolbox Version 24.2 (R2024b)
Optimization Toolbox Version 24.2 (R2024b)
Signal Processing Toolbox Version 24.2 (R2024b)
Stateflow Version 24.2 (R2024b)
Statistics and Machine Learning Toolbox Version 24.2 (R2024b)
Thanks in advance
-BastianI need to implement a real time FFT of the signal in the attached simulink model in order to detect the frequency and phase of the highest peak (it’s a single sinusoid, so it shouldn’t be an issue). As you can see, I’ve set the simulation step to 1/48000. I would like the detection update rate to be 40Hz, so the FFT is run 40 times a second. I’d like the FFT to be run on the newest samples (i.e. 48000/40) plus an overlap of 50% of the previous set (48000/80), so in other words, the latest 1800 samples. I’d like to zero pad this up to the next power of 2.
I was trying to figure out how to do a FIFO buffer that saves the last 1800 samples, but I couldn’t figure that out, and I couldn’t advance past that stage.
In case it helps, here’s what I have:
Simulink Version 24.2 (R2024b)
Control System Toolbox Version 24.2 (R2024b)
DSP System Toolbox Version 24.2 (R2024b)
Optimization Toolbox Version 24.2 (R2024b)
Signal Processing Toolbox Version 24.2 (R2024b)
Stateflow Version 24.2 (R2024b)
Statistics and Machine Learning Toolbox Version 24.2 (R2024b)
Thanks in advance
-Bastian I need to implement a real time FFT of the signal in the attached simulink model in order to detect the frequency and phase of the highest peak (it’s a single sinusoid, so it shouldn’t be an issue). As you can see, I’ve set the simulation step to 1/48000. I would like the detection update rate to be 40Hz, so the FFT is run 40 times a second. I’d like the FFT to be run on the newest samples (i.e. 48000/40) plus an overlap of 50% of the previous set (48000/80), so in other words, the latest 1800 samples. I’d like to zero pad this up to the next power of 2.
I was trying to figure out how to do a FIFO buffer that saves the last 1800 samples, but I couldn’t figure that out, and I couldn’t advance past that stage.
In case it helps, here’s what I have:
Simulink Version 24.2 (R2024b)
Control System Toolbox Version 24.2 (R2024b)
DSP System Toolbox Version 24.2 (R2024b)
Optimization Toolbox Version 24.2 (R2024b)
Signal Processing Toolbox Version 24.2 (R2024b)
Stateflow Version 24.2 (R2024b)
Statistics and Machine Learning Toolbox Version 24.2 (R2024b)
Thanks in advance
-Bastian fft MATLAB Answers — New Questions
How to calculate only several frequency with FFT ?
Almost all cases, 1st, use FFT2 transfer to frequency field all , then to analysis like filter.
If I know only some frequecy are need,
Is it possible to calculate only several frequency not all frequencies with FFT ?
If OK, How to do?
for example, if ther are 512 data points, then will get 512 data points at frequency field, but I only need 0~50Hz,
How to tall FFT no need to calculated those dat more than 50Hz ?
Like sparse , but not source dat sparse, is the transfer tanget is sparse .Almost all cases, 1st, use FFT2 transfer to frequency field all , then to analysis like filter.
If I know only some frequecy are need,
Is it possible to calculate only several frequency not all frequencies with FFT ?
If OK, How to do?
for example, if ther are 512 data points, then will get 512 data points at frequency field, but I only need 0~50Hz,
How to tall FFT no need to calculated those dat more than 50Hz ?
Like sparse , but not source dat sparse, is the transfer tanget is sparse . Almost all cases, 1st, use FFT2 transfer to frequency field all , then to analysis like filter.
If I know only some frequecy are need,
Is it possible to calculate only several frequency not all frequencies with FFT ?
If OK, How to do?
for example, if ther are 512 data points, then will get 512 data points at frequency field, but I only need 0~50Hz,
How to tall FFT no need to calculated those dat more than 50Hz ?
Like sparse , but not source dat sparse, is the transfer tanget is sparse . fft, sparse MATLAB Answers — New Questions
Effect of prediction horizon on objective cost in “Landing Rocket With MPC Example”
The Matlab example "Landing a Vehicle Using Multistage Nonlinear MPC" (which can be found here), uses a multistage nonlinear MPC to perform the trajectory optimization and another multistage nonlinear MPC to do the motion control. In the script, the former is called the "planner" and the latter is called the "lander". My question is purely regarding the planner:
Why does the objective cost increase when the prediction horizon (p) increases?
Given the sample time Ts and prediction horizon p, the prediction time becomes Ts*p. Here are three configurations with their output from the fmincon() function that resides in the nlmpcmove() function. Except the values for Ts and p, all code is similar to the Matlab example given here.
Ts = 0.2; pPlanner = 45; leads to Objective cost = 445.5349
Ts = 0.2; pPlanner = 50; leads to Objective cost = 492.9689
Ts = 0.2; pPlanner = 55; leads to Objective cost = 541.1668
To my understanding, a larger prediction horizon should give room to a more optimized result. Suppose the ideal trajectory takes Ts*p = 0.2*45 = 9 seconds. Why would the configuration with 50 seconds not lead to the exact same results?
The answers is probably related to how the nlmpcmove() function uses the user provided cost function and terminal state to converge to a solution. What is the math behind this convergence?
I’m using Matlab R2021b. Related Toolboxes are: Model Predictive Control Toolbox and Optimization Toolbox.The Matlab example "Landing a Vehicle Using Multistage Nonlinear MPC" (which can be found here), uses a multistage nonlinear MPC to perform the trajectory optimization and another multistage nonlinear MPC to do the motion control. In the script, the former is called the "planner" and the latter is called the "lander". My question is purely regarding the planner:
Why does the objective cost increase when the prediction horizon (p) increases?
Given the sample time Ts and prediction horizon p, the prediction time becomes Ts*p. Here are three configurations with their output from the fmincon() function that resides in the nlmpcmove() function. Except the values for Ts and p, all code is similar to the Matlab example given here.
Ts = 0.2; pPlanner = 45; leads to Objective cost = 445.5349
Ts = 0.2; pPlanner = 50; leads to Objective cost = 492.9689
Ts = 0.2; pPlanner = 55; leads to Objective cost = 541.1668
To my understanding, a larger prediction horizon should give room to a more optimized result. Suppose the ideal trajectory takes Ts*p = 0.2*45 = 9 seconds. Why would the configuration with 50 seconds not lead to the exact same results?
The answers is probably related to how the nlmpcmove() function uses the user provided cost function and terminal state to converge to a solution. What is the math behind this convergence?
I’m using Matlab R2021b. Related Toolboxes are: Model Predictive Control Toolbox and Optimization Toolbox. The Matlab example "Landing a Vehicle Using Multistage Nonlinear MPC" (which can be found here), uses a multistage nonlinear MPC to perform the trajectory optimization and another multistage nonlinear MPC to do the motion control. In the script, the former is called the "planner" and the latter is called the "lander". My question is purely regarding the planner:
Why does the objective cost increase when the prediction horizon (p) increases?
Given the sample time Ts and prediction horizon p, the prediction time becomes Ts*p. Here are three configurations with their output from the fmincon() function that resides in the nlmpcmove() function. Except the values for Ts and p, all code is similar to the Matlab example given here.
Ts = 0.2; pPlanner = 45; leads to Objective cost = 445.5349
Ts = 0.2; pPlanner = 50; leads to Objective cost = 492.9689
Ts = 0.2; pPlanner = 55; leads to Objective cost = 541.1668
To my understanding, a larger prediction horizon should give room to a more optimized result. Suppose the ideal trajectory takes Ts*p = 0.2*45 = 9 seconds. Why would the configuration with 50 seconds not lead to the exact same results?
The answers is probably related to how the nlmpcmove() function uses the user provided cost function and terminal state to converge to a solution. What is the math behind this convergence?
I’m using Matlab R2021b. Related Toolboxes are: Model Predictive Control Toolbox and Optimization Toolbox. multistage nonlinear model predictive controller, landing rocket with mpc example MATLAB Answers — New Questions
Issue with Adaptive MPC in Simulink Using Online Pure Pursuit for Reference Path Generation
Hi there 🙂
I am facing an issue with my Simulink model, where an adaptive MPC controls the longitudinal and lateral dynamics of a vehicle with all-wheel steering and all-wheel drive. The MPC uses future reference values over the next 10 simulation steps within its prediction horizon. These reference paths are structured as [10×3] matrices, consisting of X, Y positions and orientation (Psi) in a 2D coordinate system.
Here’s my workflow:
I use a hybrid A* algorithm to generate a global path.
I use Pure Pursuit (PP) to create a local path from the current position to the LookAhead Point. PP runs in a loop 10 times to generate the structure of 10 future points for the MPC at each time step.
When using PP with an initial position that deviates from the global path, it successfully generates a meaningful local path leading to the global path and follows it accurately. If I pass this path offline to the MPC, the controller performs as expected, closely following the path.
Problem:
When I run the PP online in parallel with the MPC, feeding it the current positions from the plant system, I observe a discrepancy:
The PP outputs appear correct and provide reasonable reference suggestions.
However, the MPC seems not to implement these references properly.
Interestingly, the MPC produces different control signals when the reference path is generated online versus offline, even though the data and its structure ([10×3]) are identical in both cases.
Key Observations:
Offline paths work perfectly with the MPC.
Online paths generated by PP lead to unexpected MPC behavior, even though the output of PP looks correct.
Questions:
What could cause the adaptive MPC to behave differently when using online reference paths, despite their structure and data being identical to offline paths?
Are there specific considerations for feeding dynamically generated paths into an adaptive MPC during runtime?
Could this issue be related to timing, delays, or synchronization between the PP and MPC blocks in Simulink?
Any insights, suggestions, or debugging tips would be greatly appreciated!
Many thanks in advance and kind regards,
DanusHi there 🙂
I am facing an issue with my Simulink model, where an adaptive MPC controls the longitudinal and lateral dynamics of a vehicle with all-wheel steering and all-wheel drive. The MPC uses future reference values over the next 10 simulation steps within its prediction horizon. These reference paths are structured as [10×3] matrices, consisting of X, Y positions and orientation (Psi) in a 2D coordinate system.
Here’s my workflow:
I use a hybrid A* algorithm to generate a global path.
I use Pure Pursuit (PP) to create a local path from the current position to the LookAhead Point. PP runs in a loop 10 times to generate the structure of 10 future points for the MPC at each time step.
When using PP with an initial position that deviates from the global path, it successfully generates a meaningful local path leading to the global path and follows it accurately. If I pass this path offline to the MPC, the controller performs as expected, closely following the path.
Problem:
When I run the PP online in parallel with the MPC, feeding it the current positions from the plant system, I observe a discrepancy:
The PP outputs appear correct and provide reasonable reference suggestions.
However, the MPC seems not to implement these references properly.
Interestingly, the MPC produces different control signals when the reference path is generated online versus offline, even though the data and its structure ([10×3]) are identical in both cases.
Key Observations:
Offline paths work perfectly with the MPC.
Online paths generated by PP lead to unexpected MPC behavior, even though the output of PP looks correct.
Questions:
What could cause the adaptive MPC to behave differently when using online reference paths, despite their structure and data being identical to offline paths?
Are there specific considerations for feeding dynamically generated paths into an adaptive MPC during runtime?
Could this issue be related to timing, delays, or synchronization between the PP and MPC blocks in Simulink?
Any insights, suggestions, or debugging tips would be greatly appreciated!
Many thanks in advance and kind regards,
Danus Hi there 🙂
I am facing an issue with my Simulink model, where an adaptive MPC controls the longitudinal and lateral dynamics of a vehicle with all-wheel steering and all-wheel drive. The MPC uses future reference values over the next 10 simulation steps within its prediction horizon. These reference paths are structured as [10×3] matrices, consisting of X, Y positions and orientation (Psi) in a 2D coordinate system.
Here’s my workflow:
I use a hybrid A* algorithm to generate a global path.
I use Pure Pursuit (PP) to create a local path from the current position to the LookAhead Point. PP runs in a loop 10 times to generate the structure of 10 future points for the MPC at each time step.
When using PP with an initial position that deviates from the global path, it successfully generates a meaningful local path leading to the global path and follows it accurately. If I pass this path offline to the MPC, the controller performs as expected, closely following the path.
Problem:
When I run the PP online in parallel with the MPC, feeding it the current positions from the plant system, I observe a discrepancy:
The PP outputs appear correct and provide reasonable reference suggestions.
However, the MPC seems not to implement these references properly.
Interestingly, the MPC produces different control signals when the reference path is generated online versus offline, even though the data and its structure ([10×3]) are identical in both cases.
Key Observations:
Offline paths work perfectly with the MPC.
Online paths generated by PP lead to unexpected MPC behavior, even though the output of PP looks correct.
Questions:
What could cause the adaptive MPC to behave differently when using online reference paths, despite their structure and data being identical to offline paths?
Are there specific considerations for feeding dynamically generated paths into an adaptive MPC during runtime?
Could this issue be related to timing, delays, or synchronization between the PP and MPC blocks in Simulink?
Any insights, suggestions, or debugging tips would be greatly appreciated!
Many thanks in advance and kind regards,
Danus mpc MATLAB Answers — New Questions
Why my PMSM loses Torque suddenly after some time.
So, I have been modelling a EV model based of an article about the Bolt EV using simscape and I got a relatively ok model using the dc motor, but when trying to implement the PMSM I could not get good results from it, with weird torque and current responses. I do not have access to specifics parameters of the PMSM, what makes me suspect that it is the problem, but I am not sure how to estimate that with no access to the hardware to empiracally test it.So, I have been modelling a EV model based of an article about the Bolt EV using simscape and I got a relatively ok model using the dc motor, but when trying to implement the PMSM I could not get good results from it, with weird torque and current responses. I do not have access to specifics parameters of the PMSM, what makes me suspect that it is the problem, but I am not sure how to estimate that with no access to the hardware to empiracally test it. So, I have been modelling a EV model based of an article about the Bolt EV using simscape and I got a relatively ok model using the dc motor, but when trying to implement the PMSM I could not get good results from it, with weird torque and current responses. I do not have access to specifics parameters of the PMSM, what makes me suspect that it is the problem, but I am not sure how to estimate that with no access to the hardware to empiracally test it. simscape, simulink, electric_motor_control MATLAB Answers — New Questions
Generation of a unique library code declaration using Embedded coder
Hello team,
I have a library that is used inside multiple models. I am using Embedded coder to generate the code for these models.
Presently, the code generation for each of these models creates a separate instance of the library and its inside functions. However, to compile the complete software package, the library and its functions should have only one instance. We want only one definition/declaration for the library and its functions without using any additional prefix/suffix.
To avoid multiple function definition/declaration errors and achieve successful compilation, would you please provide a solution to generate a unique library code?Hello team,
I have a library that is used inside multiple models. I am using Embedded coder to generate the code for these models.
Presently, the code generation for each of these models creates a separate instance of the library and its inside functions. However, to compile the complete software package, the library and its functions should have only one instance. We want only one definition/declaration for the library and its functions without using any additional prefix/suffix.
To avoid multiple function definition/declaration errors and achieve successful compilation, would you please provide a solution to generate a unique library code? Hello team,
I have a library that is used inside multiple models. I am using Embedded coder to generate the code for these models.
Presently, the code generation for each of these models creates a separate instance of the library and its inside functions. However, to compile the complete software package, the library and its functions should have only one instance. We want only one definition/declaration for the library and its functions without using any additional prefix/suffix.
To avoid multiple function definition/declaration errors and achieve successful compilation, would you please provide a solution to generate a unique library code? embedded coder, simulink, masked library MATLAB Answers — New Questions
Why am I not getting proper gate signal and voltage
Hello Everyone,
I have been trying to follow the example model "PMSM Velocity Control" where my final objective is to replace the idela converter with parameterized discrete devices. For now, I am using ideal converter, with different reference speed (Drive Cycle, constant, signal editor) and I have tuned the speed and current loops accordingly.
The Sample Time
Control Sample time (TSc) = Tsw/250 (Switching time over 250 samples per switching time)
PWM Sample time (TS) = 1/(10*fsw)
The motor is seem to follow the reference speed correctly, however the generated agte signals are seem to sampled sine wave, between 1 and -1.
The voltage (Phase-phase) and (Phase-to-Nuetral) waveform is quite unusual (my input is 48V)
Although the control loops are tuned and there is very low oscillation in the controlled output, however the phase current has hige distortion which I tried to suppress via low-pass filter.
When I put the parameterized semicondcutor instead of idela converter, the gate are signal are not even generating. A gate driver is used to provide PWM signal form the controller to the N-channel MOSFET.
I am attaching few screenshots and my model, if any could validate the model and provide the guidance regarding aforementioned.
Thank You!Hello Everyone,
I have been trying to follow the example model "PMSM Velocity Control" where my final objective is to replace the idela converter with parameterized discrete devices. For now, I am using ideal converter, with different reference speed (Drive Cycle, constant, signal editor) and I have tuned the speed and current loops accordingly.
The Sample Time
Control Sample time (TSc) = Tsw/250 (Switching time over 250 samples per switching time)
PWM Sample time (TS) = 1/(10*fsw)
The motor is seem to follow the reference speed correctly, however the generated agte signals are seem to sampled sine wave, between 1 and -1.
The voltage (Phase-phase) and (Phase-to-Nuetral) waveform is quite unusual (my input is 48V)
Although the control loops are tuned and there is very low oscillation in the controlled output, however the phase current has hige distortion which I tried to suppress via low-pass filter.
When I put the parameterized semicondcutor instead of idela converter, the gate are signal are not even generating. A gate driver is used to provide PWM signal form the controller to the N-channel MOSFET.
I am attaching few screenshots and my model, if any could validate the model and provide the guidance regarding aforementioned.
Thank You! Hello Everyone,
I have been trying to follow the example model "PMSM Velocity Control" where my final objective is to replace the idela converter with parameterized discrete devices. For now, I am using ideal converter, with different reference speed (Drive Cycle, constant, signal editor) and I have tuned the speed and current loops accordingly.
The Sample Time
Control Sample time (TSc) = Tsw/250 (Switching time over 250 samples per switching time)
PWM Sample time (TS) = 1/(10*fsw)
The motor is seem to follow the reference speed correctly, however the generated agte signals are seem to sampled sine wave, between 1 and -1.
The voltage (Phase-phase) and (Phase-to-Nuetral) waveform is quite unusual (my input is 48V)
Although the control loops are tuned and there is very low oscillation in the controlled output, however the phase current has hige distortion which I tried to suppress via low-pass filter.
When I put the parameterized semicondcutor instead of idela converter, the gate are signal are not even generating. A gate driver is used to provide PWM signal form the controller to the N-channel MOSFET.
I am attaching few screenshots and my model, if any could validate the model and provide the guidance regarding aforementioned.
Thank You! simscape, power_electronics_control MATLAB Answers — New Questions
fsolve with multiple parameters
I have defined a function with 3 inputs that finds the trajectory of a baseball using Euler’s method.
The three inputs are the initial velocity, intial angle, and flag which determines the return.
What I mean by flag is that if it is 0, the function returns the height of the baseball over home plate.
If flag is 1, the function returns the entire trajectory of the baseball (A matrix containing index, position (x,y), and time).
function ret = xyt(v0,theta0,flag)
m = 0.328;
k = 0.01;
g = 32.174;
xhome = 60.5;
spin = 0;
Vx = v0*cosd(theta0);
Vy = v0*sind(theta0);
Traj = [0 0.0 8 0];
for i = 1:(xhome*2)
dVx = (-k/m)*sqrt((Vx.^2)+(Vy.^2));
dVy = ((-k/m)*Vy*sqrt((Vx.^2)+(Vy.^2))-g+(spin/m))/Vx;
Traj(i+1,1) = i;
Traj(i+1,2) = 0.5*i;
Traj(i+1,3) = (0.5*(Vy/Vx))+Traj(i,3);
Traj(i+1,4) = (0.5/Vx)+Traj(i,4);
Vx = Vx+dVx*0.5;
Vy = Vy+dVy*0.5;
end
if flag == 0
ret = Traj((2*xhome)+1,3);
else
ret = Traj;
end
end
However, I want to try and find the initial angle given that the initial velocity is 147 and flag is 0 and the return is 3 (3 feet above homeplate).
I tried this code
v0 = 147;
x0 = 3;
flag = 0;
[x,fval] = fsolve(@(theta) xyt(v0,theta,flag), x0);
However, the return of this
Equation solved.
fsolve completed because the vector of function values is near zero
as measured by the default value of the function tolerance, and
the problem appears regular as measured by the gradient.
<stopping criteria details>
The return is no where near the expected answer which should be around 9.2. Instead the return for x is 6.1420 and the return for fval is extremely small.
Please advise what to do. I don’t fully understand the syntax of fsolve with user defined functions. Thank you.I have defined a function with 3 inputs that finds the trajectory of a baseball using Euler’s method.
The three inputs are the initial velocity, intial angle, and flag which determines the return.
What I mean by flag is that if it is 0, the function returns the height of the baseball over home plate.
If flag is 1, the function returns the entire trajectory of the baseball (A matrix containing index, position (x,y), and time).
function ret = xyt(v0,theta0,flag)
m = 0.328;
k = 0.01;
g = 32.174;
xhome = 60.5;
spin = 0;
Vx = v0*cosd(theta0);
Vy = v0*sind(theta0);
Traj = [0 0.0 8 0];
for i = 1:(xhome*2)
dVx = (-k/m)*sqrt((Vx.^2)+(Vy.^2));
dVy = ((-k/m)*Vy*sqrt((Vx.^2)+(Vy.^2))-g+(spin/m))/Vx;
Traj(i+1,1) = i;
Traj(i+1,2) = 0.5*i;
Traj(i+1,3) = (0.5*(Vy/Vx))+Traj(i,3);
Traj(i+1,4) = (0.5/Vx)+Traj(i,4);
Vx = Vx+dVx*0.5;
Vy = Vy+dVy*0.5;
end
if flag == 0
ret = Traj((2*xhome)+1,3);
else
ret = Traj;
end
end
However, I want to try and find the initial angle given that the initial velocity is 147 and flag is 0 and the return is 3 (3 feet above homeplate).
I tried this code
v0 = 147;
x0 = 3;
flag = 0;
[x,fval] = fsolve(@(theta) xyt(v0,theta,flag), x0);
However, the return of this
Equation solved.
fsolve completed because the vector of function values is near zero
as measured by the default value of the function tolerance, and
the problem appears regular as measured by the gradient.
<stopping criteria details>
The return is no where near the expected answer which should be around 9.2. Instead the return for x is 6.1420 and the return for fval is extremely small.
Please advise what to do. I don’t fully understand the syntax of fsolve with user defined functions. Thank you. I have defined a function with 3 inputs that finds the trajectory of a baseball using Euler’s method.
The three inputs are the initial velocity, intial angle, and flag which determines the return.
What I mean by flag is that if it is 0, the function returns the height of the baseball over home plate.
If flag is 1, the function returns the entire trajectory of the baseball (A matrix containing index, position (x,y), and time).
function ret = xyt(v0,theta0,flag)
m = 0.328;
k = 0.01;
g = 32.174;
xhome = 60.5;
spin = 0;
Vx = v0*cosd(theta0);
Vy = v0*sind(theta0);
Traj = [0 0.0 8 0];
for i = 1:(xhome*2)
dVx = (-k/m)*sqrt((Vx.^2)+(Vy.^2));
dVy = ((-k/m)*Vy*sqrt((Vx.^2)+(Vy.^2))-g+(spin/m))/Vx;
Traj(i+1,1) = i;
Traj(i+1,2) = 0.5*i;
Traj(i+1,3) = (0.5*(Vy/Vx))+Traj(i,3);
Traj(i+1,4) = (0.5/Vx)+Traj(i,4);
Vx = Vx+dVx*0.5;
Vy = Vy+dVy*0.5;
end
if flag == 0
ret = Traj((2*xhome)+1,3);
else
ret = Traj;
end
end
However, I want to try and find the initial angle given that the initial velocity is 147 and flag is 0 and the return is 3 (3 feet above homeplate).
I tried this code
v0 = 147;
x0 = 3;
flag = 0;
[x,fval] = fsolve(@(theta) xyt(v0,theta,flag), x0);
However, the return of this
Equation solved.
fsolve completed because the vector of function values is near zero
as measured by the default value of the function tolerance, and
the problem appears regular as measured by the gradient.
<stopping criteria details>
The return is no where near the expected answer which should be around 9.2. Instead the return for x is 6.1420 and the return for fval is extremely small.
Please advise what to do. I don’t fully understand the syntax of fsolve with user defined functions. Thank you. fsolve, input, function, embedded matlab function MATLAB Answers — New Questions
How to use PID controller from Control System TB in Matlab function of Stateflow?
I want to use PID controller in Stateflow. I made two options (above): Simulink function and Simulink state.
How to use Matlab function, PID from Control System toolbox? This PID is object like transfer function, and I need time series.I want to use PID controller in Stateflow. I made two options (above): Simulink function and Simulink state.
How to use Matlab function, PID from Control System toolbox? This PID is object like transfer function, and I need time series. I want to use PID controller in Stateflow. I made two options (above): Simulink function and Simulink state.
How to use Matlab function, PID from Control System toolbox? This PID is object like transfer function, and I need time series. pid, stateflow, embedded matlab function MATLAB Answers — New Questions
dlhdl.buildProcessor Problem
Hi
I am working on the subject that generate bitstream file.
I read matworks helper but it doesn’t work. I have a so simple question because I’m new this subject.
I have attached a screenshot of the error.
Could you help me please? What is the wrong?
Best Regards,Hi
I am working on the subject that generate bitstream file.
I read matworks helper but it doesn’t work. I have a so simple question because I’m new this subject.
I have attached a screenshot of the error.
Could you help me please? What is the wrong?
Best Regards, Hi
I am working on the subject that generate bitstream file.
I read matworks helper but it doesn’t work. I have a so simple question because I’m new this subject.
I have attached a screenshot of the error.
Could you help me please? What is the wrong?
Best Regards, dlhdl MATLAB Answers — New Questions
why i can not rename the load flow bus block in simulink?
load flow bus blockload flow bus block load flow bus block load flow bus MATLAB Answers — New Questions
Multiframe Image arrays 4-D DICOM
Hello!
I need to work with collections of images related by time or view, such as magnetic resonance imaging (MRI) slices or movie frames. (attached)
I need to get the ROI of the image but in different times.
So, I have a multi frame image (4D uint16 DICOM) with 36 frames and I also have my code but it only shows the sum of the 36 frames…
P.S. It is an image of a 3D SPECT scan I need to check the values of ROI in different times to get the intensities/ countings, so that I can get the curve Activity vs Time.
Could please somebody help me?
%%OPEN MULTI FRAME
image_data =dicomread(‘FLOW001_DS.dcm’);
sum2d = sum(image_data,4);
sum2d=256-sum2d;
imshow(sum2d,[])
%Otsu to the generated image
A=otsu(sum2d,2); % testar com outros valores (3 por exemplo);
%Cany countour to select the ROI
BW1 = edge(A,’Canny’);
imshow(BW1)
%Sum original image+ cany ;
sumf=imadd(sum2d,im2double(BW1).*250);
imshow(sumf,[])
imagesc(sumf)
%binary image
umbral=graythresh(sumf);
imag_bw=im2bw(sumf,umbral);
imshow(imag_bw)
%object identification in image
if true
% code
end
imag_bw_label=bwlabel(imag_bw);
imshow(label2rgb(imag_bw_label));
propriedades= regionprops(imag_bw_label);Hello!
I need to work with collections of images related by time or view, such as magnetic resonance imaging (MRI) slices or movie frames. (attached)
I need to get the ROI of the image but in different times.
So, I have a multi frame image (4D uint16 DICOM) with 36 frames and I also have my code but it only shows the sum of the 36 frames…
P.S. It is an image of a 3D SPECT scan I need to check the values of ROI in different times to get the intensities/ countings, so that I can get the curve Activity vs Time.
Could please somebody help me?
%%OPEN MULTI FRAME
image_data =dicomread(‘FLOW001_DS.dcm’);
sum2d = sum(image_data,4);
sum2d=256-sum2d;
imshow(sum2d,[])
%Otsu to the generated image
A=otsu(sum2d,2); % testar com outros valores (3 por exemplo);
%Cany countour to select the ROI
BW1 = edge(A,’Canny’);
imshow(BW1)
%Sum original image+ cany ;
sumf=imadd(sum2d,im2double(BW1).*250);
imshow(sumf,[])
imagesc(sumf)
%binary image
umbral=graythresh(sumf);
imag_bw=im2bw(sumf,umbral);
imshow(imag_bw)
%object identification in image
if true
% code
end
imag_bw_label=bwlabel(imag_bw);
imshow(label2rgb(imag_bw_label));
propriedades= regionprops(imag_bw_label); Hello!
I need to work with collections of images related by time or view, such as magnetic resonance imaging (MRI) slices or movie frames. (attached)
I need to get the ROI of the image but in different times.
So, I have a multi frame image (4D uint16 DICOM) with 36 frames and I also have my code but it only shows the sum of the 36 frames…
P.S. It is an image of a 3D SPECT scan I need to check the values of ROI in different times to get the intensities/ countings, so that I can get the curve Activity vs Time.
Could please somebody help me?
%%OPEN MULTI FRAME
image_data =dicomread(‘FLOW001_DS.dcm’);
sum2d = sum(image_data,4);
sum2d=256-sum2d;
imshow(sum2d,[])
%Otsu to the generated image
A=otsu(sum2d,2); % testar com outros valores (3 por exemplo);
%Cany countour to select the ROI
BW1 = edge(A,’Canny’);
imshow(BW1)
%Sum original image+ cany ;
sumf=imadd(sum2d,im2double(BW1).*250);
imshow(sumf,[])
imagesc(sumf)
%binary image
umbral=graythresh(sumf);
imag_bw=im2bw(sumf,umbral);
imshow(imag_bw)
%object identification in image
if true
% code
end
imag_bw_label=bwlabel(imag_bw);
imshow(label2rgb(imag_bw_label));
propriedades= regionprops(imag_bw_label); multi frame, dynamic, time MATLAB Answers — New Questions
Algorithm used in los2 function
I am using the los2() function to evaluate line-of-sight between two points. The function indicates that line-of-sight is lost when the elevation of the second point in the AER frame centered on the first point is greater than zero; point values corresponding to an elevation of zero are indicated as being below the horizon.
As far as I understand, all points at or above zero elevation at a particular location should be within line-of-sight from that location; however, this does not appear to agree with the results from los2. Is my understanding of the LOS calculation inaccurate or am I missing something about the way los2 performs its calculation?I am using the los2() function to evaluate line-of-sight between two points. The function indicates that line-of-sight is lost when the elevation of the second point in the AER frame centered on the first point is greater than zero; point values corresponding to an elevation of zero are indicated as being below the horizon.
As far as I understand, all points at or above zero elevation at a particular location should be within line-of-sight from that location; however, this does not appear to agree with the results from los2. Is my understanding of the LOS calculation inaccurate or am I missing something about the way los2 performs its calculation? I am using the los2() function to evaluate line-of-sight between two points. The function indicates that line-of-sight is lost when the elevation of the second point in the AER frame centered on the first point is greater than zero; point values corresponding to an elevation of zero are indicated as being below the horizon.
As far as I understand, all points at or above zero elevation at a particular location should be within line-of-sight from that location; however, this does not appear to agree with the results from los2. Is my understanding of the LOS calculation inaccurate or am I missing something about the way los2 performs its calculation? mapping toolbox, line of sight, los2, earth curvature MATLAB Answers — New Questions
Get only block name from get() function
How can I get only the name of the block without the port number?
I have this line:
blockname_and_portnum = get(line_connection_handler,’SourcePort’);
and it gives me:
Step:1
but I need only Step. I want to get this without any extractBefore functions for code optimization. It is possible to get only block name from the function get()?How can I get only the name of the block without the port number?
I have this line:
blockname_and_portnum = get(line_connection_handler,’SourcePort’);
and it gives me:
Step:1
but I need only Step. I want to get this without any extractBefore functions for code optimization. It is possible to get only block name from the function get()? How can I get only the name of the block without the port number?
I have this line:
blockname_and_portnum = get(line_connection_handler,’SourcePort’);
and it gives me:
Step:1
but I need only Step. I want to get this without any extractBefore functions for code optimization. It is possible to get only block name from the function get()? simulink, get, matlab MATLAB Answers — New Questions
I am using roots command for a complicated equation to find out the roots but in return it is giving me roots command in it . How can I solve this?
I am getting this
root(23*a^6*z^3 – 1075392*a^6*z^2 – 720*a^8*z^2 – 793497600*a^4*z^2 + 17471324160*a^6*z + 17031168*a^8*z – 27648*a^10*z + 4019957268480*a^4*z + 248656057860096*a^2*z + 1111306272768*a^8 + 1117403052244992*a^4 + 12586608230400*a^6 + 1353646080*a^10 + 442368*a^12 – 781755859725189120*a^2 + 961852771978444800, z, 1)^(1/2)
when I used the command
Det=collect(det(A),Rh);
Dc=coeffs(Det,Rh,"All");
Dr=roots(Dc);
Rh and a are my variables and I want the value of Rh in a.
I have tried the command simplify also.I am getting this
root(23*a^6*z^3 – 1075392*a^6*z^2 – 720*a^8*z^2 – 793497600*a^4*z^2 + 17471324160*a^6*z + 17031168*a^8*z – 27648*a^10*z + 4019957268480*a^4*z + 248656057860096*a^2*z + 1111306272768*a^8 + 1117403052244992*a^4 + 12586608230400*a^6 + 1353646080*a^10 + 442368*a^12 – 781755859725189120*a^2 + 961852771978444800, z, 1)^(1/2)
when I used the command
Det=collect(det(A),Rh);
Dc=coeffs(Det,Rh,"All");
Dr=roots(Dc);
Rh and a are my variables and I want the value of Rh in a.
I have tried the command simplify also. I am getting this
root(23*a^6*z^3 – 1075392*a^6*z^2 – 720*a^8*z^2 – 793497600*a^4*z^2 + 17471324160*a^6*z + 17031168*a^8*z – 27648*a^10*z + 4019957268480*a^4*z + 248656057860096*a^2*z + 1111306272768*a^8 + 1117403052244992*a^4 + 12586608230400*a^6 + 1353646080*a^10 + 442368*a^12 – 781755859725189120*a^2 + 961852771978444800, z, 1)^(1/2)
when I used the command
Det=collect(det(A),Rh);
Dc=coeffs(Det,Rh,"All");
Dr=roots(Dc);
Rh and a are my variables and I want the value of Rh in a.
I have tried the command simplify also. roots, simplif MATLAB Answers — New Questions
Function ‘boundary’ not supported for code generation. How to solve this?
Function boundary(), which is used to get the boundary of a set of points, does not support code generation. When I use coder to generate C++ code, error occurs. How to solve this problem?Function boundary(), which is used to get the boundary of a set of points, does not support code generation. When I use coder to generate C++ code, error occurs. How to solve this problem? Function boundary(), which is used to get the boundary of a set of points, does not support code generation. When I use coder to generate C++ code, error occurs. How to solve this problem? boundary, code generation MATLAB Answers — New Questions