Author: PuTI
Function Call Trigger Problem
Outport block must be connected to one of the following blocks: an exported function, a Simulink function, an Initialize/Reset/Terminate function, a Merge or Mux block that is driven by exported functions, or a Ground block.
How can i solve this problem? Thank you.Outport block must be connected to one of the following blocks: an exported function, a Simulink function, an Initialize/Reset/Terminate function, a Merge or Mux block that is driven by exported functions, or a Ground block.
How can i solve this problem? Thank you. Outport block must be connected to one of the following blocks: an exported function, a Simulink function, an Initialize/Reset/Terminate function, a Merge or Mux block that is driven by exported functions, or a Ground block.
How can i solve this problem? Thank you. matlab2024a MATLAB Answers — New Questions
How do I create a game update in a while loop
I have this project for class to make a game and for this game I wanted to add an update feature where every 1/30 seconds it completes a "tick." Basically running a while loop where it starts a timer at the begining, runs some functions, and then waits for the timer to hit 1/30 seconds before looping again to keep the game smooth. I’ve looked into the timer function but haven’t been able to get it to work and I was hoping for some help.I have this project for class to make a game and for this game I wanted to add an update feature where every 1/30 seconds it completes a "tick." Basically running a while loop where it starts a timer at the begining, runs some functions, and then waits for the timer to hit 1/30 seconds before looping again to keep the game smooth. I’ve looked into the timer function but haven’t been able to get it to work and I was hoping for some help. I have this project for class to make a game and for this game I wanted to add an update feature where every 1/30 seconds it completes a "tick." Basically running a while loop where it starts a timer at the begining, runs some functions, and then waits for the timer to hit 1/30 seconds before looping again to keep the game smooth. I’ve looked into the timer function but haven’t been able to get it to work and I was hoping for some help. while loop, loops MATLAB Answers — New Questions
How to choose the optimum values of the training options Transfer learning of the pretrain Deep networks in MATLAB
Dear all I have a question, I am using Transfer Learning of the pretraining Deep learning networks I would like to know how to choose the optimum values of the training options(Solver, initial learning rate, max epoch, miniBatchsize etc) should I keep trying different values or choosing the default values, pleaseDear all I have a question, I am using Transfer Learning of the pretraining Deep learning networks I would like to know how to choose the optimum values of the training options(Solver, initial learning rate, max epoch, miniBatchsize etc) should I keep trying different values or choosing the default values, please Dear all I have a question, I am using Transfer Learning of the pretraining Deep learning networks I would like to know how to choose the optimum values of the training options(Solver, initial learning rate, max epoch, miniBatchsize etc) should I keep trying different values or choosing the default values, please training opitions MATLAB Answers — New Questions
Assigning PWM Ports in Speedgoat Motion Control HDL I/O Blockset for IO334 with 3xx-21 Extension Card?
I want to use pwm_example_hdlc.slx example from Speedgoat Motion Control HDL I/O Blockset v1.0 (R2024b). The Example is originally set to use with IO324. I am using Speedgoat P3 with IO334 and 3xx-21 Extension card.
In HDL Workflow Advisor, step 1.3 Set Target Interface, I need to assign interfaces for ports. It seems that I do not have any suitable option available for TTL_PMW_x and TTL_CAP_x ports (it defaults to "No Interface Specified"). In this webinar (19:37) it can be seen that interface option IO3XX-21 [0:55] should be available.
How can solve this problem?I want to use pwm_example_hdlc.slx example from Speedgoat Motion Control HDL I/O Blockset v1.0 (R2024b). The Example is originally set to use with IO324. I am using Speedgoat P3 with IO334 and 3xx-21 Extension card.
In HDL Workflow Advisor, step 1.3 Set Target Interface, I need to assign interfaces for ports. It seems that I do not have any suitable option available for TTL_PMW_x and TTL_CAP_x ports (it defaults to "No Interface Specified"). In this webinar (19:37) it can be seen that interface option IO3XX-21 [0:55] should be available.
How can solve this problem? I want to use pwm_example_hdlc.slx example from Speedgoat Motion Control HDL I/O Blockset v1.0 (R2024b). The Example is originally set to use with IO324. I am using Speedgoat P3 with IO334 and 3xx-21 Extension card.
In HDL Workflow Advisor, step 1.3 Set Target Interface, I need to assign interfaces for ports. It seems that I do not have any suitable option available for TTL_PMW_x and TTL_CAP_x ports (it defaults to "No Interface Specified"). In this webinar (19:37) it can be seen that interface option IO3XX-21 [0:55] should be available.
How can solve this problem? speedgoat, hdl, pwm, real-time MATLAB Answers — New Questions
How to implemented boundary condition in solving convection diffusion equation in cylindical coordinate
For C_c at r = R_c, you can consider that node as C(length(r1),j)
For C_a at r = R_c, you can consider that node as C(length(r1)+1,j)
Then, via central difference,
dC_c/dr (at r = R_c) can be written as (C(length(r1)+1,j)-C(length(r1)-1,j))/(del_r)
Similarly, dC_a/dr (at r = R_c) can be written as (C(length(r1)+2,j)-C(length(r1),j))/(del_r)
Try to suitably implement the above in the condition mass flux continuity condition at r = R_c, and check what happens. Also, ensure that the other conditions are correctly implemented, and then run the code.
I want to know how to write this in matlab so that I will not get error. I have aslo attached my matlab file hereFor C_c at r = R_c, you can consider that node as C(length(r1),j)
For C_a at r = R_c, you can consider that node as C(length(r1)+1,j)
Then, via central difference,
dC_c/dr (at r = R_c) can be written as (C(length(r1)+1,j)-C(length(r1)-1,j))/(del_r)
Similarly, dC_a/dr (at r = R_c) can be written as (C(length(r1)+2,j)-C(length(r1),j))/(del_r)
Try to suitably implement the above in the condition mass flux continuity condition at r = R_c, and check what happens. Also, ensure that the other conditions are correctly implemented, and then run the code.
I want to know how to write this in matlab so that I will not get error. I have aslo attached my matlab file here For C_c at r = R_c, you can consider that node as C(length(r1),j)
For C_a at r = R_c, you can consider that node as C(length(r1)+1,j)
Then, via central difference,
dC_c/dr (at r = R_c) can be written as (C(length(r1)+1,j)-C(length(r1)-1,j))/(del_r)
Similarly, dC_a/dr (at r = R_c) can be written as (C(length(r1)+2,j)-C(length(r1),j))/(del_r)
Try to suitably implement the above in the condition mass flux continuity condition at r = R_c, and check what happens. Also, ensure that the other conditions are correctly implemented, and then run the code.
I want to know how to write this in matlab so that I will not get error. I have aslo attached my matlab file here boundary condition, pde MATLAB Answers — New Questions
Simulink matrix multiply, dimension error
Below is a small part of my Simulink model. The function is only a repmat that repeats the vector into 9 rows. When the matrix multiply is doing a "matrix" multiplication, all is good and I get a 9×9 matrix out.
I then need to change the Matrix Multiply to do "element-wise" multiplicaton. So, I remove uT and change the property to element-wise.
But as you can see, it fails to run and I get the below error message which does not make sence because it fails on the exact dimensions that are expected of it:
The only caveat to this whole scenario is that both the data that goes into Transpose2 and into "Matrix Multiply" is actually a 3D data in the form of 394x1x22 and 9x394x22, respectively. So, initially I thought it could be that Simulink mixes up this 3rd dimension somehow. However, this 3rd dimension exists in the rest of my model and Simulink is happy with it AND when I change the element-wise to matrix-multiplication again, Simulink is happy. So, I cannot see how that 3rd dimension will only go wrong in this specific scenario that I am interested in, i.e. element-wise multiplication.
Any ideas are greatly welcome.Below is a small part of my Simulink model. The function is only a repmat that repeats the vector into 9 rows. When the matrix multiply is doing a "matrix" multiplication, all is good and I get a 9×9 matrix out.
I then need to change the Matrix Multiply to do "element-wise" multiplicaton. So, I remove uT and change the property to element-wise.
But as you can see, it fails to run and I get the below error message which does not make sence because it fails on the exact dimensions that are expected of it:
The only caveat to this whole scenario is that both the data that goes into Transpose2 and into "Matrix Multiply" is actually a 3D data in the form of 394x1x22 and 9x394x22, respectively. So, initially I thought it could be that Simulink mixes up this 3rd dimension somehow. However, this 3rd dimension exists in the rest of my model and Simulink is happy with it AND when I change the element-wise to matrix-multiplication again, Simulink is happy. So, I cannot see how that 3rd dimension will only go wrong in this specific scenario that I am interested in, i.e. element-wise multiplication.
Any ideas are greatly welcome. Below is a small part of my Simulink model. The function is only a repmat that repeats the vector into 9 rows. When the matrix multiply is doing a "matrix" multiplication, all is good and I get a 9×9 matrix out.
I then need to change the Matrix Multiply to do "element-wise" multiplicaton. So, I remove uT and change the property to element-wise.
But as you can see, it fails to run and I get the below error message which does not make sence because it fails on the exact dimensions that are expected of it:
The only caveat to this whole scenario is that both the data that goes into Transpose2 and into "Matrix Multiply" is actually a 3D data in the form of 394x1x22 and 9x394x22, respectively. So, initially I thought it could be that Simulink mixes up this 3rd dimension somehow. However, this 3rd dimension exists in the rest of my model and Simulink is happy with it AND when I change the element-wise to matrix-multiplication again, Simulink is happy. So, I cannot see how that 3rd dimension will only go wrong in this specific scenario that I am interested in, i.e. element-wise multiplication.
Any ideas are greatly welcome. simulink, matrix MATLAB Answers — New Questions
Hi, how to obtain the parameter number of the trained deep network in MATLAB ?
Hi, how to obtain the parameter number of the trained deep network in MATLAB?Hi, how to obtain the parameter number of the trained deep network in MATLAB? Hi, how to obtain the parameter number of the trained deep network in MATLAB? deep learning MATLAB Answers — New Questions
Finding distance between centers of circles by manually selecting muliple pairs
I am having trouble finding the correct distances from circle to circle. Is there a way to select manually which circles to measure the distances between? I would need to select multiple pairs and a circle can be in a pair more than once. Then be able to advance the program when finished. Not all circles are necessary to be selected. The circle finding itself works nicely.
I included the entire code. It grabs images from a file to analyze. Thank you.
directory = uigetdir;
files = dir(fullfile(directory, ‘*.bmp’));
for k = 1:length(files)
fileName = files(k).name;
fullFilePath = fullfile(directory, fileName);
fprintf(1, ‘Processing: %sn’, fullFilePath);
rgb = imread(fullFilePath);
rgb = imcrop(rgb,[950 0 400 750]);
rgb = rgb2hsv(rgb);
rgb = rgb(:,:,3);
rgb = imadjust(rgb, [0.1 0.85]);
%rgb = im2gray(rgb);
rgb = adapthisteq(rgb);
%crop
rgb = im2bw(rgb,0.3);
%binary conversion
imshow(rgb)
d = drawline;
pos = d.Position;
diffPos = diff(pos);
diameter = hypot(diffPos(1),diffPos(2))
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’,’Sensitivity’,0.8)
imshow(rgb)
h = viscircles(centers,radii);
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’, …
‘Sensitivity’,0.8);
length(centers)
%
delete(h) % Delete previously drawn circles
h = viscircles(centers,radii);
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’, …
‘Sensitivity’,0.8,’Method’,’twostage’);
delete(h)
h = viscircles(centers,radii);
%hBright = viscircles(centersBright, radiiBright,’Color’,’b’);
h = viscircles(centers,radii);
pix = 0.00001030927835;
%calibration for pix to meter
Yp(:) = centers(:,2);
%need to do every other circle, This does distance between every one
distance = abs(diff(Yp))
%distance between center in pix
Ydiff = distance*pix
%distance between center in meters
v = 0.142082
% change this variable ‘v’ for every test run
frequency = Ydiff/v
% units 1/s
diameter = 0.00635;
% units m
Strouhal = (frequency * diameter) / v
%final strouhal number
endI am having trouble finding the correct distances from circle to circle. Is there a way to select manually which circles to measure the distances between? I would need to select multiple pairs and a circle can be in a pair more than once. Then be able to advance the program when finished. Not all circles are necessary to be selected. The circle finding itself works nicely.
I included the entire code. It grabs images from a file to analyze. Thank you.
directory = uigetdir;
files = dir(fullfile(directory, ‘*.bmp’));
for k = 1:length(files)
fileName = files(k).name;
fullFilePath = fullfile(directory, fileName);
fprintf(1, ‘Processing: %sn’, fullFilePath);
rgb = imread(fullFilePath);
rgb = imcrop(rgb,[950 0 400 750]);
rgb = rgb2hsv(rgb);
rgb = rgb(:,:,3);
rgb = imadjust(rgb, [0.1 0.85]);
%rgb = im2gray(rgb);
rgb = adapthisteq(rgb);
%crop
rgb = im2bw(rgb,0.3);
%binary conversion
imshow(rgb)
d = drawline;
pos = d.Position;
diffPos = diff(pos);
diameter = hypot(diffPos(1),diffPos(2))
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’,’Sensitivity’,0.8)
imshow(rgb)
h = viscircles(centers,radii);
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’, …
‘Sensitivity’,0.8);
length(centers)
%
delete(h) % Delete previously drawn circles
h = viscircles(centers,radii);
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’, …
‘Sensitivity’,0.8,’Method’,’twostage’);
delete(h)
h = viscircles(centers,radii);
%hBright = viscircles(centersBright, radiiBright,’Color’,’b’);
h = viscircles(centers,radii);
pix = 0.00001030927835;
%calibration for pix to meter
Yp(:) = centers(:,2);
%need to do every other circle, This does distance between every one
distance = abs(diff(Yp))
%distance between center in pix
Ydiff = distance*pix
%distance between center in meters
v = 0.142082
% change this variable ‘v’ for every test run
frequency = Ydiff/v
% units 1/s
diameter = 0.00635;
% units m
Strouhal = (frequency * diameter) / v
%final strouhal number
end I am having trouble finding the correct distances from circle to circle. Is there a way to select manually which circles to measure the distances between? I would need to select multiple pairs and a circle can be in a pair more than once. Then be able to advance the program when finished. Not all circles are necessary to be selected. The circle finding itself works nicely.
I included the entire code. It grabs images from a file to analyze. Thank you.
directory = uigetdir;
files = dir(fullfile(directory, ‘*.bmp’));
for k = 1:length(files)
fileName = files(k).name;
fullFilePath = fullfile(directory, fileName);
fprintf(1, ‘Processing: %sn’, fullFilePath);
rgb = imread(fullFilePath);
rgb = imcrop(rgb,[950 0 400 750]);
rgb = rgb2hsv(rgb);
rgb = rgb(:,:,3);
rgb = imadjust(rgb, [0.1 0.85]);
%rgb = im2gray(rgb);
rgb = adapthisteq(rgb);
%crop
rgb = im2bw(rgb,0.3);
%binary conversion
imshow(rgb)
d = drawline;
pos = d.Position;
diffPos = diff(pos);
diameter = hypot(diffPos(1),diffPos(2))
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’,’Sensitivity’,0.8)
imshow(rgb)
h = viscircles(centers,radii);
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’, …
‘Sensitivity’,0.8);
length(centers)
%
delete(h) % Delete previously drawn circles
h = viscircles(centers,radii);
[centers,radii] = imfindcircles(rgb,[10 400],’ObjectPolarity’,’dark’, …
‘Sensitivity’,0.8,’Method’,’twostage’);
delete(h)
h = viscircles(centers,radii);
%hBright = viscircles(centersBright, radiiBright,’Color’,’b’);
h = viscircles(centers,radii);
pix = 0.00001030927835;
%calibration for pix to meter
Yp(:) = centers(:,2);
%need to do every other circle, This does distance between every one
distance = abs(diff(Yp))
%distance between center in pix
Ydiff = distance*pix
%distance between center in meters
v = 0.142082
% change this variable ‘v’ for every test run
frequency = Ydiff/v
% units 1/s
diameter = 0.00635;
% units m
Strouhal = (frequency * diameter) / v
%final strouhal number
end image analysis MATLAB Answers — New Questions
matlab python engine module not recognized
I am having trouble using the matlab python engine. I tried this piece of code from the mathworks website:
import matlab.engine
if __name__ == ‘__main__’:
eng = matlab.engine.start_matlab()
x = 4.0
eng.workspace[‘y’] = x
a = eng.eval(‘sqrt(y)’)
print(a)
pass
But pycharm is giving me an error saying "ModuleNotFoundError: No module named ‘matlab.engine’; ‘matlab’ is not a package". I am using python 3.6 and matlab 2018. I saw that these are the supported versions on website, I saw a similar post about this problem but I can’t even run my program from python command line. I also can’t find teh matlab.py in my python site-packages, although I have the matlab folder in packages.I am having trouble using the matlab python engine. I tried this piece of code from the mathworks website:
import matlab.engine
if __name__ == ‘__main__’:
eng = matlab.engine.start_matlab()
x = 4.0
eng.workspace[‘y’] = x
a = eng.eval(‘sqrt(y)’)
print(a)
pass
But pycharm is giving me an error saying "ModuleNotFoundError: No module named ‘matlab.engine’; ‘matlab’ is not a package". I am using python 3.6 and matlab 2018. I saw that these are the supported versions on website, I saw a similar post about this problem but I can’t even run my program from python command line. I also can’t find teh matlab.py in my python site-packages, although I have the matlab folder in packages. I am having trouble using the matlab python engine. I tried this piece of code from the mathworks website:
import matlab.engine
if __name__ == ‘__main__’:
eng = matlab.engine.start_matlab()
x = 4.0
eng.workspace[‘y’] = x
a = eng.eval(‘sqrt(y)’)
print(a)
pass
But pycharm is giving me an error saying "ModuleNotFoundError: No module named ‘matlab.engine’; ‘matlab’ is not a package". I am using python 3.6 and matlab 2018. I saw that these are the supported versions on website, I saw a similar post about this problem but I can’t even run my program from python command line. I also can’t find teh matlab.py in my python site-packages, although I have the matlab folder in packages. matlab python engine, pycharm, passing python variables to matlab MATLAB Answers — New Questions
Add a colorbar for this quiver plot
I wrote a code to have a quiver plot as I attached here. I want to add a colorbar to this code as it shows the magnitude of the vectors. How can I do that?
nu1=3.87e5;
nu2=0.46e5;
v_m=2.84e5;
v_p=7.18e5;
%
% nu1=8.4;
% nu2=1;
% v_m=1;
% v_p=2.5;
s=1;
s1=-1;
kesi=1;
kesi1=-1;
DeltaSO=41.9e-3;
alpha=1;
A=0.0;
hbar=1;
V=0;
iform=complex(0.0,1.0);
for i=1:25
k_x=-0.3+2*(i-1)*0.3/25;
for j=1:25
k_y=-0.3+2*(j-1)*0.3/25;
sigmax=[0 1; 1 0];
sigmay=[0 -iform; iform 0];
sigmaz=[1 0; 0 -1];
sigma0=[1 0; 0 1];
H1=hbar*k_x*nu1*sigmay-hbar*k_y*(s*nu2*sigmax+kesi*v_m*sigma0+kesi*v_p*sigmaz)+DeltaSO*(alpha-s*kesi)*sigmax+A*(s*sigmaz-kesi*sigmax)+V*sigma0;
H2=hbar*k_x*nu1*sigmay-hbar*k_y*(s1*nu2*sigmax+kesi*v_m*sigma0+kesi*v_p*sigmaz)+DeltaSO*(alpha-s1*kesi)*sigmax+A*(s1*sigmaz-kesi*sigmax)+V*sigma0;
H3=hbar*k_x*nu1*sigmay-hbar*k_y*(s*nu2*sigmax+kesi1*v_m*sigma0+kesi1*v_p*sigmaz)+DeltaSO*(alpha-s*kesi1)*sigmax+A*(s*sigmaz-kesi1*sigmax)+V*sigma0;
H4=hbar*k_x*nu1*sigmay-hbar*k_y*(s1*nu2*sigmax+kesi1*v_m*sigma0+kesi1*v_p*sigmaz)+DeltaSO*(alpha-s1*kesi1)*sigmax+A*(s1*sigmaz-kesi1*sigmax)+V*sigma0;
[v1,E1]=eig(H1);
[v2,E2]=eig(H2);
[v3,E3]=eig(H3);
[v4,E4]=eig(H4);
KX(i,j)=k_x;
KY(i,j)=k_y;
sx(i,j)=v4(:,2)’*sigmax*v4(:,2);
sy(i,j)=v4(:,2)’*sigmay*v4(:,2);
end
end
quiver(KX,KY,sx,sy,1)
q.ShowArrowHead = ‘off’;
q.Marker = ‘o’;
QuI wrote a code to have a quiver plot as I attached here. I want to add a colorbar to this code as it shows the magnitude of the vectors. How can I do that?
nu1=3.87e5;
nu2=0.46e5;
v_m=2.84e5;
v_p=7.18e5;
%
% nu1=8.4;
% nu2=1;
% v_m=1;
% v_p=2.5;
s=1;
s1=-1;
kesi=1;
kesi1=-1;
DeltaSO=41.9e-3;
alpha=1;
A=0.0;
hbar=1;
V=0;
iform=complex(0.0,1.0);
for i=1:25
k_x=-0.3+2*(i-1)*0.3/25;
for j=1:25
k_y=-0.3+2*(j-1)*0.3/25;
sigmax=[0 1; 1 0];
sigmay=[0 -iform; iform 0];
sigmaz=[1 0; 0 -1];
sigma0=[1 0; 0 1];
H1=hbar*k_x*nu1*sigmay-hbar*k_y*(s*nu2*sigmax+kesi*v_m*sigma0+kesi*v_p*sigmaz)+DeltaSO*(alpha-s*kesi)*sigmax+A*(s*sigmaz-kesi*sigmax)+V*sigma0;
H2=hbar*k_x*nu1*sigmay-hbar*k_y*(s1*nu2*sigmax+kesi*v_m*sigma0+kesi*v_p*sigmaz)+DeltaSO*(alpha-s1*kesi)*sigmax+A*(s1*sigmaz-kesi*sigmax)+V*sigma0;
H3=hbar*k_x*nu1*sigmay-hbar*k_y*(s*nu2*sigmax+kesi1*v_m*sigma0+kesi1*v_p*sigmaz)+DeltaSO*(alpha-s*kesi1)*sigmax+A*(s*sigmaz-kesi1*sigmax)+V*sigma0;
H4=hbar*k_x*nu1*sigmay-hbar*k_y*(s1*nu2*sigmax+kesi1*v_m*sigma0+kesi1*v_p*sigmaz)+DeltaSO*(alpha-s1*kesi1)*sigmax+A*(s1*sigmaz-kesi1*sigmax)+V*sigma0;
[v1,E1]=eig(H1);
[v2,E2]=eig(H2);
[v3,E3]=eig(H3);
[v4,E4]=eig(H4);
KX(i,j)=k_x;
KY(i,j)=k_y;
sx(i,j)=v4(:,2)’*sigmax*v4(:,2);
sy(i,j)=v4(:,2)’*sigmay*v4(:,2);
end
end
quiver(KX,KY,sx,sy,1)
q.ShowArrowHead = ‘off’;
q.Marker = ‘o’;
Qu I wrote a code to have a quiver plot as I attached here. I want to add a colorbar to this code as it shows the magnitude of the vectors. How can I do that?
nu1=3.87e5;
nu2=0.46e5;
v_m=2.84e5;
v_p=7.18e5;
%
% nu1=8.4;
% nu2=1;
% v_m=1;
% v_p=2.5;
s=1;
s1=-1;
kesi=1;
kesi1=-1;
DeltaSO=41.9e-3;
alpha=1;
A=0.0;
hbar=1;
V=0;
iform=complex(0.0,1.0);
for i=1:25
k_x=-0.3+2*(i-1)*0.3/25;
for j=1:25
k_y=-0.3+2*(j-1)*0.3/25;
sigmax=[0 1; 1 0];
sigmay=[0 -iform; iform 0];
sigmaz=[1 0; 0 -1];
sigma0=[1 0; 0 1];
H1=hbar*k_x*nu1*sigmay-hbar*k_y*(s*nu2*sigmax+kesi*v_m*sigma0+kesi*v_p*sigmaz)+DeltaSO*(alpha-s*kesi)*sigmax+A*(s*sigmaz-kesi*sigmax)+V*sigma0;
H2=hbar*k_x*nu1*sigmay-hbar*k_y*(s1*nu2*sigmax+kesi*v_m*sigma0+kesi*v_p*sigmaz)+DeltaSO*(alpha-s1*kesi)*sigmax+A*(s1*sigmaz-kesi*sigmax)+V*sigma0;
H3=hbar*k_x*nu1*sigmay-hbar*k_y*(s*nu2*sigmax+kesi1*v_m*sigma0+kesi1*v_p*sigmaz)+DeltaSO*(alpha-s*kesi1)*sigmax+A*(s*sigmaz-kesi1*sigmax)+V*sigma0;
H4=hbar*k_x*nu1*sigmay-hbar*k_y*(s1*nu2*sigmax+kesi1*v_m*sigma0+kesi1*v_p*sigmaz)+DeltaSO*(alpha-s1*kesi1)*sigmax+A*(s1*sigmaz-kesi1*sigmax)+V*sigma0;
[v1,E1]=eig(H1);
[v2,E2]=eig(H2);
[v3,E3]=eig(H3);
[v4,E4]=eig(H4);
KX(i,j)=k_x;
KY(i,j)=k_y;
sx(i,j)=v4(:,2)’*sigmax*v4(:,2);
sy(i,j)=v4(:,2)’*sigmay*v4(:,2);
end
end
quiver(KX,KY,sx,sy,1)
q.ShowArrowHead = ‘off’;
q.Marker = ‘o’;
Qu quiver- colorbar MATLAB Answers — New Questions
Search is getting failed for a library usage in Simulink model
I wanted to search number of instances of a library being used in the entire simulink model and also wanted to know all the path where the library is being is used.
But it is not working and says "Search Failed"
I have already increased "Java Heap Memory" to MAX in preferences.
Also deleted all temp files from temp folder and restarted PC and Matlab,SI wanted to search number of instances of a library being used in the entire simulink model and also wanted to know all the path where the library is being is used.
But it is not working and says "Search Failed"
I have already increased "Java Heap Memory" to MAX in preferences.
Also deleted all temp files from temp folder and restarted PC and Matlab,S I wanted to search number of instances of a library being used in the entire simulink model and also wanted to know all the path where the library is being is used.
But it is not working and says "Search Failed"
I have already increased "Java Heap Memory" to MAX in preferences.
Also deleted all temp files from temp folder and restarted PC and Matlab,S matlab search MATLAB Answers — New Questions
How to plot AM/AM and AM/PM Characteristic using input and output baseband signals?
I have .txt files that contain complex input and output baseband signals of an amplifier. I need to plot the AM/AM (magnitude of Gain vs. Input power) and AM/PM (phase of Gain vs. Input power) Characteristic.
% Calculate input and output power
P_in = 30 + 10*log10( (abs(x_in).^2)/100); % x_in is the input baseband signal
P_out = 30 + 10*log10((abs(x_out).^2)/100); % x_out is the output baseband signal
% Calculate gain
Mag_Gain = P_out – P_in;
Phase_Gain = rad2deg((angle(x_out) – angle(x_in)));
% Then I plot the AM/AM and AM/PM curves
% however the results does not match with the theoretical results.
% Is the way for calculating the power correct?I have .txt files that contain complex input and output baseband signals of an amplifier. I need to plot the AM/AM (magnitude of Gain vs. Input power) and AM/PM (phase of Gain vs. Input power) Characteristic.
% Calculate input and output power
P_in = 30 + 10*log10( (abs(x_in).^2)/100); % x_in is the input baseband signal
P_out = 30 + 10*log10((abs(x_out).^2)/100); % x_out is the output baseband signal
% Calculate gain
Mag_Gain = P_out – P_in;
Phase_Gain = rad2deg((angle(x_out) – angle(x_in)));
% Then I plot the AM/AM and AM/PM curves
% however the results does not match with the theoretical results.
% Is the way for calculating the power correct? I have .txt files that contain complex input and output baseband signals of an amplifier. I need to plot the AM/AM (magnitude of Gain vs. Input power) and AM/PM (phase of Gain vs. Input power) Characteristic.
% Calculate input and output power
P_in = 30 + 10*log10( (abs(x_in).^2)/100); % x_in is the input baseband signal
P_out = 30 + 10*log10((abs(x_out).^2)/100); % x_out is the output baseband signal
% Calculate gain
Mag_Gain = P_out – P_in;
Phase_Gain = rad2deg((angle(x_out) – angle(x_in)));
% Then I plot the AM/AM and AM/PM curves
% however the results does not match with the theoretical results.
% Is the way for calculating the power correct? amplifier MATLAB Answers — New Questions
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