Category: Matlab
Category Archives: Matlab
Simulink External Mode not working for TI F280049C “Error occurred while executing External Mode MEX-file ‘ext_comm'”
I am currently trying to run a simulation via simulink but I am having trouble getting the monitor and tune to work, when simulate I get this error Error occurred while executing External Mode MEX-file ‘ext_comm’: Failed to connect to the target. A time-out occurred while waiting for the connection response from the target. Possible reasons for the time-out: a) The target is not switched on. b) The target is not connected to your host machine. c) The application for the model is not running on the target. You might have clicked the Stop button. If the Run button is not dimmed, click it. Otherwise, click the Build button, which downloads and runs your application on the target.
The program is able to build but and load onto the board but getting it to run via monitor and tune does not work
So far I have tried
Changing the UART serial port in hardware implementation to the port other than the Auxiallary port
Changing the OSCCART frequency from 20MHZ to 10Mhz (also tried 25MHz)
Uninstalling and reinstalling the XDS110 drivers
Closed CCS
Changed SCI_A to alternate ports
whats funny is that when i changed the UART ports yesterday it technically "ran" as in it said it was running and didnt give any errors, but the simulation stayed at T=0.00 no matter how long i left it running. but now today it just doesnt work period.
I will include a bunch of relevant screenshots, i also followed this post which had similar issues already but nothing works still
Simulink External Mode not working on Texas Instruments C2000 Launchpad F28377S – MATLAB Answers – MATLAB Central (mathworks.com)I am currently trying to run a simulation via simulink but I am having trouble getting the monitor and tune to work, when simulate I get this error Error occurred while executing External Mode MEX-file ‘ext_comm’: Failed to connect to the target. A time-out occurred while waiting for the connection response from the target. Possible reasons for the time-out: a) The target is not switched on. b) The target is not connected to your host machine. c) The application for the model is not running on the target. You might have clicked the Stop button. If the Run button is not dimmed, click it. Otherwise, click the Build button, which downloads and runs your application on the target.
The program is able to build but and load onto the board but getting it to run via monitor and tune does not work
So far I have tried
Changing the UART serial port in hardware implementation to the port other than the Auxiallary port
Changing the OSCCART frequency from 20MHZ to 10Mhz (also tried 25MHz)
Uninstalling and reinstalling the XDS110 drivers
Closed CCS
Changed SCI_A to alternate ports
whats funny is that when i changed the UART ports yesterday it technically "ran" as in it said it was running and didnt give any errors, but the simulation stayed at T=0.00 no matter how long i left it running. but now today it just doesnt work period.
I will include a bunch of relevant screenshots, i also followed this post which had similar issues already but nothing works still
Simulink External Mode not working on Texas Instruments C2000 Launchpad F28377S – MATLAB Answers – MATLAB Central (mathworks.com) I am currently trying to run a simulation via simulink but I am having trouble getting the monitor and tune to work, when simulate I get this error Error occurred while executing External Mode MEX-file ‘ext_comm’: Failed to connect to the target. A time-out occurred while waiting for the connection response from the target. Possible reasons for the time-out: a) The target is not switched on. b) The target is not connected to your host machine. c) The application for the model is not running on the target. You might have clicked the Stop button. If the Run button is not dimmed, click it. Otherwise, click the Build button, which downloads and runs your application on the target.
The program is able to build but and load onto the board but getting it to run via monitor and tune does not work
So far I have tried
Changing the UART serial port in hardware implementation to the port other than the Auxiallary port
Changing the OSCCART frequency from 20MHZ to 10Mhz (also tried 25MHz)
Uninstalling and reinstalling the XDS110 drivers
Closed CCS
Changed SCI_A to alternate ports
whats funny is that when i changed the UART ports yesterday it technically "ran" as in it said it was running and didnt give any errors, but the simulation stayed at T=0.00 no matter how long i left it running. but now today it just doesnt work period.
I will include a bunch of relevant screenshots, i also followed this post which had similar issues already but nothing works still
Simulink External Mode not working on Texas Instruments C2000 Launchpad F28377S – MATLAB Answers – MATLAB Central (mathworks.com) simulink, f280049c, monitor tune, debug, simulation MATLAB Answers — New Questions
Use Vehicle Network Toolbox with multiple CAN databases on a single CAN bus
I’m using Vehicle Network Toolbox (VNT) to itneract with a CAN bus using database files (.dbc files). I’ve got it working with the code below.
chanA = canChannel(‘Kvaser’, ‘Leaf Light v2 1’, 1);
chanA.Database = canDatabase(‘OperatorControl.dbc’);
That works fine, but now I want to interact with messages that are defined in different databases, but are on the same CAN bus. What is the best way to do that? Should I define a new CAN channel? I could do that, but it seems like it would become cumbersome if there are a lot of extra channels to deal with.
Can I combine multiple CAN databases into a single one before adding it to the CAN channel? Can I add more than one database to the CAN channel? I haven’t been able to find a way to do that.
Thank you.I’m using Vehicle Network Toolbox (VNT) to itneract with a CAN bus using database files (.dbc files). I’ve got it working with the code below.
chanA = canChannel(‘Kvaser’, ‘Leaf Light v2 1’, 1);
chanA.Database = canDatabase(‘OperatorControl.dbc’);
That works fine, but now I want to interact with messages that are defined in different databases, but are on the same CAN bus. What is the best way to do that? Should I define a new CAN channel? I could do that, but it seems like it would become cumbersome if there are a lot of extra channels to deal with.
Can I combine multiple CAN databases into a single one before adding it to the CAN channel? Can I add more than one database to the CAN channel? I haven’t been able to find a way to do that.
Thank you. I’m using Vehicle Network Toolbox (VNT) to itneract with a CAN bus using database files (.dbc files). I’ve got it working with the code below.
chanA = canChannel(‘Kvaser’, ‘Leaf Light v2 1’, 1);
chanA.Database = canDatabase(‘OperatorControl.dbc’);
That works fine, but now I want to interact with messages that are defined in different databases, but are on the same CAN bus. What is the best way to do that? Should I define a new CAN channel? I could do that, but it seems like it would become cumbersome if there are a lot of extra channels to deal with.
Can I combine multiple CAN databases into a single one before adding it to the CAN channel? Can I add more than one database to the CAN channel? I haven’t been able to find a way to do that.
Thank you. vehicle network toolbox, vnt, can, canbus, can database, dbc MATLAB Answers — New Questions
Webcam with App Designer
Hi everyone!
I have an app that I have created in app designer in which I use the use of the web camera … when I want to do packaging it marks an error and loads me the following files:
Utility.p
webcam.m
webcaDataUtilityHelper.p
And the warning says : p-files cannot de analized for dependent filesHi everyone!
I have an app that I have created in app designer in which I use the use of the web camera … when I want to do packaging it marks an error and loads me the following files:
Utility.p
webcam.m
webcaDataUtilityHelper.p
And the warning says : p-files cannot de analized for dependent files Hi everyone!
I have an app that I have created in app designer in which I use the use of the web camera … when I want to do packaging it marks an error and loads me the following files:
Utility.p
webcam.m
webcaDataUtilityHelper.p
And the warning says : p-files cannot de analized for dependent files webcam appdesigner MATLAB Answers — New Questions
how to use GPU to run idNeuralStateSpace
Hi everyone,
I am trying to use Neural state space model to identify the state derivatives using only measurement data. The system that I use requires small sampling time which leads to the requirement of large training data. I want to use GPU while estimating nonlinear state-space model using the built-in function nlssest and idNeuralStateSpace. Do you mind letting me know how I can utilize the GPU while running the model?
Thank you.Hi everyone,
I am trying to use Neural state space model to identify the state derivatives using only measurement data. The system that I use requires small sampling time which leads to the requirement of large training data. I want to use GPU while estimating nonlinear state-space model using the built-in function nlssest and idNeuralStateSpace. Do you mind letting me know how I can utilize the GPU while running the model?
Thank you. Hi everyone,
I am trying to use Neural state space model to identify the state derivatives using only measurement data. The system that I use requires small sampling time which leads to the requirement of large training data. I want to use GPU while estimating nonlinear state-space model using the built-in function nlssest and idNeuralStateSpace. Do you mind letting me know how I can utilize the GPU while running the model?
Thank you. neural network, neural state space, idneuralstatespace, nlssest, deep learning MATLAB Answers — New Questions
agrupacion de datos de una tabla
Holas,
tengo una tabla ‘tData’ de tamano: 152709×14, que resume senal de varias variables de un instrumento de medicion (FTIR) y quisiera disminuir el ruido agrupando los valores de la senial en grupos de a 10 es decir obtener una nueva tabla ‘tDataReduced’ de un tamano 15270×14. la tabla tData cuenta con una columna de texto con el nombre de cada serie de medicion llamada ‘MeasID’, una columna de fecha y hora llamada ‘Time’ y 12 columnas con valores numericos.
Para este proposito, Estoy usando este codigo:
% (1) Crear un vector de índices para agrupar las filas en grupos de 10
indices = repelem(1:ceil(height(tData)/10), 10, 1);
indices = indices(1:height(tData));
% (2) Calcular el promedio de cada grupo de 10 filas
tDataReduced = grpstats(tData, indices, ‘mean’);
% (3) Eliminar la columna de índices generada por grpstats
tDataReduced(:, ‘GroupCount’) = [];
%%%%%%%%%%%%%%%%%%%5
Pero se tranca en el paso (2) indicando este error:
%*****************
Index exceeds the number of array elements. Index must not exceed 14.
Error in dsgrpstats (line 97)
[group,glabel,groupname] = mgrp2idx(a_data(groupvars),a_nobs);
Error in grpstats (line 144)
[varargout{1:nargout}] = dsgrpstats(x,group,whichstats,varargin{:});
%******************
Algunba idea que me pueda ayudar?Holas,
tengo una tabla ‘tData’ de tamano: 152709×14, que resume senal de varias variables de un instrumento de medicion (FTIR) y quisiera disminuir el ruido agrupando los valores de la senial en grupos de a 10 es decir obtener una nueva tabla ‘tDataReduced’ de un tamano 15270×14. la tabla tData cuenta con una columna de texto con el nombre de cada serie de medicion llamada ‘MeasID’, una columna de fecha y hora llamada ‘Time’ y 12 columnas con valores numericos.
Para este proposito, Estoy usando este codigo:
% (1) Crear un vector de índices para agrupar las filas en grupos de 10
indices = repelem(1:ceil(height(tData)/10), 10, 1);
indices = indices(1:height(tData));
% (2) Calcular el promedio de cada grupo de 10 filas
tDataReduced = grpstats(tData, indices, ‘mean’);
% (3) Eliminar la columna de índices generada por grpstats
tDataReduced(:, ‘GroupCount’) = [];
%%%%%%%%%%%%%%%%%%%5
Pero se tranca en el paso (2) indicando este error:
%*****************
Index exceeds the number of array elements. Index must not exceed 14.
Error in dsgrpstats (line 97)
[group,glabel,groupname] = mgrp2idx(a_data(groupvars),a_nobs);
Error in grpstats (line 144)
[varargout{1:nargout}] = dsgrpstats(x,group,whichstats,varargin{:});
%******************
Algunba idea que me pueda ayudar? Holas,
tengo una tabla ‘tData’ de tamano: 152709×14, que resume senal de varias variables de un instrumento de medicion (FTIR) y quisiera disminuir el ruido agrupando los valores de la senial en grupos de a 10 es decir obtener una nueva tabla ‘tDataReduced’ de un tamano 15270×14. la tabla tData cuenta con una columna de texto con el nombre de cada serie de medicion llamada ‘MeasID’, una columna de fecha y hora llamada ‘Time’ y 12 columnas con valores numericos.
Para este proposito, Estoy usando este codigo:
% (1) Crear un vector de índices para agrupar las filas en grupos de 10
indices = repelem(1:ceil(height(tData)/10), 10, 1);
indices = indices(1:height(tData));
% (2) Calcular el promedio de cada grupo de 10 filas
tDataReduced = grpstats(tData, indices, ‘mean’);
% (3) Eliminar la columna de índices generada por grpstats
tDataReduced(:, ‘GroupCount’) = [];
%%%%%%%%%%%%%%%%%%%5
Pero se tranca en el paso (2) indicando este error:
%*****************
Index exceeds the number of array elements. Index must not exceed 14.
Error in dsgrpstats (line 97)
[group,glabel,groupname] = mgrp2idx(a_data(groupvars),a_nobs);
Error in grpstats (line 144)
[varargout{1:nargout}] = dsgrpstats(x,group,whichstats,varargin{:});
%******************
Algunba idea que me pueda ayudar? statistics, table, grpstats, filter, signal processing MATLAB Answers — New Questions
stl to grid error
I tired to use above code to make grid [xgridvector,ygridvector,zheights] use for simscape grid surface.
when I use ‘terrain.stl’, it works well. But when I use ‘untitle.stl’ the resault shows like this. please help me T_T..
%%code starts here
[stlData, ~] = stlread(‘untitled.stl’);
vertices = stlData.vertices;
% %
[uniqueVertices, ~, ic] = unique(vertices(:, 1:2), ‘rows’);
averageZ = accumarray(ic, vertices(:, 3), [], @mean);
vertices = [uniqueVertices, averageZ];
xGridVector = linspace(min(vertices(:,1)), max(vertices(:,1)), 100);
yGridVector = linspace(min(vertices(:,2)), max(vertices(:,2)), 100);
[X, Y] = ndgrid(xGridVector, yGridVector);
F = scatteredInterpolant(vertices(:,1), vertices(:,2), vertices(:,3), ‘linear’, ‘none’);
ZHeights = F(X, Y);
ZHeights(isnan(ZHeights)) = min(vertices(:,3));
figure;
surf(X, Y, ZHeights);
title(‘Grid Surface from STL File’);
xlabel(‘X (meters)’);
ylabel(‘Y (meters)’);
zlabel(‘Z (meters)’);
grid on;
function [stlData, units] = stlread(filename)
fid = fopen(filename, ‘r’);
if fid == -1
error(‘File could not be opened, check name or path.’)
end
M = fread(fid, inf, ‘uint8=>uint8’);
fclose(fid);
[pathstr, name, ext] = fileparts(filename);
if strcmpi(ext, ‘.stl’) ~= 1
error(‘Filename must have a .stl extension’);
end
if isempty(M)
error(‘File is empty.’);
end
M = char(M’);
if (strncmp(M, ‘solid’, 5))
[stlData.vertices, stlData.faces, units] = stlReadAscii(filename);
else
[stlData.vertices, stlData.faces, units] = stlReadBinary(filename);
end
end
% ASCII 형식 STL 파일 읽기 (단순화된 예시)
function [vertices, faces, units] = stlReadAscii(filename)
fid = fopen(filename, ‘r’);
vertices = [];
while ~feof(fid)
line = fgetl(fid);
if startsWith(line, ‘vertex’)
vertex = sscanf(line, ‘vertex %f %f %f’);
vertices = [vertices; vertex’];
end
end
fclose(fid);
faces = reshape(1:size(vertices, 1), 3, [])’;
units = ‘mm’;
end
% Binary 형식 STL 파일 읽기 (단순화된 예시)
function [vertices, faces, units] = stlReadBinary(filename)
fid = fopen(filename, ‘rb’);
fseek(fid, 80, ‘bof’);
numFaces = fread(fid, 1, ‘uint32’);
faces = zeros(numFaces, 3);
vertices = zeros(numFaces*3, 3);
for i = 1:numFaces
fread(fid, 3, ‘float32’);
vertices((i-1)*3+1:i*3, 🙂 = fread(fid, [3, 3], ‘float32′)’;
fread(fid, 1, ‘uint16’);
faces(i, 🙂 = (i-1)*3+1:i*3;
end
fclose(fid);
units = ‘mm’;
endI tired to use above code to make grid [xgridvector,ygridvector,zheights] use for simscape grid surface.
when I use ‘terrain.stl’, it works well. But when I use ‘untitle.stl’ the resault shows like this. please help me T_T..
%%code starts here
[stlData, ~] = stlread(‘untitled.stl’);
vertices = stlData.vertices;
% %
[uniqueVertices, ~, ic] = unique(vertices(:, 1:2), ‘rows’);
averageZ = accumarray(ic, vertices(:, 3), [], @mean);
vertices = [uniqueVertices, averageZ];
xGridVector = linspace(min(vertices(:,1)), max(vertices(:,1)), 100);
yGridVector = linspace(min(vertices(:,2)), max(vertices(:,2)), 100);
[X, Y] = ndgrid(xGridVector, yGridVector);
F = scatteredInterpolant(vertices(:,1), vertices(:,2), vertices(:,3), ‘linear’, ‘none’);
ZHeights = F(X, Y);
ZHeights(isnan(ZHeights)) = min(vertices(:,3));
figure;
surf(X, Y, ZHeights);
title(‘Grid Surface from STL File’);
xlabel(‘X (meters)’);
ylabel(‘Y (meters)’);
zlabel(‘Z (meters)’);
grid on;
function [stlData, units] = stlread(filename)
fid = fopen(filename, ‘r’);
if fid == -1
error(‘File could not be opened, check name or path.’)
end
M = fread(fid, inf, ‘uint8=>uint8’);
fclose(fid);
[pathstr, name, ext] = fileparts(filename);
if strcmpi(ext, ‘.stl’) ~= 1
error(‘Filename must have a .stl extension’);
end
if isempty(M)
error(‘File is empty.’);
end
M = char(M’);
if (strncmp(M, ‘solid’, 5))
[stlData.vertices, stlData.faces, units] = stlReadAscii(filename);
else
[stlData.vertices, stlData.faces, units] = stlReadBinary(filename);
end
end
% ASCII 형식 STL 파일 읽기 (단순화된 예시)
function [vertices, faces, units] = stlReadAscii(filename)
fid = fopen(filename, ‘r’);
vertices = [];
while ~feof(fid)
line = fgetl(fid);
if startsWith(line, ‘vertex’)
vertex = sscanf(line, ‘vertex %f %f %f’);
vertices = [vertices; vertex’];
end
end
fclose(fid);
faces = reshape(1:size(vertices, 1), 3, [])’;
units = ‘mm’;
end
% Binary 형식 STL 파일 읽기 (단순화된 예시)
function [vertices, faces, units] = stlReadBinary(filename)
fid = fopen(filename, ‘rb’);
fseek(fid, 80, ‘bof’);
numFaces = fread(fid, 1, ‘uint32’);
faces = zeros(numFaces, 3);
vertices = zeros(numFaces*3, 3);
for i = 1:numFaces
fread(fid, 3, ‘float32’);
vertices((i-1)*3+1:i*3, 🙂 = fread(fid, [3, 3], ‘float32′)’;
fread(fid, 1, ‘uint16’);
faces(i, 🙂 = (i-1)*3+1:i*3;
end
fclose(fid);
units = ‘mm’;
end I tired to use above code to make grid [xgridvector,ygridvector,zheights] use for simscape grid surface.
when I use ‘terrain.stl’, it works well. But when I use ‘untitle.stl’ the resault shows like this. please help me T_T..
%%code starts here
[stlData, ~] = stlread(‘untitled.stl’);
vertices = stlData.vertices;
% %
[uniqueVertices, ~, ic] = unique(vertices(:, 1:2), ‘rows’);
averageZ = accumarray(ic, vertices(:, 3), [], @mean);
vertices = [uniqueVertices, averageZ];
xGridVector = linspace(min(vertices(:,1)), max(vertices(:,1)), 100);
yGridVector = linspace(min(vertices(:,2)), max(vertices(:,2)), 100);
[X, Y] = ndgrid(xGridVector, yGridVector);
F = scatteredInterpolant(vertices(:,1), vertices(:,2), vertices(:,3), ‘linear’, ‘none’);
ZHeights = F(X, Y);
ZHeights(isnan(ZHeights)) = min(vertices(:,3));
figure;
surf(X, Y, ZHeights);
title(‘Grid Surface from STL File’);
xlabel(‘X (meters)’);
ylabel(‘Y (meters)’);
zlabel(‘Z (meters)’);
grid on;
function [stlData, units] = stlread(filename)
fid = fopen(filename, ‘r’);
if fid == -1
error(‘File could not be opened, check name or path.’)
end
M = fread(fid, inf, ‘uint8=>uint8’);
fclose(fid);
[pathstr, name, ext] = fileparts(filename);
if strcmpi(ext, ‘.stl’) ~= 1
error(‘Filename must have a .stl extension’);
end
if isempty(M)
error(‘File is empty.’);
end
M = char(M’);
if (strncmp(M, ‘solid’, 5))
[stlData.vertices, stlData.faces, units] = stlReadAscii(filename);
else
[stlData.vertices, stlData.faces, units] = stlReadBinary(filename);
end
end
% ASCII 형식 STL 파일 읽기 (단순화된 예시)
function [vertices, faces, units] = stlReadAscii(filename)
fid = fopen(filename, ‘r’);
vertices = [];
while ~feof(fid)
line = fgetl(fid);
if startsWith(line, ‘vertex’)
vertex = sscanf(line, ‘vertex %f %f %f’);
vertices = [vertices; vertex’];
end
end
fclose(fid);
faces = reshape(1:size(vertices, 1), 3, [])’;
units = ‘mm’;
end
% Binary 형식 STL 파일 읽기 (단순화된 예시)
function [vertices, faces, units] = stlReadBinary(filename)
fid = fopen(filename, ‘rb’);
fseek(fid, 80, ‘bof’);
numFaces = fread(fid, 1, ‘uint32’);
faces = zeros(numFaces, 3);
vertices = zeros(numFaces*3, 3);
for i = 1:numFaces
fread(fid, 3, ‘float32’);
vertices((i-1)*3+1:i*3, 🙂 = fread(fid, [3, 3], ‘float32′)’;
fread(fid, 1, ‘uint16’);
faces(i, 🙂 = (i-1)*3+1:i*3;
end
fclose(fid);
units = ‘mm’;
end stl, grid, error, export MATLAB Answers — New Questions
Good evening, we have a point cloud and have applied an first rotation to align the point cloud along the y-axis. Now we have a problem with a second rotation
clear all
close all
clc
%%
movingReg=pcread(‘v65_ts40_repeatibility_four9.ply’);
figure, pcshow(movingReg), view([0 0 ]), axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% roi dove ci sono i quattro fori
roi = [360 540 -155 -130 40 115]; % DA CAD
indices = findPointsInROI(movingReg,roi);
ptCloudB = select(movingReg,indices);
figure, pcshow(ptCloudB)
%% punto medio della nuvola di punti
centro=[mean(ptCloudB.Location(:,1)) mean(ptCloudB.Location(:,2)) mean(ptCloudB.Location(:,3))];
%% codice dato da Paolo per l’allineamento della nuvola
XYZ=[ptCloudB.Location(:,1) ptCloudB.Location(:,2) ptCloudB.Location(:,3)];
xyz0=mean(XYZ,1);
A=XYZ-xyz0;
[~,~,V]=svd(A,0);
a=cross(V(:,3),[0;0;1]);
T=makehgtform(‘axisrotate’, a, -atan2(norm(a),V(3,3)));
R=T(1:3,1:3);
A_rot = A*R;
% A_rot_pt=pointCloud(A_rot);
A_rot_p(:,1)=A_rot(:,1);
A_rot_p(:,3)=A_rot(:,2);
A_rot_p(:,2)=A_rot(:,3);
A_rot_p=pointCloud(A_rot_p);
figure, pcshow(A_rot_p),axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% applico una seconda svd
XYZ2=[A_rot_p.Location(:,1) A_rot_p.Location(:,2) A_rot_p.Location(:,3)];
xyz0_2=mean(XYZ2,1);
A=XYZ2-xyz0_2;
[~,~,V]=svd(A,0);
a=cross(V(:,1),[0;1;0]);%cross(V(:,2),[0;1;0]);
% T=makehgtform(‘zrotate’, -atan2(norm(a),V(2,1)));
if (V(1,2))>0
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),V(1,2)));
else
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),-V(1,2)));
endclear all
close all
clc
%%
movingReg=pcread(‘v65_ts40_repeatibility_four9.ply’);
figure, pcshow(movingReg), view([0 0 ]), axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% roi dove ci sono i quattro fori
roi = [360 540 -155 -130 40 115]; % DA CAD
indices = findPointsInROI(movingReg,roi);
ptCloudB = select(movingReg,indices);
figure, pcshow(ptCloudB)
%% punto medio della nuvola di punti
centro=[mean(ptCloudB.Location(:,1)) mean(ptCloudB.Location(:,2)) mean(ptCloudB.Location(:,3))];
%% codice dato da Paolo per l’allineamento della nuvola
XYZ=[ptCloudB.Location(:,1) ptCloudB.Location(:,2) ptCloudB.Location(:,3)];
xyz0=mean(XYZ,1);
A=XYZ-xyz0;
[~,~,V]=svd(A,0);
a=cross(V(:,3),[0;0;1]);
T=makehgtform(‘axisrotate’, a, -atan2(norm(a),V(3,3)));
R=T(1:3,1:3);
A_rot = A*R;
% A_rot_pt=pointCloud(A_rot);
A_rot_p(:,1)=A_rot(:,1);
A_rot_p(:,3)=A_rot(:,2);
A_rot_p(:,2)=A_rot(:,3);
A_rot_p=pointCloud(A_rot_p);
figure, pcshow(A_rot_p),axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% applico una seconda svd
XYZ2=[A_rot_p.Location(:,1) A_rot_p.Location(:,2) A_rot_p.Location(:,3)];
xyz0_2=mean(XYZ2,1);
A=XYZ2-xyz0_2;
[~,~,V]=svd(A,0);
a=cross(V(:,1),[0;1;0]);%cross(V(:,2),[0;1;0]);
% T=makehgtform(‘zrotate’, -atan2(norm(a),V(2,1)));
if (V(1,2))>0
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),V(1,2)));
else
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),-V(1,2)));
end clear all
close all
clc
%%
movingReg=pcread(‘v65_ts40_repeatibility_four9.ply’);
figure, pcshow(movingReg), view([0 0 ]), axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% roi dove ci sono i quattro fori
roi = [360 540 -155 -130 40 115]; % DA CAD
indices = findPointsInROI(movingReg,roi);
ptCloudB = select(movingReg,indices);
figure, pcshow(ptCloudB)
%% punto medio della nuvola di punti
centro=[mean(ptCloudB.Location(:,1)) mean(ptCloudB.Location(:,2)) mean(ptCloudB.Location(:,3))];
%% codice dato da Paolo per l’allineamento della nuvola
XYZ=[ptCloudB.Location(:,1) ptCloudB.Location(:,2) ptCloudB.Location(:,3)];
xyz0=mean(XYZ,1);
A=XYZ-xyz0;
[~,~,V]=svd(A,0);
a=cross(V(:,3),[0;0;1]);
T=makehgtform(‘axisrotate’, a, -atan2(norm(a),V(3,3)));
R=T(1:3,1:3);
A_rot = A*R;
% A_rot_pt=pointCloud(A_rot);
A_rot_p(:,1)=A_rot(:,1);
A_rot_p(:,3)=A_rot(:,2);
A_rot_p(:,2)=A_rot(:,3);
A_rot_p=pointCloud(A_rot_p);
figure, pcshow(A_rot_p),axis on, xlabel(‘x [mm]’), ylabel(‘y [mm]’), zlabel(‘z [mm]’)
%% applico una seconda svd
XYZ2=[A_rot_p.Location(:,1) A_rot_p.Location(:,2) A_rot_p.Location(:,3)];
xyz0_2=mean(XYZ2,1);
A=XYZ2-xyz0_2;
[~,~,V]=svd(A,0);
a=cross(V(:,1),[0;1;0]);%cross(V(:,2),[0;1;0]);
% T=makehgtform(‘zrotate’, -atan2(norm(a),V(2,1)));
if (V(1,2))>0
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),V(1,2)));
else
T=makehgtform(‘axisrotate’, [0 1 0], -atan2(norm(a),-V(1,2)));
end point cloud, data rotation MATLAB Answers — New Questions
Reading ADC data from MSP430 to Matlab via serial port
My situation is
1. external ADC samples from one channel and transmit to Serial port Via Uart and then switches over to second channel to do same and then third.
2. I manage to view data in Hterm and it looked quite fine.
3. I want to plot it live in matlab- I know there are ways to do it but can someone here explain me a basic step by step to achieve my objective?
I have basic idea of what i should be doing
setup serial communication.
create array to store uart values
calculate voltage values
plot live values
It would be nice if someone points out me for where to look for point 2 and 4 specifically.My situation is
1. external ADC samples from one channel and transmit to Serial port Via Uart and then switches over to second channel to do same and then third.
2. I manage to view data in Hterm and it looked quite fine.
3. I want to plot it live in matlab- I know there are ways to do it but can someone here explain me a basic step by step to achieve my objective?
I have basic idea of what i should be doing
setup serial communication.
create array to store uart values
calculate voltage values
plot live values
It would be nice if someone points out me for where to look for point 2 and 4 specifically. My situation is
1. external ADC samples from one channel and transmit to Serial port Via Uart and then switches over to second channel to do same and then third.
2. I manage to view data in Hterm and it looked quite fine.
3. I want to plot it live in matlab- I know there are ways to do it but can someone here explain me a basic step by step to achieve my objective?
I have basic idea of what i should be doing
setup serial communication.
create array to store uart values
calculate voltage values
plot live values
It would be nice if someone points out me for where to look for point 2 and 4 specifically. msp430, adc, uart, serial MATLAB Answers — New Questions
Why am I unable to change the user on the Online Training Suite License?
Why am I unable to change the user on the Online Training Suite License?Why am I unable to change the user on the Online Training Suite License? Why am I unable to change the user on the Online Training Suite License? MATLAB Answers — New Questions
Shiftet values of omega in bode plot as result from generating idfrd() and tfest()
Hello,
i have a problem at the calculation / estimation of a transfer function when using frequency-domain data.
My task is to get the continious transfer function for further simulation from measured magnitude and phase response by an impedance analyser.
The quality of the estimated curve is ok, but the problem is that the curve is shifted in omega and i cannot observe the problem.
The frequency limits of the measured data are 20 Hz to 5000 Hz with the units (freq. [Hz], magn [-], phase [°]).
Figure 1 and Figrue 2 shows the magnitude and phase of the measured data.
In Figure 3 shows the bode plot with idfrd() / frd() and the estimated TF.
Here the values are shiftet.
What ist the problem in this case?
format short g
clear
matt = readmatrix(‘data.CSV’);
fre = matt(1:300,1);
frerad = fre.*(pi/180);
abso = matt(1:300,2);
absdb = 20*log10(abso);
phdeg = matt(1:300,3);
phrad = phdeg.*(pi/180);
% options = bodeoptions;
% options.FreqUnits = ‘Hz’;
figure(1)
semilogx(fre,absdb)
legend()
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
grid()
figure(2)
semilogx(fre,phdeg)
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
legend()
grid()
complexVector = abso.* exp(1j*phrad);
vect_mess = idfrd(complexVector,frerad,0);
% vect_mess = frd(complexVector,frerad);
tf_estimated = tfest(vect_mess,3)
figure(3)
bode(vect_mess,tf_estimated )
legend()
grid()Hello,
i have a problem at the calculation / estimation of a transfer function when using frequency-domain data.
My task is to get the continious transfer function for further simulation from measured magnitude and phase response by an impedance analyser.
The quality of the estimated curve is ok, but the problem is that the curve is shifted in omega and i cannot observe the problem.
The frequency limits of the measured data are 20 Hz to 5000 Hz with the units (freq. [Hz], magn [-], phase [°]).
Figure 1 and Figrue 2 shows the magnitude and phase of the measured data.
In Figure 3 shows the bode plot with idfrd() / frd() and the estimated TF.
Here the values are shiftet.
What ist the problem in this case?
format short g
clear
matt = readmatrix(‘data.CSV’);
fre = matt(1:300,1);
frerad = fre.*(pi/180);
abso = matt(1:300,2);
absdb = 20*log10(abso);
phdeg = matt(1:300,3);
phrad = phdeg.*(pi/180);
% options = bodeoptions;
% options.FreqUnits = ‘Hz’;
figure(1)
semilogx(fre,absdb)
legend()
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
grid()
figure(2)
semilogx(fre,phdeg)
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
legend()
grid()
complexVector = abso.* exp(1j*phrad);
vect_mess = idfrd(complexVector,frerad,0);
% vect_mess = frd(complexVector,frerad);
tf_estimated = tfest(vect_mess,3)
figure(3)
bode(vect_mess,tf_estimated )
legend()
grid() Hello,
i have a problem at the calculation / estimation of a transfer function when using frequency-domain data.
My task is to get the continious transfer function for further simulation from measured magnitude and phase response by an impedance analyser.
The quality of the estimated curve is ok, but the problem is that the curve is shifted in omega and i cannot observe the problem.
The frequency limits of the measured data are 20 Hz to 5000 Hz with the units (freq. [Hz], magn [-], phase [°]).
Figure 1 and Figrue 2 shows the magnitude and phase of the measured data.
In Figure 3 shows the bode plot with idfrd() / frd() and the estimated TF.
Here the values are shiftet.
What ist the problem in this case?
format short g
clear
matt = readmatrix(‘data.CSV’);
fre = matt(1:300,1);
frerad = fre.*(pi/180);
abso = matt(1:300,2);
absdb = 20*log10(abso);
phdeg = matt(1:300,3);
phrad = phdeg.*(pi/180);
% options = bodeoptions;
% options.FreqUnits = ‘Hz’;
figure(1)
semilogx(fre,absdb)
legend()
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
grid()
figure(2)
semilogx(fre,phdeg)
ylabel(‘magn. [dB]’)
xlabel(‘freq. [Hz]’)
legend()
grid()
complexVector = abso.* exp(1j*phrad);
vect_mess = idfrd(complexVector,frerad,0);
% vect_mess = frd(complexVector,frerad);
tf_estimated = tfest(vect_mess,3)
figure(3)
bode(vect_mess,tf_estimated )
legend()
grid() transfer function, estimation tfest MATLAB Answers — New Questions
After completing Matlab onramp my progress bar keeps changing back to 87% with some modules saying they aren’t completed after recieving a certificate with 100% completion.
I have completed the Matlab onramp and recieved a certificate saying 100% complettion, despite issues with the website proccessing this it finally went through. After returning to the MathWorks site to link my certificate to linkedin my progress has gone back down to 87% saying that some modules are incomplete- with the effect of reducing the progress score on my certificate down to 87%.I have completed the Matlab onramp and recieved a certificate saying 100% complettion, despite issues with the website proccessing this it finally went through. After returning to the MathWorks site to link my certificate to linkedin my progress has gone back down to 87% saying that some modules are incomplete- with the effect of reducing the progress score on my certificate down to 87%. I have completed the Matlab onramp and recieved a certificate saying 100% complettion, despite issues with the website proccessing this it finally went through. After returning to the MathWorks site to link my certificate to linkedin my progress has gone back down to 87% saying that some modules are incomplete- with the effect of reducing the progress score on my certificate down to 87%. onramp MATLAB Answers — New Questions
Leave-out-one cross validation during neural network training
Hello there I am trying to train a ML model with leave-out-one trial cross validation. Right now I have input data stored in the 1×10 cell array: "XTrain" with each cell containing the prediction inputs for all 10 trials and another 1×10 cell array: "YTrain" that contains the correposding continous variable we are trying to predict/output.
net = connectLayers(net,outputName,"fc");
% Specify training options
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 60, …
‘MiniBatchSize’, 1, …
‘SequenceLength’, ‘longest’, …
‘InputDataFormats’, ‘CTB’, …
‘Plots’, ‘training-progress’, …
‘Metrics’, ‘rmse’, …
‘Verbose’, 0 …
‘Validation);
% Train the network
net = trainnet(XTrain,YTrain,net,"mse",options)
I have built my model’s network architecture stored in "net", but I am unsure of how to incorporte "leave out one trial" validation during training and then test my model’s performance. I want the model to pull out one trial at a time and then train the model and continue to do this for all 10 trials so that I end up with one final network trained and validated on all the trials. But I also want to have data to test the model’s performance? Do I need to create a loop for this? or is there a way I can specify this in the training options? Any help would be greatly appreciated!Hello there I am trying to train a ML model with leave-out-one trial cross validation. Right now I have input data stored in the 1×10 cell array: "XTrain" with each cell containing the prediction inputs for all 10 trials and another 1×10 cell array: "YTrain" that contains the correposding continous variable we are trying to predict/output.
net = connectLayers(net,outputName,"fc");
% Specify training options
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 60, …
‘MiniBatchSize’, 1, …
‘SequenceLength’, ‘longest’, …
‘InputDataFormats’, ‘CTB’, …
‘Plots’, ‘training-progress’, …
‘Metrics’, ‘rmse’, …
‘Verbose’, 0 …
‘Validation);
% Train the network
net = trainnet(XTrain,YTrain,net,"mse",options)
I have built my model’s network architecture stored in "net", but I am unsure of how to incorporte "leave out one trial" validation during training and then test my model’s performance. I want the model to pull out one trial at a time and then train the model and continue to do this for all 10 trials so that I end up with one final network trained and validated on all the trials. But I also want to have data to test the model’s performance? Do I need to create a loop for this? or is there a way I can specify this in the training options? Any help would be greatly appreciated! Hello there I am trying to train a ML model with leave-out-one trial cross validation. Right now I have input data stored in the 1×10 cell array: "XTrain" with each cell containing the prediction inputs for all 10 trials and another 1×10 cell array: "YTrain" that contains the correposding continous variable we are trying to predict/output.
net = connectLayers(net,outputName,"fc");
% Specify training options
options = trainingOptions(‘adam’, …
‘MaxEpochs’, 60, …
‘MiniBatchSize’, 1, …
‘SequenceLength’, ‘longest’, …
‘InputDataFormats’, ‘CTB’, …
‘Plots’, ‘training-progress’, …
‘Metrics’, ‘rmse’, …
‘Verbose’, 0 …
‘Validation);
% Train the network
net = trainnet(XTrain,YTrain,net,"mse",options)
I have built my model’s network architecture stored in "net", but I am unsure of how to incorporte "leave out one trial" validation during training and then test my model’s performance. I want the model to pull out one trial at a time and then train the model and continue to do this for all 10 trials so that I end up with one final network trained and validated on all the trials. But I also want to have data to test the model’s performance? Do I need to create a loop for this? or is there a way I can specify this in the training options? Any help would be greatly appreciated! machine learning, validation, neural network, trainnet MATLAB Answers — New Questions
Incorrect Data Interpretation in UDP Reception with Simulink
On an ESP32, I am sending distance data via UDP to MATLAB. There are multiple distances involved, so both the receiver number (from 81 to 84) and the respective distance are transmitted. I can also receive and analyze the data using the following program:
% Set up the UDP receiver
udpReceiver = udpport("LocalPort", 4141);
% Define a function to parse the received UDP packet
% Main loop to continuously receive and display distances
while true
% Check if a packet is available
if udpReceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpReceiver, udpReceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Display current distances
fprintf(‘Distance from Device 1: %.2f metersn’, distance1);
fprintf(‘Distance from Device 2: %.2f metersn’, distance2);
fprintf(‘Distance from Device 3: %.2f metersn’, distance3);
fprintf(‘Distance from Device 4: %.2f metersn’, distance4);
fprintf(‘n’); % Add newline for clarity
end
pause(0.1);
end
% Clean up
delete(udpReceiver)
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Now I want to further process only the respective distances in Simulink. For this, I have converted the code into a Level 2 MATLAB function. Here is the code for it:
function UDP_Receiver(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.NumDialogPrms = 0;
block.SampleTimes = [-1 0];
block.SimStateCompliance = ‘DefaultSimState’;
block.RegBlockMethod(‘SetInputPortSamplingMode’, @SetInpPortFrameData);
block.RegBlockMethod(‘Outputs’, @Outputs);
block.RegBlockMethod(‘Terminate’, @Terminate);
% Initialize UDP receiver
% Set output port sampling modes
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = ‘Sample’; % Set all output ports to Sample mode
end
block.SetAccelRunOnTLC(true);
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
function Outputs(block)
udpreceiver = udpport("LocalPort", 4141);
% Check if UDP receiver is valid
while true
if isvalid(udpreceiver)
% Check if a packet is available
if udpreceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpreceiver, udpreceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Output distances
block.OutputPort(1).Data = distance1;
block.OutputPort(2).Data = distance2;
block.OutputPort(3).Data = distance3;
block.OutputPort(4).Data = distance4;
end
end
end
function Terminate(block)
% Define a function to parse the received UDP packet
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
if numel(parts) == 2
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Even though it is the same code, the simulation gets terminated or the Data is wrong. What can i do?On an ESP32, I am sending distance data via UDP to MATLAB. There are multiple distances involved, so both the receiver number (from 81 to 84) and the respective distance are transmitted. I can also receive and analyze the data using the following program:
% Set up the UDP receiver
udpReceiver = udpport("LocalPort", 4141);
% Define a function to parse the received UDP packet
% Main loop to continuously receive and display distances
while true
% Check if a packet is available
if udpReceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpReceiver, udpReceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Display current distances
fprintf(‘Distance from Device 1: %.2f metersn’, distance1);
fprintf(‘Distance from Device 2: %.2f metersn’, distance2);
fprintf(‘Distance from Device 3: %.2f metersn’, distance3);
fprintf(‘Distance from Device 4: %.2f metersn’, distance4);
fprintf(‘n’); % Add newline for clarity
end
pause(0.1);
end
% Clean up
delete(udpReceiver)
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Now I want to further process only the respective distances in Simulink. For this, I have converted the code into a Level 2 MATLAB function. Here is the code for it:
function UDP_Receiver(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.NumDialogPrms = 0;
block.SampleTimes = [-1 0];
block.SimStateCompliance = ‘DefaultSimState’;
block.RegBlockMethod(‘SetInputPortSamplingMode’, @SetInpPortFrameData);
block.RegBlockMethod(‘Outputs’, @Outputs);
block.RegBlockMethod(‘Terminate’, @Terminate);
% Initialize UDP receiver
% Set output port sampling modes
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = ‘Sample’; % Set all output ports to Sample mode
end
block.SetAccelRunOnTLC(true);
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
function Outputs(block)
udpreceiver = udpport("LocalPort", 4141);
% Check if UDP receiver is valid
while true
if isvalid(udpreceiver)
% Check if a packet is available
if udpreceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpreceiver, udpreceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Output distances
block.OutputPort(1).Data = distance1;
block.OutputPort(2).Data = distance2;
block.OutputPort(3).Data = distance3;
block.OutputPort(4).Data = distance4;
end
end
end
function Terminate(block)
% Define a function to parse the received UDP packet
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
if numel(parts) == 2
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Even though it is the same code, the simulation gets terminated or the Data is wrong. What can i do? On an ESP32, I am sending distance data via UDP to MATLAB. There are multiple distances involved, so both the receiver number (from 81 to 84) and the respective distance are transmitted. I can also receive and analyze the data using the following program:
% Set up the UDP receiver
udpReceiver = udpport("LocalPort", 4141);
% Define a function to parse the received UDP packet
% Main loop to continuously receive and display distances
while true
% Check if a packet is available
if udpReceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpReceiver, udpReceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Display current distances
fprintf(‘Distance from Device 1: %.2f metersn’, distance1);
fprintf(‘Distance from Device 2: %.2f metersn’, distance2);
fprintf(‘Distance from Device 3: %.2f metersn’, distance3);
fprintf(‘Distance from Device 4: %.2f metersn’, distance4);
fprintf(‘n’); % Add newline for clarity
end
pause(0.1);
end
% Clean up
delete(udpReceiver)
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Now I want to further process only the respective distances in Simulink. For this, I have converted the code into a Level 2 MATLAB function. Here is the code for it:
function UDP_Receiver(block)
setup(block);
function setup(block)
block.NumInputPorts = 0;
block.NumOutputPorts = 4;
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
block.NumDialogPrms = 0;
block.SampleTimes = [-1 0];
block.SimStateCompliance = ‘DefaultSimState’;
block.RegBlockMethod(‘SetInputPortSamplingMode’, @SetInpPortFrameData);
block.RegBlockMethod(‘Outputs’, @Outputs);
block.RegBlockMethod(‘Terminate’, @Terminate);
% Initialize UDP receiver
% Set output port sampling modes
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = ‘Sample’; % Set all output ports to Sample mode
end
block.SetAccelRunOnTLC(true);
function SetInpPortFrameData(block, idx, fd)
block.InputPort(idx).SamplingMode = fd;
for i = 1:block.NumOutputPorts
block.OutputPort(i).SamplingMode = fd;
end
function Outputs(block)
udpreceiver = udpport("LocalPort", 4141);
% Check if UDP receiver is valid
while true
if isvalid(udpreceiver)
% Check if a packet is available
if udpreceiver.NumBytesAvailable > 0
% Read the packet
packet = read(udpreceiver, udpreceiver.NumBytesAvailable, "char");
% Parse the received packet
[distance1, distance2, distance3, distance4] = parsePacket(packet);
% Output distances
block.OutputPort(1).Data = distance1;
block.OutputPort(2).Data = distance2;
block.OutputPort(3).Data = distance3;
block.OutputPort(4).Data = distance4;
end
end
end
function Terminate(block)
% Define a function to parse the received UDP packet
function [distance1, distance2, distance3, distance4] = parsePacket(packet)
% Initialize distances
distance1 = NaN;
distance2 = NaN;
distance3 = NaN;
distance4 = NaN;
% Convert packet to string
packetStr = char(packet);
% Split the string by semicolon
data = strsplit(packetStr, ‘;’);
% Parse each part of the data
for i = 1:length(data)
% Split by comma to separate address and distance
parts = strsplit(data{i}, ‘,’);
if numel(parts) == 2
device = str2double(parts{1});
distance = str2double(parts{2});
% Assign distances based on address
switch device
case 1
distance1 = distance;
case 2
distance2 = distance;
case 3
distance3 = distance;
case 4
distance4 = distance;
end
end
end
Even though it is the same code, the simulation gets terminated or the Data is wrong. What can i do? udp, udp receive, simulink, level2 function MATLAB Answers — New Questions
Structure data obtained from webread
Hi, I would like to have to automatize a procedure to extract data from different URLs, One example of one URL link is the following:
% Generating the URL link
url=’https://earthquake.usgs.gov/fdsnws/event/1/query?format=quakeml&eventid=us6000n8tq’;
% Reading the data
data=webread(url);
The variable “data” contains huge amount of information that I would like to structure in order to access and retrieve data easily without the need of creating a xml file.
I would appreciate the help.Hi, I would like to have to automatize a procedure to extract data from different URLs, One example of one URL link is the following:
% Generating the URL link
url=’https://earthquake.usgs.gov/fdsnws/event/1/query?format=quakeml&eventid=us6000n8tq’;
% Reading the data
data=webread(url);
The variable “data” contains huge amount of information that I would like to structure in order to access and retrieve data easily without the need of creating a xml file.
I would appreciate the help. Hi, I would like to have to automatize a procedure to extract data from different URLs, One example of one URL link is the following:
% Generating the URL link
url=’https://earthquake.usgs.gov/fdsnws/event/1/query?format=quakeml&eventid=us6000n8tq’;
% Reading the data
data=webread(url);
The variable “data” contains huge amount of information that I would like to structure in order to access and retrieve data easily without the need of creating a xml file.
I would appreciate the help. structuring data from webread MATLAB Answers — New Questions
I don’t understand an error message I get that’s related to function ode45.
The error message I get is:
Arrays have incompatible sizes for this operation.
Error in ode45 (line 299)
y5 = y + h .* (b41.*f1 + b42.*f2 + b43.*f3 + b44.*f4 );
I’ve checked my initial condition vector is the correct size. I’m not sure what this error indicated might be wrong in my code.The error message I get is:
Arrays have incompatible sizes for this operation.
Error in ode45 (line 299)
y5 = y + h .* (b41.*f1 + b42.*f2 + b43.*f3 + b44.*f4 );
I’ve checked my initial condition vector is the correct size. I’m not sure what this error indicated might be wrong in my code. The error message I get is:
Arrays have incompatible sizes for this operation.
Error in ode45 (line 299)
y5 = y + h .* (b41.*f1 + b42.*f2 + b43.*f3 + b44.*f4 );
I’ve checked my initial condition vector is the correct size. I’m not sure what this error indicated might be wrong in my code. ode45, matlab MATLAB Answers — New Questions
how can solve this problem : Conversion to cell from double is not possible.
what the error (Error using Untitled18 (line 12)
Conversion to cell from double is not possible.)
% Ensure all columns except the last one are numeric
for i = 1:(width(data) – 1)
if iscell(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
elseif ischar(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
end
endwhat the error (Error using Untitled18 (line 12)
Conversion to cell from double is not possible.)
% Ensure all columns except the last one are numeric
for i = 1:(width(data) – 1)
if iscell(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
elseif ischar(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
end
end what the error (Error using Untitled18 (line 12)
Conversion to cell from double is not possible.)
% Ensure all columns except the last one are numeric
for i = 1:(width(data) – 1)
if iscell(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
elseif ischar(data{:, i})
data{:, i} = grp2idx(categorical(data{:, i}));
end
end axes, optimization MATLAB Answers — New Questions
How to count the number of non-nan values for combination of multiple variables
Hello, I would like to count the number of non-nan values in the d column for unique combinations of a, b and c (i.e I want to generate the e column in tt). If any a,b or c are NaN then the count should be nan as well
% Initial table
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
t = table(a,b,c,d)
% Desired output
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
e = [1, 1, 1, 2, 2, NaN, 1]’
tt = table(a,b,c,d,e)Hello, I would like to count the number of non-nan values in the d column for unique combinations of a, b and c (i.e I want to generate the e column in tt). If any a,b or c are NaN then the count should be nan as well
% Initial table
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
t = table(a,b,c,d)
% Desired output
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
e = [1, 1, 1, 2, 2, NaN, 1]’
tt = table(a,b,c,d,e) Hello, I would like to count the number of non-nan values in the d column for unique combinations of a, b and c (i.e I want to generate the e column in tt). If any a,b or c are NaN then the count should be nan as well
% Initial table
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
t = table(a,b,c,d)
% Desired output
a = [1,1,1,2,2,2,2]’
b = [660, 661, 661, 663, 663, NaN, 663]’
c = [1,2,2,5,5,NaN,6]’
d = [11,12,NaN, 13, 14, NaN,5]’
e = [1, 1, 1, 2, 2, NaN, 1]’
tt = table(a,b,c,d,e) sum MATLAB Answers — New Questions
Launching MATLAB2024a
Good day,
I have a challenge launching MATLAB2024a. I get an error message of "Why do I get an error of "You do not have a valid license file. How can I resolve this issue?
Your help will be much appreciated.
Kind regards,Good day,
I have a challenge launching MATLAB2024a. I get an error message of "Why do I get an error of "You do not have a valid license file. How can I resolve this issue?
Your help will be much appreciated.
Kind regards, Good day,
I have a challenge launching MATLAB2024a. I get an error message of "Why do I get an error of "You do not have a valid license file. How can I resolve this issue?
Your help will be much appreciated.
Kind regards, matlab, matlab2024a MATLAB Answers — New Questions
i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i have tried using pretty, symplify, ignoreanalyticconstraint,true and simplifyFraction, but none have worked
f(x) = -3, -pi < x < 0
f(x) = 3, 0 < x < pi
syms t n
T = 2*pi
w0 = 2*pi/T
n=1:5
a0 = (1/T)*int(3,t,-pi,0) + (1/T)*int(-3,t,0,pi)
an = (2/T)*int(-3*cos(n*w0*t),t,-pi,0) + (2/T)*int(3*cos(n*w0*t),t,0,pi)
bn = (2/T)*int(-3*sin(n*w0*t),t,-pi,0) + (2/T)*int(3*sin(n*w0*t),t,0,pi);
pretty(bn)i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i have tried using pretty, symplify, ignoreanalyticconstraint,true and simplifyFraction, but none have worked
f(x) = -3, -pi < x < 0
f(x) = 3, 0 < x < pi
syms t n
T = 2*pi
w0 = 2*pi/T
n=1:5
a0 = (1/T)*int(3,t,-pi,0) + (1/T)*int(-3,t,0,pi)
an = (2/T)*int(-3*cos(n*w0*t),t,-pi,0) + (2/T)*int(3*cos(n*w0*t),t,0,pi)
bn = (2/T)*int(-3*sin(n*w0*t),t,-pi,0) + (2/T)*int(3*sin(n*w0*t),t,0,pi);
pretty(bn) i am trying to find coefficients a0 , an and bn but the output for bn seems wrong and will not simplify
i have tried using pretty, symplify, ignoreanalyticconstraint,true and simplifyFraction, but none have worked
f(x) = -3, -pi < x < 0
f(x) = 3, 0 < x < pi
syms t n
T = 2*pi
w0 = 2*pi/T
n=1:5
a0 = (1/T)*int(3,t,-pi,0) + (1/T)*int(-3,t,0,pi)
an = (2/T)*int(-3*cos(n*w0*t),t,-pi,0) + (2/T)*int(3*cos(n*w0*t),t,0,pi)
bn = (2/T)*int(-3*sin(n*w0*t),t,-pi,0) + (2/T)*int(3*sin(n*w0*t),t,0,pi);
pretty(bn) fourier, coeffeicients, series, a0, bn, an MATLAB Answers — New Questions
How to include field value in ThingHTTP URL GET Request
I am trying to include a field value in a ThingHTTP GET request but have not been successful.
For example, I have have successfully used
https://myurl.com/site?value=12.34
to send a specifice value to an external site, but was unsuccessful when I tried to send a ThingSpeak channel field value in a similar way. I used the %% method, which works for ThingTweet, but that didn’t seem to work here. e.g.
https://myurl.com/site?value=%%channel_1234567_field_1%%
Am I doing something wrong, or is there an alternative method for doing this?I am trying to include a field value in a ThingHTTP GET request but have not been successful.
For example, I have have successfully used
https://myurl.com/site?value=12.34
to send a specifice value to an external site, but was unsuccessful when I tried to send a ThingSpeak channel field value in a similar way. I used the %% method, which works for ThingTweet, but that didn’t seem to work here. e.g.
https://myurl.com/site?value=%%channel_1234567_field_1%%
Am I doing something wrong, or is there an alternative method for doing this? I am trying to include a field value in a ThingHTTP GET request but have not been successful.
For example, I have have successfully used
https://myurl.com/site?value=12.34
to send a specifice value to an external site, but was unsuccessful when I tried to send a ThingSpeak channel field value in a similar way. I used the %% method, which works for ThingTweet, but that didn’t seem to work here. e.g.
https://myurl.com/site?value=%%channel_1234567_field_1%%
Am I doing something wrong, or is there an alternative method for doing this? thinghttp MATLAB Answers — New Questions