Tag Archives: matlab
Why I am unable to receive data on Pixhawk 6x board using UAV Toolbox support package for PX4 Autopilots?
I am trying to receive data from Pixhawk 6x in Connected IO mode and Monitor & Tune simulation in R2024a and R2024b release. However, I am getting zero values for accel and gyro valuesI am trying to receive data from Pixhawk 6x in Connected IO mode and Monitor & Tune simulation in R2024a and R2024b release. However, I am getting zero values for accel and gyro values I am trying to receive data from Pixhawk 6x in Connected IO mode and Monitor & Tune simulation in R2024a and R2024b release. However, I am getting zero values for accel and gyro values px4 MATLAB Answers — New Questions
Indexing in nonsequential order
The following code copy files from the source folder to a destination folder:
SourcePath =’/f1/f2/f3/f4/f5/f6/f7/f8/’;
index = [00001]
%iteration for the 9th subfolder
for i = 1 : length(index)
newParticipant=num2str(index(i));
T = [‘sub-m’,newParticipant];
SourceFolder = fullfile([SourcePath,T],’f10/f11′)
%Destination folder is the current directory + DistFolder
DistFolder = fullfile(‘d1′,T,’d3’);
[X,Y,Z] = copyfile(fullfile(SourceFolder,’*y_file.chik.chik’), …
DistFolder);
end
Question: How can I automate the index when the subbfolder’s name (see above 9th subfolder) are 5-digits non sequential numbers?. The codeline
index = 00001 : 02500;
yileds an undesired output: It will create multiple empty folders in "distfolder".
For instance, the first file to copy is located in
SourceFolder = ‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m00001/f10/f11’
The Line index = 00001 : 02500; will create 120 empty files, since the second file to copy is located in
SourceFolder = ‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m00121/f10/f11’The following code copy files from the source folder to a destination folder:
SourcePath =’/f1/f2/f3/f4/f5/f6/f7/f8/’;
index = [00001]
%iteration for the 9th subfolder
for i = 1 : length(index)
newParticipant=num2str(index(i));
T = [‘sub-m’,newParticipant];
SourceFolder = fullfile([SourcePath,T],’f10/f11′)
%Destination folder is the current directory + DistFolder
DistFolder = fullfile(‘d1′,T,’d3’);
[X,Y,Z] = copyfile(fullfile(SourceFolder,’*y_file.chik.chik’), …
DistFolder);
end
Question: How can I automate the index when the subbfolder’s name (see above 9th subfolder) are 5-digits non sequential numbers?. The codeline
index = 00001 : 02500;
yileds an undesired output: It will create multiple empty folders in "distfolder".
For instance, the first file to copy is located in
SourceFolder = ‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m00001/f10/f11’
The Line index = 00001 : 02500; will create 120 empty files, since the second file to copy is located in
SourceFolder = ‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m00121/f10/f11’ The following code copy files from the source folder to a destination folder:
SourcePath =’/f1/f2/f3/f4/f5/f6/f7/f8/’;
index = [00001]
%iteration for the 9th subfolder
for i = 1 : length(index)
newParticipant=num2str(index(i));
T = [‘sub-m’,newParticipant];
SourceFolder = fullfile([SourcePath,T],’f10/f11′)
%Destination folder is the current directory + DistFolder
DistFolder = fullfile(‘d1′,T,’d3’);
[X,Y,Z] = copyfile(fullfile(SourceFolder,’*y_file.chik.chik’), …
DistFolder);
end
Question: How can I automate the index when the subbfolder’s name (see above 9th subfolder) are 5-digits non sequential numbers?. The codeline
index = 00001 : 02500;
yileds an undesired output: It will create multiple empty folders in "distfolder".
For instance, the first file to copy is located in
SourceFolder = ‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m00001/f10/f11’
The Line index = 00001 : 02500; will create 120 empty files, since the second file to copy is located in
SourceFolder = ‘/f1/f2/f3/f4/f5/f6/f7/f8/sub-m00121/f10/f11’ index, copyfile MATLAB Answers — New Questions
Polyspace Test GUI not starting
Hello,
Just installed polyspace test R2024b, but the GUI does not load completly and is not accesible.
The following message is shown: Cannot read properties of undefined (reading ‘statusCode’)
I already re-installed couple of times with the same result.
Does anyone know that can be / how to solve the issue?Hello,
Just installed polyspace test R2024b, but the GUI does not load completly and is not accesible.
The following message is shown: Cannot read properties of undefined (reading ‘statusCode’)
I already re-installed couple of times with the same result.
Does anyone know that can be / how to solve the issue? Hello,
Just installed polyspace test R2024b, but the GUI does not load completly and is not accesible.
The following message is shown: Cannot read properties of undefined (reading ‘statusCode’)
I already re-installed couple of times with the same result.
Does anyone know that can be / how to solve the issue? polyspace test MATLAB Answers — New Questions
How to acces lib.pointer in C++ Mex Files
Hello everyone,
I want to access lib.pointer within a mexFile using Matlab’s C++ API. The pointer is transported as matlab::data::ArrayType::HANDLE_OBJECT_REF, but I don’t know how to access the values within this structure. I want to convert this to a void pointer later. The lib.pointer contains a handle to a device and I am using this to communicate with the device via a separate API.
Hopefully someone can help me further.
Thank you in advance.Hello everyone,
I want to access lib.pointer within a mexFile using Matlab’s C++ API. The pointer is transported as matlab::data::ArrayType::HANDLE_OBJECT_REF, but I don’t know how to access the values within this structure. I want to convert this to a void pointer later. The lib.pointer contains a handle to a device and I am using this to communicate with the device via a separate API.
Hopefully someone can help me further.
Thank you in advance. Hello everyone,
I want to access lib.pointer within a mexFile using Matlab’s C++ API. The pointer is transported as matlab::data::ArrayType::HANDLE_OBJECT_REF, but I don’t know how to access the values within this structure. I want to convert this to a void pointer later. The lib.pointer contains a handle to a device and I am using this to communicate with the device via a separate API.
Hopefully someone can help me further.
Thank you in advance. dll, c++, api, mex MATLAB Answers — New Questions
How to read and show image from database?
I’m currently doing image processing, I had already created the database (982×2) where column 1 for RGB and column 2 for grayscale for all the images but I want to check whether the database is correct or not. So I want to read and show the image but I don’t know how to read the image by its row and column. Can anyone help me? Thank you in advance.I’m currently doing image processing, I had already created the database (982×2) where column 1 for RGB and column 2 for grayscale for all the images but I want to check whether the database is correct or not. So I want to read and show the image but I don’t know how to read the image by its row and column. Can anyone help me? Thank you in advance. I’m currently doing image processing, I had already created the database (982×2) where column 1 for RGB and column 2 for grayscale for all the images but I want to check whether the database is correct or not. So I want to read and show the image but I don’t know how to read the image by its row and column. Can anyone help me? Thank you in advance. read and show image from database MATLAB Answers — New Questions
Why I am I getting a row
How should I fix it so that x1 can be a column
r = 1;
K = 2;
tspan = [0 10];
x0 = 0.5;
[t,x] = ode45(@(t,x) x*(1- x/K), tspan, y0);
f = @(t) K / (1 + (K / x0 – 1) * exp(-1*r*t));
x1 = f(t);How should I fix it so that x1 can be a column
r = 1;
K = 2;
tspan = [0 10];
x0 = 0.5;
[t,x] = ode45(@(t,x) x*(1- x/K), tspan, y0);
f = @(t) K / (1 + (K / x0 – 1) * exp(-1*r*t));
x1 = f(t); How should I fix it so that x1 can be a column
r = 1;
K = 2;
tspan = [0 10];
x0 = 0.5;
[t,x] = ode45(@(t,x) x*(1- x/K), tspan, y0);
f = @(t) K / (1 + (K / x0 – 1) * exp(-1*r*t));
x1 = f(t); ode45, array MATLAB Answers — New Questions
File Exchange: how to “Link to an External Website”
According to https://www.mathworks.com/matlabcentral/content/fx/about.html I should be able to share my code without uploading a file, just by linking to my website.
When I try to Publish to File Exchange, I have "My code is on Github", "My code is on my computer" but I have no "Link to an External Website".
Where is this feature ?According to https://www.mathworks.com/matlabcentral/content/fx/about.html I should be able to share my code without uploading a file, just by linking to my website.
When I try to Publish to File Exchange, I have "My code is on Github", "My code is on my computer" but I have no "Link to an External Website".
Where is this feature ? According to https://www.mathworks.com/matlabcentral/content/fx/about.html I should be able to share my code without uploading a file, just by linking to my website.
When I try to Publish to File Exchange, I have "My code is on Github", "My code is on my computer" but I have no "Link to an External Website".
Where is this feature ? fileexchange MATLAB Answers — New Questions
Avoid generating empty functions with Simulink Embedded Coder
Hi, I’m generating C code from a Simulink model using Embedded Coder on Matlab R2017a. By default two functions are created, step and initialize. For my Simulink model, the initalize function is empty. Is there a way of avoiding generating the initialize function if it is going to be empty? The generation of this empty function creates some problems on the postprocessing of the generated C code by another tool so I was wondering if I could configure Embedded Coder not to generate empty functions.
Thanks in advance.Hi, I’m generating C code from a Simulink model using Embedded Coder on Matlab R2017a. By default two functions are created, step and initialize. For my Simulink model, the initalize function is empty. Is there a way of avoiding generating the initialize function if it is going to be empty? The generation of this empty function creates some problems on the postprocessing of the generated C code by another tool so I was wondering if I could configure Embedded Coder not to generate empty functions.
Thanks in advance. Hi, I’m generating C code from a Simulink model using Embedded Coder on Matlab R2017a. By default two functions are created, step and initialize. For my Simulink model, the initalize function is empty. Is there a way of avoiding generating the initialize function if it is going to be empty? The generation of this empty function creates some problems on the postprocessing of the generated C code by another tool so I was wondering if I could configure Embedded Coder not to generate empty functions.
Thanks in advance. embedded coder, simulink MATLAB Answers — New Questions
My agent isn’t learning it settles on a low reward
Hello, I’m currently researching using reinforcement learning as a controller to solve non-linearities in hydraulic systems, I’m facing a problem during traning my rl agent isn’t learning or settles on very low reward, I really don’t understand it’s behaviour I increased exploration and faced the same problem I was using initially a ddqn agent and faced the same problem. I’m so lost.
criticOptions = rlOptimizerOptions( …
Optimizer="adam", …
LearnRate=1e-5,…
GradientThreshold=1, …
L2RegularizationFactor=2e-4);
actorOptions = rlOptimizerOptions( …
Optimizer="adam", …
LearnRate=1e-5,…
GradientThreshold=1, …
L2RegularizationFactor=1e-5);
agentOptions = rlTD3AgentOptions;
agentOptions.ExplorationModel.StandardDeviation = 0.5;
agentOptions.ExplorationModel.StandardDeviationDecayRate = 1e-4;
agentOptions.DiscountFactor = 0.99;
agentOptions.TargetSmoothFactor = 5e-3;
agentOptions.TargetPolicySmoothModel.Variance = 0.2;
agentOptions.TargetUpdateFrequency = 10;
agentOptions.CriticOptimizerOptions = criticOptions;
agentOptions.ActorOptimizerOptions = actorOptions;
agent = rlTD3Agent(actor,[critic1 critic2],agentOptions);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’, 400, …
‘MaxStepsPerEpisode’, ceil(Tf / Ts), …
‘StopTrainingCriteria’, ‘EpisodeReward’, …
‘StopTrainingValue’, 2000, …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘SaveAgentCriteria’, ‘Custom’, …
‘SaveAgentValue’, @mySaveFcn, …
‘SaveAgentDirectory’, "SavedAgents");
[trainingStats] = train(agent, env, trainOpts);
Here’s the for the agent and traning
function y = fcn(u)
u=abs(u);
if (u<=0.005)
y=10;
elseif (u<=0.05)
y=5;
elseif (u<=0.5)
y=1;
else
y=-1;
end
end
and this is the reward
I’ve increased the number of episodes it didn’t change a thingHello, I’m currently researching using reinforcement learning as a controller to solve non-linearities in hydraulic systems, I’m facing a problem during traning my rl agent isn’t learning or settles on very low reward, I really don’t understand it’s behaviour I increased exploration and faced the same problem I was using initially a ddqn agent and faced the same problem. I’m so lost.
criticOptions = rlOptimizerOptions( …
Optimizer="adam", …
LearnRate=1e-5,…
GradientThreshold=1, …
L2RegularizationFactor=2e-4);
actorOptions = rlOptimizerOptions( …
Optimizer="adam", …
LearnRate=1e-5,…
GradientThreshold=1, …
L2RegularizationFactor=1e-5);
agentOptions = rlTD3AgentOptions;
agentOptions.ExplorationModel.StandardDeviation = 0.5;
agentOptions.ExplorationModel.StandardDeviationDecayRate = 1e-4;
agentOptions.DiscountFactor = 0.99;
agentOptions.TargetSmoothFactor = 5e-3;
agentOptions.TargetPolicySmoothModel.Variance = 0.2;
agentOptions.TargetUpdateFrequency = 10;
agentOptions.CriticOptimizerOptions = criticOptions;
agentOptions.ActorOptimizerOptions = actorOptions;
agent = rlTD3Agent(actor,[critic1 critic2],agentOptions);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’, 400, …
‘MaxStepsPerEpisode’, ceil(Tf / Ts), …
‘StopTrainingCriteria’, ‘EpisodeReward’, …
‘StopTrainingValue’, 2000, …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘SaveAgentCriteria’, ‘Custom’, …
‘SaveAgentValue’, @mySaveFcn, …
‘SaveAgentDirectory’, "SavedAgents");
[trainingStats] = train(agent, env, trainOpts);
Here’s the for the agent and traning
function y = fcn(u)
u=abs(u);
if (u<=0.005)
y=10;
elseif (u<=0.05)
y=5;
elseif (u<=0.5)
y=1;
else
y=-1;
end
end
and this is the reward
I’ve increased the number of episodes it didn’t change a thing Hello, I’m currently researching using reinforcement learning as a controller to solve non-linearities in hydraulic systems, I’m facing a problem during traning my rl agent isn’t learning or settles on very low reward, I really don’t understand it’s behaviour I increased exploration and faced the same problem I was using initially a ddqn agent and faced the same problem. I’m so lost.
criticOptions = rlOptimizerOptions( …
Optimizer="adam", …
LearnRate=1e-5,…
GradientThreshold=1, …
L2RegularizationFactor=2e-4);
actorOptions = rlOptimizerOptions( …
Optimizer="adam", …
LearnRate=1e-5,…
GradientThreshold=1, …
L2RegularizationFactor=1e-5);
agentOptions = rlTD3AgentOptions;
agentOptions.ExplorationModel.StandardDeviation = 0.5;
agentOptions.ExplorationModel.StandardDeviationDecayRate = 1e-4;
agentOptions.DiscountFactor = 0.99;
agentOptions.TargetSmoothFactor = 5e-3;
agentOptions.TargetPolicySmoothModel.Variance = 0.2;
agentOptions.TargetUpdateFrequency = 10;
agentOptions.CriticOptimizerOptions = criticOptions;
agentOptions.ActorOptimizerOptions = actorOptions;
agent = rlTD3Agent(actor,[critic1 critic2],agentOptions);
trainOpts = rlTrainingOptions(…
‘MaxEpisodes’, 400, …
‘MaxStepsPerEpisode’, ceil(Tf / Ts), …
‘StopTrainingCriteria’, ‘EpisodeReward’, …
‘StopTrainingValue’, 2000, …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘SaveAgentCriteria’, ‘Custom’, …
‘SaveAgentValue’, @mySaveFcn, …
‘SaveAgentDirectory’, "SavedAgents");
[trainingStats] = train(agent, env, trainOpts);
Here’s the for the agent and traning
function y = fcn(u)
u=abs(u);
if (u<=0.005)
y=10;
elseif (u<=0.05)
y=5;
elseif (u<=0.5)
y=1;
else
y=-1;
end
end
and this is the reward
I’ve increased the number of episodes it didn’t change a thing rl, reward, machine learning, deep learning, reinforcment learning MATLAB Answers — New Questions
how to remove deadcode or unused code in matlab model
Their is one model i have generate the code that model, after that i am done polyspace on that code then their some violation on that code,
According to guideline also I select MISRA C and POLYSPACE in code generation process.Their is one model i have generate the code that model, after that i am done polyspace on that code then their some violation on that code,
According to guideline also I select MISRA C and POLYSPACE in code generation process. Their is one model i have generate the code that model, after that i am done polyspace on that code then their some violation on that code,
According to guideline also I select MISRA C and POLYSPACE in code generation process. how to remove dead code in matlab model MATLAB Answers — New Questions
Issue loading mat file in different MATLAB versions
I have a mat file which contains userInputs that has 24 fileds. when i load in MATLAB 2023b i gives struct field userInput.SignalSourceType as empty but when i load same file in MATLAB 2024b i givest struct field userInput.SignalSourceType as 1. I am attaching screenshot for reference. The difference cause further issues and errors in my code and i need to run it on 2024b for certain requirments. If anyone have resolution please help me out.I have a mat file which contains userInputs that has 24 fileds. when i load in MATLAB 2023b i gives struct field userInput.SignalSourceType as empty but when i load same file in MATLAB 2024b i givest struct field userInput.SignalSourceType as 1. I am attaching screenshot for reference. The difference cause further issues and errors in my code and i need to run it on 2024b for certain requirments. If anyone have resolution please help me out. I have a mat file which contains userInputs that has 24 fileds. when i load in MATLAB 2023b i gives struct field userInput.SignalSourceType as empty but when i load same file in MATLAB 2024b i givest struct field userInput.SignalSourceType as 1. I am attaching screenshot for reference. The difference cause further issues and errors in my code and i need to run it on 2024b for certain requirments. If anyone have resolution please help me out. mat file, matlab version compatibility, load MATLAB Answers — New Questions
Importing Point cloud to overlay on solid object
I would like to import point cloud data from metrology system into Matlab.
The datatype i have point cloud is in text/asc/spreesheet/can also be converted to matlab array
i would like to visualise these points and later place these on the solid step file object i imported earlier to see the diffrence between them.
i tried to use mesh function but i get these errors , so i tried to change the import type and it doesn’t work .
Error in Test2 (line 3)
x = Experiment1coordinates.X; % All x values
^^^^^^^^^^^^^^^^^^^^^^^^
>> Test2
Error using mesh (line 71)
Z must be a matrix, not a scalar or vector.
Error in Test2 (line 6)
s = mesh(x,y,z,’FaceAlpha’,’0.5′)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^I would like to import point cloud data from metrology system into Matlab.
The datatype i have point cloud is in text/asc/spreesheet/can also be converted to matlab array
i would like to visualise these points and later place these on the solid step file object i imported earlier to see the diffrence between them.
i tried to use mesh function but i get these errors , so i tried to change the import type and it doesn’t work .
Error in Test2 (line 3)
x = Experiment1coordinates.X; % All x values
^^^^^^^^^^^^^^^^^^^^^^^^
>> Test2
Error using mesh (line 71)
Z must be a matrix, not a scalar or vector.
Error in Test2 (line 6)
s = mesh(x,y,z,’FaceAlpha’,’0.5′)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ I would like to import point cloud data from metrology system into Matlab.
The datatype i have point cloud is in text/asc/spreesheet/can also be converted to matlab array
i would like to visualise these points and later place these on the solid step file object i imported earlier to see the diffrence between them.
i tried to use mesh function but i get these errors , so i tried to change the import type and it doesn’t work .
Error in Test2 (line 3)
x = Experiment1coordinates.X; % All x values
^^^^^^^^^^^^^^^^^^^^^^^^
>> Test2
Error using mesh (line 71)
Z must be a matrix, not a scalar or vector.
Error in Test2 (line 6)
s = mesh(x,y,z,’FaceAlpha’,’0.5′)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ data import, point cloud MATLAB Answers — New Questions
How to measure the frequency of a 3 phase generator in simscape electrical
Hello
I would like to measure the freqeuncy of a 3 phase signal generated by a 3 phase generator in simscape electrical?
I didn’t use the sps library for my model, is there any alternative in the simscape electrical (the blue blocks)?
thank youHello
I would like to measure the freqeuncy of a 3 phase signal generated by a 3 phase generator in simscape electrical?
I didn’t use the sps library for my model, is there any alternative in the simscape electrical (the blue blocks)?
thank you Hello
I would like to measure the freqeuncy of a 3 phase signal generated by a 3 phase generator in simscape electrical?
I didn’t use the sps library for my model, is there any alternative in the simscape electrical (the blue blocks)?
thank you simscape electrical, frequency, measure MATLAB Answers — New Questions
I can’t synchronize lidar and camera together for fusion
This my code. When I move camera detects that am moving then 5 seconds later I start moving in the lidar.
% lidarFig = subplot(1, 2, 2); % Create subplot for lidar data
countinueStreaming = true;
while countinueStreaming
% Record the current timestamp before capturing the image
% Capture the image from the Jetson camera hardware.
I = snapshot(cam);
% Record the timestamp after capturing the image
% Call to detect method
[bboxes, scores, labels] = detect(detector, I);
personIndices = find(labels == ‘person’);
personBboxes = bboxes(personIndices, :);
% Convert categorical labels to cell array of character vectors
labels = cellstr(labels);
% Annotate detections in the camera image.
img = insertObjectAnnotation(I, ‘rectangle’, bboxes, labels);
% Display camera image
imshow(img);
hold on;
% Read data from Velodyne Lidar
pc = read(lidar);
% Remove ground plane
groundPtsIndex = segmentGroundFromLidarData(pc, ‘ElevationAngleDelta’, 0, …
‘InitialElevationAngle’, 0);
nonGroundPts = select(pc, ~groundPtsIndex);
imPts = projectLidarPointsOnImage(pc, intrinsics, LidarToCam);
scatter(imPts(:, 1), imPts(:, 2), 10, ‘g’, ‘filled’);
% Display lidar data
% pcshow(nonGroundPts.Location, ‘Parent’, lidarFig);
if ~isempty(personIndices)
for i = 1:numel(personIndices)
index = personIndices(i);
personBbox = bboxes(index, :);
% Process lidar data for each detected person
[lidarBbox, ~, boxUsed] = bboxCameraToLidar(personBbox, nonGroundPts, intrinsics, …
camToLidar, ‘ClusterThreshold’, 2, ‘MaxDetectionRange’, [1, 10]);
[distance, nearestRect, idx] = helperComputeDistance(personBbox, nonGroundPts, lidarBbox, …
intrinsics, LidarToCam);
% Print distance information
fprintf(‘DistOfPerson %d: %.2f metersn’, i, distance);
% Update image with bounding boxes
% im = updateImage(display, im, nearestRect, distance);
% updateLidarBbox(display, lidarBbox)
end
else
% Process lidar data for other objects
[lidarBbox, ~, boxUsed] = bboxCameraToLidar(bboxes, nonGroundPts, intrinsics, …
camToLidar, ‘ClusterThreshold’, 2, ‘MaxDetectionRange’, [1, 10]);
[distance, nearestRect, idx] = helperComputeDistance(bboxes, nonGroundPts, lidarBbox, …
intrinsics, LidarToCam);
% Print distance information
fprintf(‘DistOfObj: %.2f metersn’, distance);
% Update image with bounding boxes
% im = updateImage(display, im, nearestRect, distance);
% updateLidarBbox(display, lidarBbox)
end
hold off;
endThis my code. When I move camera detects that am moving then 5 seconds later I start moving in the lidar.
% lidarFig = subplot(1, 2, 2); % Create subplot for lidar data
countinueStreaming = true;
while countinueStreaming
% Record the current timestamp before capturing the image
% Capture the image from the Jetson camera hardware.
I = snapshot(cam);
% Record the timestamp after capturing the image
% Call to detect method
[bboxes, scores, labels] = detect(detector, I);
personIndices = find(labels == ‘person’);
personBboxes = bboxes(personIndices, :);
% Convert categorical labels to cell array of character vectors
labels = cellstr(labels);
% Annotate detections in the camera image.
img = insertObjectAnnotation(I, ‘rectangle’, bboxes, labels);
% Display camera image
imshow(img);
hold on;
% Read data from Velodyne Lidar
pc = read(lidar);
% Remove ground plane
groundPtsIndex = segmentGroundFromLidarData(pc, ‘ElevationAngleDelta’, 0, …
‘InitialElevationAngle’, 0);
nonGroundPts = select(pc, ~groundPtsIndex);
imPts = projectLidarPointsOnImage(pc, intrinsics, LidarToCam);
scatter(imPts(:, 1), imPts(:, 2), 10, ‘g’, ‘filled’);
% Display lidar data
% pcshow(nonGroundPts.Location, ‘Parent’, lidarFig);
if ~isempty(personIndices)
for i = 1:numel(personIndices)
index = personIndices(i);
personBbox = bboxes(index, :);
% Process lidar data for each detected person
[lidarBbox, ~, boxUsed] = bboxCameraToLidar(personBbox, nonGroundPts, intrinsics, …
camToLidar, ‘ClusterThreshold’, 2, ‘MaxDetectionRange’, [1, 10]);
[distance, nearestRect, idx] = helperComputeDistance(personBbox, nonGroundPts, lidarBbox, …
intrinsics, LidarToCam);
% Print distance information
fprintf(‘DistOfPerson %d: %.2f metersn’, i, distance);
% Update image with bounding boxes
% im = updateImage(display, im, nearestRect, distance);
% updateLidarBbox(display, lidarBbox)
end
else
% Process lidar data for other objects
[lidarBbox, ~, boxUsed] = bboxCameraToLidar(bboxes, nonGroundPts, intrinsics, …
camToLidar, ‘ClusterThreshold’, 2, ‘MaxDetectionRange’, [1, 10]);
[distance, nearestRect, idx] = helperComputeDistance(bboxes, nonGroundPts, lidarBbox, …
intrinsics, LidarToCam);
% Print distance information
fprintf(‘DistOfObj: %.2f metersn’, distance);
% Update image with bounding boxes
% im = updateImage(display, im, nearestRect, distance);
% updateLidarBbox(display, lidarBbox)
end
hold off;
end This my code. When I move camera detects that am moving then 5 seconds later I start moving in the lidar.
% lidarFig = subplot(1, 2, 2); % Create subplot for lidar data
countinueStreaming = true;
while countinueStreaming
% Record the current timestamp before capturing the image
% Capture the image from the Jetson camera hardware.
I = snapshot(cam);
% Record the timestamp after capturing the image
% Call to detect method
[bboxes, scores, labels] = detect(detector, I);
personIndices = find(labels == ‘person’);
personBboxes = bboxes(personIndices, :);
% Convert categorical labels to cell array of character vectors
labels = cellstr(labels);
% Annotate detections in the camera image.
img = insertObjectAnnotation(I, ‘rectangle’, bboxes, labels);
% Display camera image
imshow(img);
hold on;
% Read data from Velodyne Lidar
pc = read(lidar);
% Remove ground plane
groundPtsIndex = segmentGroundFromLidarData(pc, ‘ElevationAngleDelta’, 0, …
‘InitialElevationAngle’, 0);
nonGroundPts = select(pc, ~groundPtsIndex);
imPts = projectLidarPointsOnImage(pc, intrinsics, LidarToCam);
scatter(imPts(:, 1), imPts(:, 2), 10, ‘g’, ‘filled’);
% Display lidar data
% pcshow(nonGroundPts.Location, ‘Parent’, lidarFig);
if ~isempty(personIndices)
for i = 1:numel(personIndices)
index = personIndices(i);
personBbox = bboxes(index, :);
% Process lidar data for each detected person
[lidarBbox, ~, boxUsed] = bboxCameraToLidar(personBbox, nonGroundPts, intrinsics, …
camToLidar, ‘ClusterThreshold’, 2, ‘MaxDetectionRange’, [1, 10]);
[distance, nearestRect, idx] = helperComputeDistance(personBbox, nonGroundPts, lidarBbox, …
intrinsics, LidarToCam);
% Print distance information
fprintf(‘DistOfPerson %d: %.2f metersn’, i, distance);
% Update image with bounding boxes
% im = updateImage(display, im, nearestRect, distance);
% updateLidarBbox(display, lidarBbox)
end
else
% Process lidar data for other objects
[lidarBbox, ~, boxUsed] = bboxCameraToLidar(bboxes, nonGroundPts, intrinsics, …
camToLidar, ‘ClusterThreshold’, 2, ‘MaxDetectionRange’, [1, 10]);
[distance, nearestRect, idx] = helperComputeDistance(bboxes, nonGroundPts, lidarBbox, …
intrinsics, LidarToCam);
% Print distance information
fprintf(‘DistOfObj: %.2f metersn’, distance);
% Update image with bounding boxes
% im = updateImage(display, im, nearestRect, distance);
% updateLidarBbox(display, lidarBbox)
end
hold off;
end fusion, lidar, computer vision MATLAB Answers — New Questions
calling a python fuction within matlab
Hi,
i encountered the problem that when calling a python function within the matlab environment, the return value from python is not recognized in matlab – i always get a py.NoneType as an output.
Here my code in python, it is a code to send E-mails. I can see the print commands as an output in matlab but cannot capture the return values properly (always a py.NoneType in Matlab). When calling the function directly from python everything works fine.
What could the problem be ?
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
def send_email(gmail_user, gmail_password, to_email, subject, body, attachment_path):
"""
Send an email with an attachment using Gmail’s SMTP server.
Parameters:
gmail_user (str): Your Gmail email address
gmail_password (str): Your Gmail app password
to_email (str): Recipient’s email address
subject (str): Subject of the email
body (str): Body text of the email
attachment_path (str): Full path to the attachment file
"""
try:
# Create the email
email = MIMEMultipart()
email[‘From’] = gmail_user
email[‘To’] = to_email
email[‘Subject’] = subject
# Add the email body
email.attach(MIMEText(body, ‘plain’))
# Normalize the file path
attachment_path = attachment_path.encode(‘utf-8’).decode(‘utf-8’)
attachment_path = os.path.normpath(attachment_path)
# attachment_path = attachment_path.replace("\", "\\")
print(f"Processed attachment path: {attachment_path}")
# Check if the attachment file exists
if not os.path.exists(attachment_path):
print(f"Error: The file {attachment_path} does not exist.")
return ‘Name in Email not correct!’;
# Open the file in binary mode and encode it
with open(attachment_path, ‘rb’) as attachment_file:
attachment = MIMEBase(‘application’, ‘octet-stream’) # Generic MIME type, could be more specific
attachment.set_payload(attachment_file.read())
encoders.encode_base64(attachment)
# Extract filename from the path
filename = os.path.basename(attachment_path)
print(f"Attachment found: {filename}")
# Add header for the attachment
attachment.add_header(‘Content-Disposition’, ‘attachment’, filename=filename)
# Attach the file to the email
email.attach(attachment)
print(f"Attachment ‘{filename}’ added successfully.")
return ‘yes’
# Send the email using Gmail’s SMTP server
with smtplib.SMTP(‘smtp.gmail.com’, 587) as server:
server.starttls() # Secure the connection
server.login(gmail_user, gmail_password)
server.sendmail(gmail_user, to_email, email.as_string())
print("Email sent successfully!")
return ‘Email sent!’
except Exception as e:
print(f"Failed to send email: {e}")
return ‘Email failed fatal!’
return "Unknown error occurred."
Thanks in advance
I tried a "mini example" with a simple python function (just adding two numbers) and it worked, so I have no idea why the more advanced code does not work.Hi,
i encountered the problem that when calling a python function within the matlab environment, the return value from python is not recognized in matlab – i always get a py.NoneType as an output.
Here my code in python, it is a code to send E-mails. I can see the print commands as an output in matlab but cannot capture the return values properly (always a py.NoneType in Matlab). When calling the function directly from python everything works fine.
What could the problem be ?
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
def send_email(gmail_user, gmail_password, to_email, subject, body, attachment_path):
"""
Send an email with an attachment using Gmail’s SMTP server.
Parameters:
gmail_user (str): Your Gmail email address
gmail_password (str): Your Gmail app password
to_email (str): Recipient’s email address
subject (str): Subject of the email
body (str): Body text of the email
attachment_path (str): Full path to the attachment file
"""
try:
# Create the email
email = MIMEMultipart()
email[‘From’] = gmail_user
email[‘To’] = to_email
email[‘Subject’] = subject
# Add the email body
email.attach(MIMEText(body, ‘plain’))
# Normalize the file path
attachment_path = attachment_path.encode(‘utf-8’).decode(‘utf-8’)
attachment_path = os.path.normpath(attachment_path)
# attachment_path = attachment_path.replace("\", "\\")
print(f"Processed attachment path: {attachment_path}")
# Check if the attachment file exists
if not os.path.exists(attachment_path):
print(f"Error: The file {attachment_path} does not exist.")
return ‘Name in Email not correct!’;
# Open the file in binary mode and encode it
with open(attachment_path, ‘rb’) as attachment_file:
attachment = MIMEBase(‘application’, ‘octet-stream’) # Generic MIME type, could be more specific
attachment.set_payload(attachment_file.read())
encoders.encode_base64(attachment)
# Extract filename from the path
filename = os.path.basename(attachment_path)
print(f"Attachment found: {filename}")
# Add header for the attachment
attachment.add_header(‘Content-Disposition’, ‘attachment’, filename=filename)
# Attach the file to the email
email.attach(attachment)
print(f"Attachment ‘{filename}’ added successfully.")
return ‘yes’
# Send the email using Gmail’s SMTP server
with smtplib.SMTP(‘smtp.gmail.com’, 587) as server:
server.starttls() # Secure the connection
server.login(gmail_user, gmail_password)
server.sendmail(gmail_user, to_email, email.as_string())
print("Email sent successfully!")
return ‘Email sent!’
except Exception as e:
print(f"Failed to send email: {e}")
return ‘Email failed fatal!’
return "Unknown error occurred."
Thanks in advance
I tried a "mini example" with a simple python function (just adding two numbers) and it worked, so I have no idea why the more advanced code does not work. Hi,
i encountered the problem that when calling a python function within the matlab environment, the return value from python is not recognized in matlab – i always get a py.NoneType as an output.
Here my code in python, it is a code to send E-mails. I can see the print commands as an output in matlab but cannot capture the return values properly (always a py.NoneType in Matlab). When calling the function directly from python everything works fine.
What could the problem be ?
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
def send_email(gmail_user, gmail_password, to_email, subject, body, attachment_path):
"""
Send an email with an attachment using Gmail’s SMTP server.
Parameters:
gmail_user (str): Your Gmail email address
gmail_password (str): Your Gmail app password
to_email (str): Recipient’s email address
subject (str): Subject of the email
body (str): Body text of the email
attachment_path (str): Full path to the attachment file
"""
try:
# Create the email
email = MIMEMultipart()
email[‘From’] = gmail_user
email[‘To’] = to_email
email[‘Subject’] = subject
# Add the email body
email.attach(MIMEText(body, ‘plain’))
# Normalize the file path
attachment_path = attachment_path.encode(‘utf-8’).decode(‘utf-8’)
attachment_path = os.path.normpath(attachment_path)
# attachment_path = attachment_path.replace("\", "\\")
print(f"Processed attachment path: {attachment_path}")
# Check if the attachment file exists
if not os.path.exists(attachment_path):
print(f"Error: The file {attachment_path} does not exist.")
return ‘Name in Email not correct!’;
# Open the file in binary mode and encode it
with open(attachment_path, ‘rb’) as attachment_file:
attachment = MIMEBase(‘application’, ‘octet-stream’) # Generic MIME type, could be more specific
attachment.set_payload(attachment_file.read())
encoders.encode_base64(attachment)
# Extract filename from the path
filename = os.path.basename(attachment_path)
print(f"Attachment found: {filename}")
# Add header for the attachment
attachment.add_header(‘Content-Disposition’, ‘attachment’, filename=filename)
# Attach the file to the email
email.attach(attachment)
print(f"Attachment ‘{filename}’ added successfully.")
return ‘yes’
# Send the email using Gmail’s SMTP server
with smtplib.SMTP(‘smtp.gmail.com’, 587) as server:
server.starttls() # Secure the connection
server.login(gmail_user, gmail_password)
server.sendmail(gmail_user, to_email, email.as_string())
print("Email sent successfully!")
return ‘Email sent!’
except Exception as e:
print(f"Failed to send email: {e}")
return ‘Email failed fatal!’
return "Unknown error occurred."
Thanks in advance
I tried a "mini example" with a simple python function (just adding two numbers) and it worked, so I have no idea why the more advanced code does not work. python, function, py.nonetype MATLAB Answers — New Questions
Error when running app designer
Hi,
I have built an app in app designer that calculates heat transfer between a hot surface and a fluid.. I added equations for Reynolds and Nusselt numbers as well as heat transfer coefficient. I want to calculate all these variables when I push one button. I added all the equations for one push button and debugged the code. The app takes a very long time and it doesn’t show the results. Please advise!
Thank youHi,
I have built an app in app designer that calculates heat transfer between a hot surface and a fluid.. I added equations for Reynolds and Nusselt numbers as well as heat transfer coefficient. I want to calculate all these variables when I push one button. I added all the equations for one push button and debugged the code. The app takes a very long time and it doesn’t show the results. Please advise!
Thank you Hi,
I have built an app in app designer that calculates heat transfer between a hot surface and a fluid.. I added equations for Reynolds and Nusselt numbers as well as heat transfer coefficient. I want to calculate all these variables when I push one button. I added all the equations for one push button and debugged the code. The app takes a very long time and it doesn’t show the results. Please advise!
Thank you app_designer_error, push_button, heat_transfer MATLAB Answers — New Questions
LAUNCHXL-F280049C: External mode for debugging
I can build and deploy any program on the board (LAUNCHXL-F280049C). It works correctly.
For debugging purpose, I wanted to connect the board with my computer with the external mode. I have this error bellow.
I have try differents things:
In configuration parameter/hardware implementation/target hardware resources/external mode => try both COM port (UART and dataport)
Different switchs settings tried
S6 : 0 & S8 : 0
S3.1 : 1 & S4 : 1 & S8 : 1
__________________________________________________________________________________________
External Mode Open Protocol Connect command failed Caused by:
Could not connect to target application: XCP internal error: timeout expired, in response to XCP CONNECT commandI can build and deploy any program on the board (LAUNCHXL-F280049C). It works correctly.
For debugging purpose, I wanted to connect the board with my computer with the external mode. I have this error bellow.
I have try differents things:
In configuration parameter/hardware implementation/target hardware resources/external mode => try both COM port (UART and dataport)
Different switchs settings tried
S6 : 0 & S8 : 0
S3.1 : 1 & S4 : 1 & S8 : 1
__________________________________________________________________________________________
External Mode Open Protocol Connect command failed Caused by:
Could not connect to target application: XCP internal error: timeout expired, in response to XCP CONNECT command I can build and deploy any program on the board (LAUNCHXL-F280049C). It works correctly.
For debugging purpose, I wanted to connect the board with my computer with the external mode. I have this error bellow.
I have try differents things:
In configuration parameter/hardware implementation/target hardware resources/external mode => try both COM port (UART and dataport)
Different switchs settings tried
S6 : 0 & S8 : 0
S3.1 : 1 & S4 : 1 & S8 : 1
__________________________________________________________________________________________
External Mode Open Protocol Connect command failed Caused by:
Could not connect to target application: XCP internal error: timeout expired, in response to XCP CONNECT command simulink, c2000 MATLAB Answers — New Questions
driving scenario designer programically roads combine
when i am trying to create a driving scenario file programically and if i add 2 or more roads these will combine and form a single road when running it back?when i am trying to create a driving scenario file programically and if i add 2 or more roads these will combine and form a single road when running it back? when i am trying to create a driving scenario file programically and if i add 2 or more roads these will combine and form a single road when running it back? driving scenario designer, scenario MATLAB Answers — New Questions
How i can you ode extend function to used the solution till the end of timespan and in between used the RLC, offset and phase time as parameterizng function.
How i can you ode extend function to used the solution till the end of timespan and in between used the RLC, offset and phase time as parameterizng function. Kindly guide me.How i can you ode extend function to used the solution till the end of timespan and in between used the RLC, offset and phase time as parameterizng function. Kindly guide me. How i can you ode extend function to used the solution till the end of timespan and in between used the RLC, offset and phase time as parameterizng function. Kindly guide me. matlab MATLAB Answers — New Questions
MATLAB Simulink student license
Hi, I am a postgraduate student. Do Matlab student package include the C2000 Microcontroller blockset? As i am an ordinary student with lack of financial. Thus, the student package is the most affordable for me. Thank you.Hi, I am a postgraduate student. Do Matlab student package include the C2000 Microcontroller blockset? As i am an ordinary student with lack of financial. Thus, the student package is the most affordable for me. Thank you. Hi, I am a postgraduate student. Do Matlab student package include the C2000 Microcontroller blockset? As i am an ordinary student with lack of financial. Thus, the student package is the most affordable for me. Thank you. c2000 microcontroller blockset MATLAB Answers — New Questions