Category: Matlab
Category Archives: Matlab
Replacing one line (or one part of a line) in a text file
Hello. I have a config file that contains 1 specific line that I want to change just the number (in this case from 1000 to e.g. 235)
This is my code so far:
%Get current Value
FilePath=’C:Program FilesTeledyne DALSASaperaCamFilesUsermyCamera.ccf’
Filedata = readlines(FilePath)
TF = contains(Filedata,"Time Integrate Duration=")
k = find(TF,1);
expStr=Filedata(TF);
ReportMessage(app,expStr); %My report function that reports to a UITextarea
oldLine=Filedata(k)
Filedata(k) ="Time Integrate Duration=235" %this is the new line I want
[fid, msg] = fopen(‘FilePath’, ‘w’)
if fid < 1;
error(‘could not write output file because "%s"’, msg);
end
fwrite(fid, strjoin(Filedata, ‘n’));
fclose(fid);
But it doesn’t seem to be changing the file
I also enclose the config file (text)Hello. I have a config file that contains 1 specific line that I want to change just the number (in this case from 1000 to e.g. 235)
This is my code so far:
%Get current Value
FilePath=’C:Program FilesTeledyne DALSASaperaCamFilesUsermyCamera.ccf’
Filedata = readlines(FilePath)
TF = contains(Filedata,"Time Integrate Duration=")
k = find(TF,1);
expStr=Filedata(TF);
ReportMessage(app,expStr); %My report function that reports to a UITextarea
oldLine=Filedata(k)
Filedata(k) ="Time Integrate Duration=235" %this is the new line I want
[fid, msg] = fopen(‘FilePath’, ‘w’)
if fid < 1;
error(‘could not write output file because "%s"’, msg);
end
fwrite(fid, strjoin(Filedata, ‘n’));
fclose(fid);
But it doesn’t seem to be changing the file
I also enclose the config file (text) Hello. I have a config file that contains 1 specific line that I want to change just the number (in this case from 1000 to e.g. 235)
This is my code so far:
%Get current Value
FilePath=’C:Program FilesTeledyne DALSASaperaCamFilesUsermyCamera.ccf’
Filedata = readlines(FilePath)
TF = contains(Filedata,"Time Integrate Duration=")
k = find(TF,1);
expStr=Filedata(TF);
ReportMessage(app,expStr); %My report function that reports to a UITextarea
oldLine=Filedata(k)
Filedata(k) ="Time Integrate Duration=235" %this is the new line I want
[fid, msg] = fopen(‘FilePath’, ‘w’)
if fid < 1;
error(‘could not write output file because "%s"’, msg);
end
fwrite(fid, strjoin(Filedata, ‘n’));
fclose(fid);
But it doesn’t seem to be changing the file
I also enclose the config file (text) readlines, contains, fwrite MATLAB Answers — New Questions
Why does MATLAB Runtime cache (CTF extraction path) get corrupted after running the executable for several number of times?
We have a .NET application where functions of a MATLAB Compiler SDK generated DLL are called.
It happens that the MATLAB Runtime cache gets corrupt, such that executing the DLL function always results in error.
This happens only after running the application for several number of times. When I manually delete the entire MATLAB Runtime cache directory helps resolving the issue. I am wondering what could be the reason for corrupted CTF extraction.We have a .NET application where functions of a MATLAB Compiler SDK generated DLL are called.
It happens that the MATLAB Runtime cache gets corrupt, such that executing the DLL function always results in error.
This happens only after running the application for several number of times. When I manually delete the entire MATLAB Runtime cache directory helps resolving the issue. I am wondering what could be the reason for corrupted CTF extraction. We have a .NET application where functions of a MATLAB Compiler SDK generated DLL are called.
It happens that the MATLAB Runtime cache gets corrupt, such that executing the DLL function always results in error.
This happens only after running the application for several number of times. When I manually delete the entire MATLAB Runtime cache directory helps resolving the issue. I am wondering what could be the reason for corrupted CTF extraction. corrupted, mcr MATLAB Answers — New Questions
3D system definition: How btaining the angle between a single axis and a plane
Hello, I am having trouble obtaining the angle between a vector and a plane which are defined by two different rotation matrix.
I have two objects, A and B, which are defined by rotation matrices R (Rotation matrix from global origin to A) and R’ (Rotation matrix from global origin to B).
R = [a b c; d e f; g h i]
R’= [a’ b’ c’; d’ e’ f’; g’ h’ i’]
I want to obtain the rotation in degrees between the axis X from object A to the plane XZ (and eventually XY) from object B.
Thank you in advance.
AlonsoHello, I am having trouble obtaining the angle between a vector and a plane which are defined by two different rotation matrix.
I have two objects, A and B, which are defined by rotation matrices R (Rotation matrix from global origin to A) and R’ (Rotation matrix from global origin to B).
R = [a b c; d e f; g h i]
R’= [a’ b’ c’; d’ e’ f’; g’ h’ i’]
I want to obtain the rotation in degrees between the axis X from object A to the plane XZ (and eventually XY) from object B.
Thank you in advance.
Alonso Hello, I am having trouble obtaining the angle between a vector and a plane which are defined by two different rotation matrix.
I have two objects, A and B, which are defined by rotation matrices R (Rotation matrix from global origin to A) and R’ (Rotation matrix from global origin to B).
R = [a b c; d e f; g h i]
R’= [a’ b’ c’; d’ e’ f’; g’ h’ i’]
I want to obtain the rotation in degrees between the axis X from object A to the plane XZ (and eventually XY) from object B.
Thank you in advance.
Alonso 3d kinematics, rotation matrices MATLAB Answers — New Questions
Performance Issue using cell() to convert Python data types to Matlab
I have a Python list of 50,000 elements in Matlab, and using the cell() function to convert it to Matlab cell array is taking over an hour, while on my coworkers machine it takes less than a minute. We are both using Python 3.9, Matlab 2021b, and my VM is v4cpu 16G RAM. Also, when trying to pause or stop the execution of cell() Matlab freezes, and has to be forcefully shut down.
Note – The code below executed instantly in this website, but takes over an hour on Matlab 2021b installed on my local.
pyrun("py_list = list(range(50000))");
cellArray = cell(pyrun(‘py_list’, ‘py_list’));I have a Python list of 50,000 elements in Matlab, and using the cell() function to convert it to Matlab cell array is taking over an hour, while on my coworkers machine it takes less than a minute. We are both using Python 3.9, Matlab 2021b, and my VM is v4cpu 16G RAM. Also, when trying to pause or stop the execution of cell() Matlab freezes, and has to be forcefully shut down.
Note – The code below executed instantly in this website, but takes over an hour on Matlab 2021b installed on my local.
pyrun("py_list = list(range(50000))");
cellArray = cell(pyrun(‘py_list’, ‘py_list’)); I have a Python list of 50,000 elements in Matlab, and using the cell() function to convert it to Matlab cell array is taking over an hour, while on my coworkers machine it takes less than a minute. We are both using Python 3.9, Matlab 2021b, and my VM is v4cpu 16G RAM. Also, when trying to pause or stop the execution of cell() Matlab freezes, and has to be forcefully shut down.
Note – The code below executed instantly in this website, but takes over an hour on Matlab 2021b installed on my local.
pyrun("py_list = list(range(50000))");
cellArray = cell(pyrun(‘py_list’, ‘py_list’)); python, cell MATLAB Answers — New Questions
Line following AGV Simulation Issue
I’m planning to simulate a warehouse with line following AGVs. I would like the warehouse as the one in Mobile Robotics Simulation Toolbox. However, instead of using probabilistic methods, I want each robot to strictly follow predefined paths/lines without deviating. How can I configure these paths and ensure the robots follow them while avoiding collisions with each other? Thank you
Control and Simulate Multiple Warehouse Robots – MATLAB & Simulink (mathworks.com)I’m planning to simulate a warehouse with line following AGVs. I would like the warehouse as the one in Mobile Robotics Simulation Toolbox. However, instead of using probabilistic methods, I want each robot to strictly follow predefined paths/lines without deviating. How can I configure these paths and ensure the robots follow them while avoiding collisions with each other? Thank you
Control and Simulate Multiple Warehouse Robots – MATLAB & Simulink (mathworks.com) I’m planning to simulate a warehouse with line following AGVs. I would like the warehouse as the one in Mobile Robotics Simulation Toolbox. However, instead of using probabilistic methods, I want each robot to strictly follow predefined paths/lines without deviating. How can I configure these paths and ensure the robots follow them while avoiding collisions with each other? Thank you
Control and Simulate Multiple Warehouse Robots – MATLAB & Simulink (mathworks.com) control, line, warehouse, robots, robot, robotics, mobile robotics simulation toolbox, mobile, agv MATLAB Answers — New Questions
How to resolve the error “Could not access MATLAB Runtime component cache fl:filesystem:InvalidArgument”?
I am attempting to run a compiled application. However, I am encountering the following error:
Could not access the MATLAB Runtime component cache.
Details: fl:filesystem:InvalidArgument; component cache root:;
componentname: APP_NAME
How can I resolve this error?I am attempting to run a compiled application. However, I am encountering the following error:
Could not access the MATLAB Runtime component cache.
Details: fl:filesystem:InvalidArgument; component cache root:;
componentname: APP_NAME
How can I resolve this error? I am attempting to run a compiled application. However, I am encountering the following error:
Could not access the MATLAB Runtime component cache.
Details: fl:filesystem:InvalidArgument; component cache root:;
componentname: APP_NAME
How can I resolve this error? mcr, runtime, component, cache, deployed, app, application MATLAB Answers — New Questions
Finding intersection between line plot and horizontal line
I’ve been trying to find the full width at half max (FWHM) some data points. There are about 1000 data points (intensity on the y and angle on the x), and when I plot them, there is a line drawn to connect all the points. My current method for calculating the FWHM is to use the find function and locate the points in the original data that are closest to the half max.
Is it possible to use the line drawn to connect all the points and find the intersection between that and a horizontal line at the half max? I’ve tired using the find function like:
intersection = find(intensity == halfMax);
However this returns an empty vector (unsurprisngly). If there was a way to access the points on the line that connect my original data, this would make it a more accurate calculation.
The attached graph is semilogy, please let me know if you know it this is possible or need clarification.I’ve been trying to find the full width at half max (FWHM) some data points. There are about 1000 data points (intensity on the y and angle on the x), and when I plot them, there is a line drawn to connect all the points. My current method for calculating the FWHM is to use the find function and locate the points in the original data that are closest to the half max.
Is it possible to use the line drawn to connect all the points and find the intersection between that and a horizontal line at the half max? I’ve tired using the find function like:
intersection = find(intensity == halfMax);
However this returns an empty vector (unsurprisngly). If there was a way to access the points on the line that connect my original data, this would make it a more accurate calculation.
The attached graph is semilogy, please let me know if you know it this is possible or need clarification. I’ve been trying to find the full width at half max (FWHM) some data points. There are about 1000 data points (intensity on the y and angle on the x), and when I plot them, there is a line drawn to connect all the points. My current method for calculating the FWHM is to use the find function and locate the points in the original data that are closest to the half max.
Is it possible to use the line drawn to connect all the points and find the intersection between that and a horizontal line at the half max? I’ve tired using the find function like:
intersection = find(intensity == halfMax);
However this returns an empty vector (unsurprisngly). If there was a way to access the points on the line that connect my original data, this would make it a more accurate calculation.
The attached graph is semilogy, please let me know if you know it this is possible or need clarification. fwhm, data plot MATLAB Answers — New Questions
Error in for loop: Index exceeds matrix dimensions.
Hi everyone! I need help with my code.I have a matrix (300×300) with some equal rows, and I need to eliminate the duplicate rows. I can’t solve the error. Can anyone help me??Thank you very much!
Below I copy the part of the code with the error and a simplified example.
clear all
matrix_f=[1 2 3; 1 2 3; 4 5 6; 7 8 9; 7 8 9; 10 11 12];
for k=1:length(matrix_f(:,1))
if matrix_f(k,1)==matrix_f(k+1,1)
matrix_f(k+1,:)=[];
end
endHi everyone! I need help with my code.I have a matrix (300×300) with some equal rows, and I need to eliminate the duplicate rows. I can’t solve the error. Can anyone help me??Thank you very much!
Below I copy the part of the code with the error and a simplified example.
clear all
matrix_f=[1 2 3; 1 2 3; 4 5 6; 7 8 9; 7 8 9; 10 11 12];
for k=1:length(matrix_f(:,1))
if matrix_f(k,1)==matrix_f(k+1,1)
matrix_f(k+1,:)=[];
end
end Hi everyone! I need help with my code.I have a matrix (300×300) with some equal rows, and I need to eliminate the duplicate rows. I can’t solve the error. Can anyone help me??Thank you very much!
Below I copy the part of the code with the error and a simplified example.
clear all
matrix_f=[1 2 3; 1 2 3; 4 5 6; 7 8 9; 7 8 9; 10 11 12];
for k=1:length(matrix_f(:,1))
if matrix_f(k,1)==matrix_f(k+1,1)
matrix_f(k+1,:)=[];
end
end for, for loop, matrix, index exceeds matrix dimensions. MATLAB Answers — New Questions
finding the remainder of the division of two symbolic variables
I want to get 2*V^2 from the operation below
syms A V
rem(2*V^2+3A,A)
but it seems like rem() function does not work with symbolic variables. Is there a way to achieve this in another way?I want to get 2*V^2 from the operation below
syms A V
rem(2*V^2+3A,A)
but it seems like rem() function does not work with symbolic variables. Is there a way to achieve this in another way? I want to get 2*V^2 from the operation below
syms A V
rem(2*V^2+3A,A)
but it seems like rem() function does not work with symbolic variables. Is there a way to achieve this in another way? symbolic MATLAB Answers — New Questions
Parfeval with backgorund pool cannot read XML file
Inside the parfeval I am using xml_read with an XML path. This function works properly with a parpool object but not with a backgorundPoolInside the parfeval I am using xml_read with an XML path. This function works properly with a parpool object but not with a backgorundPool Inside the parfeval I am using xml_read with an XML path. This function works properly with a parpool object but not with a backgorundPool backgroundpool, parfeval MATLAB Answers — New Questions
code does not call a designed function that works in other program
Hello and sorry for this long query. I am not very good at this , I have to admit it.
I am encountering an issue when trying to apply custom boundary conditions in a PDE model using MATLAB. Specifically, I have a custom boundary condition function mybc1 that works correctly in another code when using structuralBC to apply displacement conditions to vertices. However, in my current code, when I try to use applyBoundaryCondition to set mixed boundary conditions on specific faces, it seems that the solver does not enter the custom boundary condition function mybc1.
Here’s a brief description of what I am trying to do:
Model Definition: I have defined a PDE model with certain geometry and mesh.
Boundary Condition Application: I attempt to apply mixed boundary conditions on specific faces using applyBoundaryCondition with the u parameter set to a custom function handle @(location, state)mybc1(location, state, dis, ts, in).
Issue: It appears that the solver does not call the mybc1 function during the solution process. I verified this by setting breakpoints inside mybc1, which are never hit.
The mybc1 function interpolates the acceleration data (dis) at the times specified by the solver (state.time) and returns the corresponding values. This function has been tested and works correctly in another program with structuralBC.
code as follows:
%____________Define dimensions of the plate________________________________
len = 1.22; % length in x direction
width = 1.22; % Width in y direction
sq_side = 0.10; % Side length of the squares in corners
% Create the geometry description matrix___________________________________
% —–Define the outer boundary——————————————-
outer_boundary = [3, 4, 0, len, len, 0, 0, 0, width, width]’;
%——Define squares in the corners—————————————
square_1 = [3, 4, 0, sq_side, sq_side, 0, 0, 0, sq_side, sq_side]’;
square_2 = [3, 4, len – sq_side, len, len, len – sq_side, 0, 0, sq_side, sq_side]’;
square_3 = [3, 4, len – sq_side, len, len, len – sq_side, width – sq_side, width – sq_side, width, width]’;
square_4 = [3, 4, 0, sq_side, sq_side, 0, width – sq_side, width – sq_side, width, width]’;
%——Combine all the geometries——————————————
gdm = [outer_boundary, square_1, square_2, square_3, square_4];
%——Define the names for each region————————————
ns = (char(‘R1′,’R2′,’R3′,’R4′,’R5′))’;
sf = ‘R1+R2+R3+R4+R5’;
%——-Create the geometry————————————————
model = createpde(2);
geometryFromEdges(model, decsg(gdm, sf, ns));
%——-Generate the mesh and plot the geometry—————————-
msh = generateMesh(model, ‘Hmax’, 0.1); % Use ‘Hmax’ to control mesh density
figure
pdemesh(model)
%_____________Create the different regions of the model___________________
% Obtain nodes and elements of the mesh
[p,e,t] = meshToPet(model.Mesh);
% ———-Plot with Faces labels—————————————-
figure;
pdegplot(model, ‘FaceLabels’, ‘on’, ‘FaceAlpha’, 0.5);
figure
pdemesh(model, ‘NodeLabels’, ‘on’);
% Definition of the constants
E = 4E9;
h_thick = 0.05;
nu = 0.3;
mass = 100;
D = E*h_thick^3/(12*(1-nu)^2);
% Now we create the PDE systems as symbolic equations_____________________
syms pres
syms u1(x,y,t) u2(x,y,t)
pdeeq = [-laplacian(u1,[x y])+u2; D*laplacian(u2,[x y])+ mass*diff(u1,t,t)-pres];
symcoeffs = pdeCoefficients(pdeeq,[u1,u2],’Symbolic’,true);
c2=symcoeffs.c;
m2=symcoeffs.m;
%——Display the symbolic coefficients———————————–
structfun(@disp,symcoeffs);
symcoeffs=subs(symcoeffs,pres,1);
coeffs=pdeCoefficientsToDouble(symcoeffs);
%——pass these coefficients to the pde model—————————-
specifyCoefficients(model,’m’,coeffs.m,’d’,coeffs.d,’c’,…
coeffs.c,’a’,coeffs.a,’f’,coeffs.f);
% INITIAL CONDITIONS ——————————————————
setInitialConditions(model,[0;0],[0;0]);
%USE THE DATA FROM ASHMOLEAN AS BOUNDARY CONDITIONS————————
%load the vector containing the acceleration values
load(totaldata.mat’, ‘DATA’,…
‘TIME’,’fs’);
ac=DATA;
% ——-Create vector time, not starting in 0
num_samples = size(DATA, 1);
dt = 1 / fs; % interval between measurements
t = (1:num_samples) * dt; % vector of times
% TRANSFORM ACCELERATIONS INTO DISPLACEMENTS_______________________________
acvedi=AccVelDis(962.54,1005.11,992.35,ac,fs,t);
dis=acvedi{3};
t=[0,t]; % I start the time at 0
% Boundary conditions in the faces using the displacement vectors
in=0; %counter variable
Faces=[1,2,3,5]; %Vector with faces numbers
for jk = 1:numel(Faces)
in=in+1;%add 1 in every loop to access the different measurmentes contained in the matrix acceleration
face= Faces(jk);
dis1=dis(:,in);
applyBoundaryCondition(model,"mixed","Face",[face,face],"u",@(location,state)mybc1(location,state,dis1,t),"EquationIndex",1,"q",[0 0],"g",0);
%applyBoundaryCondition(model,"dirichlet","Face",face,"h",[0 0 ; 0 1],"r",bcfunc)
end
in=0;
tim=[t(2) t(3)]; %tim represents the time of interest to solve the pde
res=solvepde(model, tim);
% Access the solution at the nodal locations
sol=res.NodalSolution;
And this is the function that works in another code:
function bcMatrix = mybc1(location,state,acs,ti)
%This function is use to extrapolate the values of acceleration for the
%time instances chosen by the system to do the integration of the system.
%as imput it requires the measurements matrix and the corresponding time
%measurements. As output, it provices the extrapoleted values for the state
%time
T=state.time;
% Check if T is NaN and assign the previous value if true
if isnan(T)
vq = NaN(size(location.x)); %this is what documentation says????
else
ac = acs; %gets the value of the corresponding acceleration
vq = interp1(ti, ac, T); %interpolates it
end
bcMatrix = vq;
end
I would really appreciate any help/guidanceHello and sorry for this long query. I am not very good at this , I have to admit it.
I am encountering an issue when trying to apply custom boundary conditions in a PDE model using MATLAB. Specifically, I have a custom boundary condition function mybc1 that works correctly in another code when using structuralBC to apply displacement conditions to vertices. However, in my current code, when I try to use applyBoundaryCondition to set mixed boundary conditions on specific faces, it seems that the solver does not enter the custom boundary condition function mybc1.
Here’s a brief description of what I am trying to do:
Model Definition: I have defined a PDE model with certain geometry and mesh.
Boundary Condition Application: I attempt to apply mixed boundary conditions on specific faces using applyBoundaryCondition with the u parameter set to a custom function handle @(location, state)mybc1(location, state, dis, ts, in).
Issue: It appears that the solver does not call the mybc1 function during the solution process. I verified this by setting breakpoints inside mybc1, which are never hit.
The mybc1 function interpolates the acceleration data (dis) at the times specified by the solver (state.time) and returns the corresponding values. This function has been tested and works correctly in another program with structuralBC.
code as follows:
%____________Define dimensions of the plate________________________________
len = 1.22; % length in x direction
width = 1.22; % Width in y direction
sq_side = 0.10; % Side length of the squares in corners
% Create the geometry description matrix___________________________________
% —–Define the outer boundary——————————————-
outer_boundary = [3, 4, 0, len, len, 0, 0, 0, width, width]’;
%——Define squares in the corners—————————————
square_1 = [3, 4, 0, sq_side, sq_side, 0, 0, 0, sq_side, sq_side]’;
square_2 = [3, 4, len – sq_side, len, len, len – sq_side, 0, 0, sq_side, sq_side]’;
square_3 = [3, 4, len – sq_side, len, len, len – sq_side, width – sq_side, width – sq_side, width, width]’;
square_4 = [3, 4, 0, sq_side, sq_side, 0, width – sq_side, width – sq_side, width, width]’;
%——Combine all the geometries——————————————
gdm = [outer_boundary, square_1, square_2, square_3, square_4];
%——Define the names for each region————————————
ns = (char(‘R1′,’R2′,’R3′,’R4′,’R5′))’;
sf = ‘R1+R2+R3+R4+R5’;
%——-Create the geometry————————————————
model = createpde(2);
geometryFromEdges(model, decsg(gdm, sf, ns));
%——-Generate the mesh and plot the geometry—————————-
msh = generateMesh(model, ‘Hmax’, 0.1); % Use ‘Hmax’ to control mesh density
figure
pdemesh(model)
%_____________Create the different regions of the model___________________
% Obtain nodes and elements of the mesh
[p,e,t] = meshToPet(model.Mesh);
% ———-Plot with Faces labels—————————————-
figure;
pdegplot(model, ‘FaceLabels’, ‘on’, ‘FaceAlpha’, 0.5);
figure
pdemesh(model, ‘NodeLabels’, ‘on’);
% Definition of the constants
E = 4E9;
h_thick = 0.05;
nu = 0.3;
mass = 100;
D = E*h_thick^3/(12*(1-nu)^2);
% Now we create the PDE systems as symbolic equations_____________________
syms pres
syms u1(x,y,t) u2(x,y,t)
pdeeq = [-laplacian(u1,[x y])+u2; D*laplacian(u2,[x y])+ mass*diff(u1,t,t)-pres];
symcoeffs = pdeCoefficients(pdeeq,[u1,u2],’Symbolic’,true);
c2=symcoeffs.c;
m2=symcoeffs.m;
%——Display the symbolic coefficients———————————–
structfun(@disp,symcoeffs);
symcoeffs=subs(symcoeffs,pres,1);
coeffs=pdeCoefficientsToDouble(symcoeffs);
%——pass these coefficients to the pde model—————————-
specifyCoefficients(model,’m’,coeffs.m,’d’,coeffs.d,’c’,…
coeffs.c,’a’,coeffs.a,’f’,coeffs.f);
% INITIAL CONDITIONS ——————————————————
setInitialConditions(model,[0;0],[0;0]);
%USE THE DATA FROM ASHMOLEAN AS BOUNDARY CONDITIONS————————
%load the vector containing the acceleration values
load(totaldata.mat’, ‘DATA’,…
‘TIME’,’fs’);
ac=DATA;
% ——-Create vector time, not starting in 0
num_samples = size(DATA, 1);
dt = 1 / fs; % interval between measurements
t = (1:num_samples) * dt; % vector of times
% TRANSFORM ACCELERATIONS INTO DISPLACEMENTS_______________________________
acvedi=AccVelDis(962.54,1005.11,992.35,ac,fs,t);
dis=acvedi{3};
t=[0,t]; % I start the time at 0
% Boundary conditions in the faces using the displacement vectors
in=0; %counter variable
Faces=[1,2,3,5]; %Vector with faces numbers
for jk = 1:numel(Faces)
in=in+1;%add 1 in every loop to access the different measurmentes contained in the matrix acceleration
face= Faces(jk);
dis1=dis(:,in);
applyBoundaryCondition(model,"mixed","Face",[face,face],"u",@(location,state)mybc1(location,state,dis1,t),"EquationIndex",1,"q",[0 0],"g",0);
%applyBoundaryCondition(model,"dirichlet","Face",face,"h",[0 0 ; 0 1],"r",bcfunc)
end
in=0;
tim=[t(2) t(3)]; %tim represents the time of interest to solve the pde
res=solvepde(model, tim);
% Access the solution at the nodal locations
sol=res.NodalSolution;
And this is the function that works in another code:
function bcMatrix = mybc1(location,state,acs,ti)
%This function is use to extrapolate the values of acceleration for the
%time instances chosen by the system to do the integration of the system.
%as imput it requires the measurements matrix and the corresponding time
%measurements. As output, it provices the extrapoleted values for the state
%time
T=state.time;
% Check if T is NaN and assign the previous value if true
if isnan(T)
vq = NaN(size(location.x)); %this is what documentation says????
else
ac = acs; %gets the value of the corresponding acceleration
vq = interp1(ti, ac, T); %interpolates it
end
bcMatrix = vq;
end
I would really appreciate any help/guidance Hello and sorry for this long query. I am not very good at this , I have to admit it.
I am encountering an issue when trying to apply custom boundary conditions in a PDE model using MATLAB. Specifically, I have a custom boundary condition function mybc1 that works correctly in another code when using structuralBC to apply displacement conditions to vertices. However, in my current code, when I try to use applyBoundaryCondition to set mixed boundary conditions on specific faces, it seems that the solver does not enter the custom boundary condition function mybc1.
Here’s a brief description of what I am trying to do:
Model Definition: I have defined a PDE model with certain geometry and mesh.
Boundary Condition Application: I attempt to apply mixed boundary conditions on specific faces using applyBoundaryCondition with the u parameter set to a custom function handle @(location, state)mybc1(location, state, dis, ts, in).
Issue: It appears that the solver does not call the mybc1 function during the solution process. I verified this by setting breakpoints inside mybc1, which are never hit.
The mybc1 function interpolates the acceleration data (dis) at the times specified by the solver (state.time) and returns the corresponding values. This function has been tested and works correctly in another program with structuralBC.
code as follows:
%____________Define dimensions of the plate________________________________
len = 1.22; % length in x direction
width = 1.22; % Width in y direction
sq_side = 0.10; % Side length of the squares in corners
% Create the geometry description matrix___________________________________
% —–Define the outer boundary——————————————-
outer_boundary = [3, 4, 0, len, len, 0, 0, 0, width, width]’;
%——Define squares in the corners—————————————
square_1 = [3, 4, 0, sq_side, sq_side, 0, 0, 0, sq_side, sq_side]’;
square_2 = [3, 4, len – sq_side, len, len, len – sq_side, 0, 0, sq_side, sq_side]’;
square_3 = [3, 4, len – sq_side, len, len, len – sq_side, width – sq_side, width – sq_side, width, width]’;
square_4 = [3, 4, 0, sq_side, sq_side, 0, width – sq_side, width – sq_side, width, width]’;
%——Combine all the geometries——————————————
gdm = [outer_boundary, square_1, square_2, square_3, square_4];
%——Define the names for each region————————————
ns = (char(‘R1′,’R2′,’R3′,’R4′,’R5′))’;
sf = ‘R1+R2+R3+R4+R5’;
%——-Create the geometry————————————————
model = createpde(2);
geometryFromEdges(model, decsg(gdm, sf, ns));
%——-Generate the mesh and plot the geometry—————————-
msh = generateMesh(model, ‘Hmax’, 0.1); % Use ‘Hmax’ to control mesh density
figure
pdemesh(model)
%_____________Create the different regions of the model___________________
% Obtain nodes and elements of the mesh
[p,e,t] = meshToPet(model.Mesh);
% ———-Plot with Faces labels—————————————-
figure;
pdegplot(model, ‘FaceLabels’, ‘on’, ‘FaceAlpha’, 0.5);
figure
pdemesh(model, ‘NodeLabels’, ‘on’);
% Definition of the constants
E = 4E9;
h_thick = 0.05;
nu = 0.3;
mass = 100;
D = E*h_thick^3/(12*(1-nu)^2);
% Now we create the PDE systems as symbolic equations_____________________
syms pres
syms u1(x,y,t) u2(x,y,t)
pdeeq = [-laplacian(u1,[x y])+u2; D*laplacian(u2,[x y])+ mass*diff(u1,t,t)-pres];
symcoeffs = pdeCoefficients(pdeeq,[u1,u2],’Symbolic’,true);
c2=symcoeffs.c;
m2=symcoeffs.m;
%——Display the symbolic coefficients———————————–
structfun(@disp,symcoeffs);
symcoeffs=subs(symcoeffs,pres,1);
coeffs=pdeCoefficientsToDouble(symcoeffs);
%——pass these coefficients to the pde model—————————-
specifyCoefficients(model,’m’,coeffs.m,’d’,coeffs.d,’c’,…
coeffs.c,’a’,coeffs.a,’f’,coeffs.f);
% INITIAL CONDITIONS ——————————————————
setInitialConditions(model,[0;0],[0;0]);
%USE THE DATA FROM ASHMOLEAN AS BOUNDARY CONDITIONS————————
%load the vector containing the acceleration values
load(totaldata.mat’, ‘DATA’,…
‘TIME’,’fs’);
ac=DATA;
% ——-Create vector time, not starting in 0
num_samples = size(DATA, 1);
dt = 1 / fs; % interval between measurements
t = (1:num_samples) * dt; % vector of times
% TRANSFORM ACCELERATIONS INTO DISPLACEMENTS_______________________________
acvedi=AccVelDis(962.54,1005.11,992.35,ac,fs,t);
dis=acvedi{3};
t=[0,t]; % I start the time at 0
% Boundary conditions in the faces using the displacement vectors
in=0; %counter variable
Faces=[1,2,3,5]; %Vector with faces numbers
for jk = 1:numel(Faces)
in=in+1;%add 1 in every loop to access the different measurmentes contained in the matrix acceleration
face= Faces(jk);
dis1=dis(:,in);
applyBoundaryCondition(model,"mixed","Face",[face,face],"u",@(location,state)mybc1(location,state,dis1,t),"EquationIndex",1,"q",[0 0],"g",0);
%applyBoundaryCondition(model,"dirichlet","Face",face,"h",[0 0 ; 0 1],"r",bcfunc)
end
in=0;
tim=[t(2) t(3)]; %tim represents the time of interest to solve the pde
res=solvepde(model, tim);
% Access the solution at the nodal locations
sol=res.NodalSolution;
And this is the function that works in another code:
function bcMatrix = mybc1(location,state,acs,ti)
%This function is use to extrapolate the values of acceleration for the
%time instances chosen by the system to do the integration of the system.
%as imput it requires the measurements matrix and the corresponding time
%measurements. As output, it provices the extrapoleted values for the state
%time
T=state.time;
% Check if T is NaN and assign the previous value if true
if isnan(T)
vq = NaN(size(location.x)); %this is what documentation says????
else
ac = acs; %gets the value of the corresponding acceleration
vq = interp1(ti, ac, T); %interpolates it
end
bcMatrix = vq;
end
I would really appreciate any help/guidance handles, pde, applyboundaryconditions, function, differential equations MATLAB Answers — New Questions
Friend Function implementation in MATLAB
Typically, the private properties of a class are not accessible by any other class or function from outside.
But, a friend function can be granted special access to private and protected members of a class in C++.
For further reference: https://en.cppreference.com/w/cpp/language/friend
Is there any way, I can implement this in MATLAB?
It would be really helpful if anyone could provide a sample code illustrating the implementation in MATLAB.
Thanks in advance.Typically, the private properties of a class are not accessible by any other class or function from outside.
But, a friend function can be granted special access to private and protected members of a class in C++.
For further reference: https://en.cppreference.com/w/cpp/language/friend
Is there any way, I can implement this in MATLAB?
It would be really helpful if anyone could provide a sample code illustrating the implementation in MATLAB.
Thanks in advance. Typically, the private properties of a class are not accessible by any other class or function from outside.
But, a friend function can be granted special access to private and protected members of a class in C++.
For further reference: https://en.cppreference.com/w/cpp/language/friend
Is there any way, I can implement this in MATLAB?
It would be really helpful if anyone could provide a sample code illustrating the implementation in MATLAB.
Thanks in advance. matlab, oop, programming MATLAB Answers — New Questions
How to use indices of one matrix as entries of another matrix?
Hello, I have two matrices, M1 ans M2. They both have rows and columns fom 0 to 9 and a to f (16 * 16) matrix.
Mi matrix is filled with random numbers form 0 to 255 in hex decimal notation.
The second matrix M2 is empty but has the same row and column indexs. I need to fill M2 with the help of M1. For eample, in M2, at row 3 and colm 4 ( 34,the first entry of M1) will be 00 ( index of the first entry of M1). In M2 at row 6 col A, the entry will be 01, at row 2 col 9, the entry will be 02, and so on.
%% % Initialize M2 with zeros
M2 = zeros(16,16);
for row = 0:15
for col = 0:15
% get the value from M1
value= M1(row+1,col+1);
% Convert the values to row and col indices for M2
hexStr=dec2hex(value,2); % convert to 2 digit hex
M2_row=hex2dec(hexStr(1))+1;% convert first digit to decimal
M2_col=hex2dec(hexStr(2))+1;% convert first digit to decimal
% %Debugging
% % place the original rows and columns in M2
%
M2(M2_row, M2_col)=row*16+col;
end
end
M2;
If anyone can help.Hello, I have two matrices, M1 ans M2. They both have rows and columns fom 0 to 9 and a to f (16 * 16) matrix.
Mi matrix is filled with random numbers form 0 to 255 in hex decimal notation.
The second matrix M2 is empty but has the same row and column indexs. I need to fill M2 with the help of M1. For eample, in M2, at row 3 and colm 4 ( 34,the first entry of M1) will be 00 ( index of the first entry of M1). In M2 at row 6 col A, the entry will be 01, at row 2 col 9, the entry will be 02, and so on.
%% % Initialize M2 with zeros
M2 = zeros(16,16);
for row = 0:15
for col = 0:15
% get the value from M1
value= M1(row+1,col+1);
% Convert the values to row and col indices for M2
hexStr=dec2hex(value,2); % convert to 2 digit hex
M2_row=hex2dec(hexStr(1))+1;% convert first digit to decimal
M2_col=hex2dec(hexStr(2))+1;% convert first digit to decimal
% %Debugging
% % place the original rows and columns in M2
%
M2(M2_row, M2_col)=row*16+col;
end
end
M2;
If anyone can help. Hello, I have two matrices, M1 ans M2. They both have rows and columns fom 0 to 9 and a to f (16 * 16) matrix.
Mi matrix is filled with random numbers form 0 to 255 in hex decimal notation.
The second matrix M2 is empty but has the same row and column indexs. I need to fill M2 with the help of M1. For eample, in M2, at row 3 and colm 4 ( 34,the first entry of M1) will be 00 ( index of the first entry of M1). In M2 at row 6 col A, the entry will be 01, at row 2 col 9, the entry will be 02, and so on.
%% % Initialize M2 with zeros
M2 = zeros(16,16);
for row = 0:15
for col = 0:15
% get the value from M1
value= M1(row+1,col+1);
% Convert the values to row and col indices for M2
hexStr=dec2hex(value,2); % convert to 2 digit hex
M2_row=hex2dec(hexStr(1))+1;% convert first digit to decimal
M2_col=hex2dec(hexStr(2))+1;% convert first digit to decimal
% %Debugging
% % place the original rows and columns in M2
%
M2(M2_row, M2_col)=row*16+col;
end
end
M2;
If anyone can help. matrix indexes MATLAB Answers — New Questions
How to create an overall legend that includes all appeared data groups?
I’m trying to make a plot, using the tiledlayout function to create 4 subplots, while in the first subplot, there are 5 data groups, while the remaining subplots only have four of those 5 groups. If I create an overall legend, it will only show 4 groups that appeared in all the subplots, and automatically omit the extra one that’s only shown in the first subplot, how to include that grounp into the overall legend as well? Thanks!I’m trying to make a plot, using the tiledlayout function to create 4 subplots, while in the first subplot, there are 5 data groups, while the remaining subplots only have four of those 5 groups. If I create an overall legend, it will only show 4 groups that appeared in all the subplots, and automatically omit the extra one that’s only shown in the first subplot, how to include that grounp into the overall legend as well? Thanks! I’m trying to make a plot, using the tiledlayout function to create 4 subplots, while in the first subplot, there are 5 data groups, while the remaining subplots only have four of those 5 groups. If I create an overall legend, it will only show 4 groups that appeared in all the subplots, and automatically omit the extra one that’s only shown in the first subplot, how to include that grounp into the overall legend as well? Thanks! plotting, legend, tiledlayout, subplots MATLAB Answers — New Questions
How to get cluster data after clustering in EEGLAB ?
Hello everyone
Hello everyone,I’m encountering some difficulties while analyzing EEG data using EEGLab. After clustering ICs using the K-means algorithm, I’m unsure about how to select meaningful clusters for further analysis.Specifically, I’d like to plot ERSPs for a chosen cluster (e.g., cluster 2) and then apply bootstrapping to the entire epoch. Subsequently, I want to set all non-significant ERSP values (p > 0.05) compared to this distribution to zero dB.Hello everyone
Hello everyone,I’m encountering some difficulties while analyzing EEG data using EEGLab. After clustering ICs using the K-means algorithm, I’m unsure about how to select meaningful clusters for further analysis.Specifically, I’d like to plot ERSPs for a chosen cluster (e.g., cluster 2) and then apply bootstrapping to the entire epoch. Subsequently, I want to set all non-significant ERSP values (p > 0.05) compared to this distribution to zero dB. Hello everyone
Hello everyone,I’m encountering some difficulties while analyzing EEG data using EEGLab. After clustering ICs using the K-means algorithm, I’m unsure about how to select meaningful clusters for further analysis.Specifically, I’d like to plot ERSPs for a chosen cluster (e.g., cluster 2) and then apply bootstrapping to the entire epoch. Subsequently, I want to set all non-significant ERSP values (p > 0.05) compared to this distribution to zero dB. matlab, eeglab, eeg, ersp, clustering MATLAB Answers — New Questions
Only algebraic system equations in Model Predictive Control Toolbox?
My goal ist to use Model Predictive Control (MPC) for high-level planning. Instead of having differential equations I want to use only algebraic equations in the state function.
The equations would be in the form . Is there a way to define the MPC state functions as such?
Preferably I would use the nonlinear version of MPC.
Thank you very much.
Best regards,
MartinMy goal ist to use Model Predictive Control (MPC) for high-level planning. Instead of having differential equations I want to use only algebraic equations in the state function.
The equations would be in the form . Is there a way to define the MPC state functions as such?
Preferably I would use the nonlinear version of MPC.
Thank you very much.
Best regards,
Martin My goal ist to use Model Predictive Control (MPC) for high-level planning. Instead of having differential equations I want to use only algebraic equations in the state function.
The equations would be in the form . Is there a way to define the MPC state functions as such?
Preferably I would use the nonlinear version of MPC.
Thank you very much.
Best regards,
Martin mpc, algebraic equation MATLAB Answers — New Questions
Controller update in a discrete system
Hello everyone, I have a question
I have a continuous system that updates every 0.001 seconds.
In addition to this, I have a controller that should be updated with a delay of at least 100 times the system (ie every 100 iterations it is updated)
My question is this:
Do I need to calculate the signal and its derivatives and in addition the error and its derivative with T or with dt? I’m not sure..
The system is denoted as y_pk
The required signal is denoted as y_dk
This is part of my code:
dt=0.001; %discrete time
T=0.1; %continoues time
y_d = sin(1 * time); % desired signal
dy_d = diff(y_d) / dt;
ddy_d = diff(dy_d) / dt;
%initialize:
y_dk1=0; dy_dk1=0; uk2=0; uk1=0;
firstrun=true;
for j = 1:length(time)
y_dk = y_d(j);
if mod(j, 100) == 0 ||firstrun
T=dt; % ??
dy_dk = (y_dk-y_dk1)/T; %derv of y_dk
ddy_dk = (dy_dk – dy_dk1)/T; %second derv of y_dk
ek = y_dk – y_pk;
de_k = dy_dk – dy_pk;
uk = (1/c)*(a1*dy_pk + b1*(dy_pk)^2 + a2*y_pk + b2*(y_pk)^2 +k_p*ek + k_d*de_k + ddy_dk); % u: control input
% Store data for nex step:
uk2=uk1;
uk1=uk;
firstrun=false;
end
y_pk = …. ; %update each 0.001 second (continoues time)
dy_pk = (y_pk-y_pk1)/dt; %derv of y_pk
% Store data for nex step: system
y_pk2=y_pk1;
y_pk1=y_pk;
Thank you all!! :)Hello everyone, I have a question
I have a continuous system that updates every 0.001 seconds.
In addition to this, I have a controller that should be updated with a delay of at least 100 times the system (ie every 100 iterations it is updated)
My question is this:
Do I need to calculate the signal and its derivatives and in addition the error and its derivative with T or with dt? I’m not sure..
The system is denoted as y_pk
The required signal is denoted as y_dk
This is part of my code:
dt=0.001; %discrete time
T=0.1; %continoues time
y_d = sin(1 * time); % desired signal
dy_d = diff(y_d) / dt;
ddy_d = diff(dy_d) / dt;
%initialize:
y_dk1=0; dy_dk1=0; uk2=0; uk1=0;
firstrun=true;
for j = 1:length(time)
y_dk = y_d(j);
if mod(j, 100) == 0 ||firstrun
T=dt; % ??
dy_dk = (y_dk-y_dk1)/T; %derv of y_dk
ddy_dk = (dy_dk – dy_dk1)/T; %second derv of y_dk
ek = y_dk – y_pk;
de_k = dy_dk – dy_pk;
uk = (1/c)*(a1*dy_pk + b1*(dy_pk)^2 + a2*y_pk + b2*(y_pk)^2 +k_p*ek + k_d*de_k + ddy_dk); % u: control input
% Store data for nex step:
uk2=uk1;
uk1=uk;
firstrun=false;
end
y_pk = …. ; %update each 0.001 second (continoues time)
dy_pk = (y_pk-y_pk1)/dt; %derv of y_pk
% Store data for nex step: system
y_pk2=y_pk1;
y_pk1=y_pk;
Thank you all!! 🙂 Hello everyone, I have a question
I have a continuous system that updates every 0.001 seconds.
In addition to this, I have a controller that should be updated with a delay of at least 100 times the system (ie every 100 iterations it is updated)
My question is this:
Do I need to calculate the signal and its derivatives and in addition the error and its derivative with T or with dt? I’m not sure..
The system is denoted as y_pk
The required signal is denoted as y_dk
This is part of my code:
dt=0.001; %discrete time
T=0.1; %continoues time
y_d = sin(1 * time); % desired signal
dy_d = diff(y_d) / dt;
ddy_d = diff(dy_d) / dt;
%initialize:
y_dk1=0; dy_dk1=0; uk2=0; uk1=0;
firstrun=true;
for j = 1:length(time)
y_dk = y_d(j);
if mod(j, 100) == 0 ||firstrun
T=dt; % ??
dy_dk = (y_dk-y_dk1)/T; %derv of y_dk
ddy_dk = (dy_dk – dy_dk1)/T; %second derv of y_dk
ek = y_dk – y_pk;
de_k = dy_dk – dy_pk;
uk = (1/c)*(a1*dy_pk + b1*(dy_pk)^2 + a2*y_pk + b2*(y_pk)^2 +k_p*ek + k_d*de_k + ddy_dk); % u: control input
% Store data for nex step:
uk2=uk1;
uk1=uk;
firstrun=false;
end
y_pk = …. ; %update each 0.001 second (continoues time)
dy_pk = (y_pk-y_pk1)/dt; %derv of y_pk
% Store data for nex step: system
y_pk2=y_pk1;
y_pk1=y_pk;
Thank you all!! 🙂 control, discrete system, controller MATLAB Answers — New Questions
VerifyEqual within a time interval
Hello, I have been assigned a series of tests to be completed on several floating point variables. The assignment requires me to check whether the Expected value is the same as the Actual value. However, it may take a few milliseconds for the Actual value to reach the same status as the Expected value, and the verifyEqual function does not seem to consider this scenario.
I’d like to know if there is some sort of workaround for this situation. Basically, if A is the Actual value and E the Expected value, I’d like to modify (somehow) the verifyEqual function so that it returns a passing test if A == E with a time delay of approx. 3 milliseconds.
Thank you for your cooperation.Hello, I have been assigned a series of tests to be completed on several floating point variables. The assignment requires me to check whether the Expected value is the same as the Actual value. However, it may take a few milliseconds for the Actual value to reach the same status as the Expected value, and the verifyEqual function does not seem to consider this scenario.
I’d like to know if there is some sort of workaround for this situation. Basically, if A is the Actual value and E the Expected value, I’d like to modify (somehow) the verifyEqual function so that it returns a passing test if A == E with a time delay of approx. 3 milliseconds.
Thank you for your cooperation. Hello, I have been assigned a series of tests to be completed on several floating point variables. The assignment requires me to check whether the Expected value is the same as the Actual value. However, it may take a few milliseconds for the Actual value to reach the same status as the Expected value, and the verifyEqual function does not seem to consider this scenario.
I’d like to know if there is some sort of workaround for this situation. Basically, if A is the Actual value and E the Expected value, I’d like to modify (somehow) the verifyEqual function so that it returns a passing test if A == E with a time delay of approx. 3 milliseconds.
Thank you for your cooperation. matlab function, testcase, guide, solve, time MATLAB Answers — New Questions
Adjust the fitting for non-unique values data (alternative to the fuction smoothing spline, createFit.f)
Good morning everyone,
I am trying to extract the fracture aperture from a tomography image. I have written the code for the extraction, and everything works using the fitting smoothing spline (createFit function attached) for clu_sli_12.mat and I_12.mat, but not on clu_sli_1400.mat and I_1400.mat in which we have non-unique data (presented directly in the code below). The variable clu_sli_1400 represents the point cloud used as reference for selecting data in the tomography slice (variable I_1400). We tried using other functions in matlab, without success. Can anybody help suggesting a specific function for fitting this data?
thanks in advance for any help!!!!!!!!
clear;
close all;
clc;
warning off;
load(‘I_1400.mat’)
load(‘clu_sli_1400.mat’)
voxel_size=70.69*10^-3;
%% Iteration on the slices
mean_widths = [];
std_widths = [];
min_widths = [];
max_widths = [];
areas = [];
% for ii = 12 %we have to iterate to ii = 12 and ii = 1400 (the last one not working properly on the fitting)
% fitting data
X = clu_sli(:,1);
Y = clu_sli(:,2);
% Create model fitting
[fitresult, gof] = createFit(X, Y);
% Calcolare i valori della curva di fitting
vv = ppval(fitresult.p, X);
% Calcolare la prima derivata della curva di fitting
d1 = ppval(fnder(fitresult.p, 1), X);
% Calcolare la normale alla curva di fitting
epsilon = 1e-10; % Evita la divisione per zero
nn = 1 ./ (d1 + epsilon);
% Calcolare gli angoli delle normali
theta = atan(-1 ./ d1); % Angolo della normale (in radianti)
% Calcolare le componenti della normale
normal_x = cos(theta); % Componente x della normale
normal_y = sin(theta); % Componente y della normale
% Calcolare l’ampiezza della crepa e visualizzare i segmenti
span = 50;
largh = zeros(size(clu_sli, 1), 1);
% Creare una figura con due subplot
figure;
% Primo subplot: Visualizzare la slice con i pallini rossi
subplot(1, 2, 1);
pcolor(I);
shading interp;
axis equal;
hold on;
scatter(clu_sli(:,1), clu_sli(:,2), ‘r’);
xlabel(‘X’);
ylabel(‘Y’);
% Secondo subplot: Visualizzare la slice con i segmenti verdi
subplot(1, 2, 2);
pcolor(I);
shading interp;
axis equal;
hold on;
scatter(clu_sli(:,1), clu_sli(:,2), ‘r’);
plot(X, vv, ‘b’, ‘LineWidth’, 2);
quiver(X, vv, normal_x, normal_y, 0.5, ‘k’, ‘LineWidth’, 1);
intensity_profiles = cell(size(clu_sli, 1), 1);
vet_in = zeros(size(clu_sli, 1), 2);
vet_fin = zeros(size(clu_sli, 1), 2);
for kk = 1:size(clu_sli, 1)
c = round(X(kk));
r = round(vv(kk));
% Genera i pixel lungo la normale
x_profile = round(c + (-span:span) * normal_x(kk));
y_profile = round(r + (-span:span) * normal_y(kk));
% Assicurarsi che i pixel siano all’interno dell’immagine
valid_idx = x_profile > 0 & x_profile <= size(I, 2) & y_profile > 0 & y_profile <= size(I, 1);
x_profile = x_profile(valid_idx);
y_profile = y_profile(valid_idx);
% Estrarre i valori del profilo dall’immagine
profilo = I(sub2ind(size(I), y_profile, x_profile));
intensity_profiles{kk} = profilo;
% Calcolare l’ampiezza della crepa
largh(kk) = conv_crepa(profilo);
% Calcolare i punti del segmento di larghezza
half_width = largh(kk) / 2;
segment_x = [c – half_width * normal_x(kk), c + half_width * normal_x(kk)];
segment_y = [r – half_width * normal_y(kk), r + half_width * normal_y(kk)];
vet_in(kk,1) = c – half_width * normal_x(kk);
vet_fin(kk,1) = c + half_width * normal_x(kk);
vet_in(kk,2) = r – half_width * normal_y(kk);
vet_fin(kk,2) = r + half_width * normal_y(kk);
% Visualizzare il segmento di larghezza
plot(segment_x, segment_y, ‘g’, ‘LineWidth’, 2);
end
hold off;
% Calcolare la media, la deviazione standard, il minimo e il massimo della larghezza della crepa
mean_width = mean(largh, ‘omitnan’);
std_width = std(largh, ‘omitnan’);
min_width = min(largh, [], ‘omitnan’);
max_width = max(largh, [], ‘omitnan’);
mean_widths = [mean_widths; mean_width];
std_widths = [std_widths; std_width];
min_widths = [min_widths; min_width];
max_widths = [max_widths; max_width];
% Calcolo dell’area all’interno delle curve usando trapz
% Creazione del poligono per calcolare l’area
all_x = [vet_in(:,1); flip(vet_fin(:,1))];
all_y = [vet_in(:,2); flip(vet_fin(:,2))];
% Rimuovi i NaN
valid_idx = ~isnan(all_x) & ~isnan(all_y);
all_x = all_x(valid_idx);
all_y = all_y(valid_idx);
% Assicurarsi che i punti formino un poligono chiuso
if length(all_x) > 1 && (all_x(1) ~= all_x(end) || all_y(1) ~= all_y(end))
all_x(end+1) = all_x(1);
all_y(end+1) = all_y(1);
end
% Calcolo dell’area del poligono usando trapz
area = trapz(all_x, all_y);
areas = [areas; area];
title(‘Area Between Curves per Slice’);
%% calcoli in mm
areas_mm = areas.* voxel_size^2
std_mm=std_widths.*voxel_size
mean_mm=mean_widths.*voxel_size
min_mm=min_widths.*voxel_size
max_mm=max_widths.*voxel_sizeGood morning everyone,
I am trying to extract the fracture aperture from a tomography image. I have written the code for the extraction, and everything works using the fitting smoothing spline (createFit function attached) for clu_sli_12.mat and I_12.mat, but not on clu_sli_1400.mat and I_1400.mat in which we have non-unique data (presented directly in the code below). The variable clu_sli_1400 represents the point cloud used as reference for selecting data in the tomography slice (variable I_1400). We tried using other functions in matlab, without success. Can anybody help suggesting a specific function for fitting this data?
thanks in advance for any help!!!!!!!!
clear;
close all;
clc;
warning off;
load(‘I_1400.mat’)
load(‘clu_sli_1400.mat’)
voxel_size=70.69*10^-3;
%% Iteration on the slices
mean_widths = [];
std_widths = [];
min_widths = [];
max_widths = [];
areas = [];
% for ii = 12 %we have to iterate to ii = 12 and ii = 1400 (the last one not working properly on the fitting)
% fitting data
X = clu_sli(:,1);
Y = clu_sli(:,2);
% Create model fitting
[fitresult, gof] = createFit(X, Y);
% Calcolare i valori della curva di fitting
vv = ppval(fitresult.p, X);
% Calcolare la prima derivata della curva di fitting
d1 = ppval(fnder(fitresult.p, 1), X);
% Calcolare la normale alla curva di fitting
epsilon = 1e-10; % Evita la divisione per zero
nn = 1 ./ (d1 + epsilon);
% Calcolare gli angoli delle normali
theta = atan(-1 ./ d1); % Angolo della normale (in radianti)
% Calcolare le componenti della normale
normal_x = cos(theta); % Componente x della normale
normal_y = sin(theta); % Componente y della normale
% Calcolare l’ampiezza della crepa e visualizzare i segmenti
span = 50;
largh = zeros(size(clu_sli, 1), 1);
% Creare una figura con due subplot
figure;
% Primo subplot: Visualizzare la slice con i pallini rossi
subplot(1, 2, 1);
pcolor(I);
shading interp;
axis equal;
hold on;
scatter(clu_sli(:,1), clu_sli(:,2), ‘r’);
xlabel(‘X’);
ylabel(‘Y’);
% Secondo subplot: Visualizzare la slice con i segmenti verdi
subplot(1, 2, 2);
pcolor(I);
shading interp;
axis equal;
hold on;
scatter(clu_sli(:,1), clu_sli(:,2), ‘r’);
plot(X, vv, ‘b’, ‘LineWidth’, 2);
quiver(X, vv, normal_x, normal_y, 0.5, ‘k’, ‘LineWidth’, 1);
intensity_profiles = cell(size(clu_sli, 1), 1);
vet_in = zeros(size(clu_sli, 1), 2);
vet_fin = zeros(size(clu_sli, 1), 2);
for kk = 1:size(clu_sli, 1)
c = round(X(kk));
r = round(vv(kk));
% Genera i pixel lungo la normale
x_profile = round(c + (-span:span) * normal_x(kk));
y_profile = round(r + (-span:span) * normal_y(kk));
% Assicurarsi che i pixel siano all’interno dell’immagine
valid_idx = x_profile > 0 & x_profile <= size(I, 2) & y_profile > 0 & y_profile <= size(I, 1);
x_profile = x_profile(valid_idx);
y_profile = y_profile(valid_idx);
% Estrarre i valori del profilo dall’immagine
profilo = I(sub2ind(size(I), y_profile, x_profile));
intensity_profiles{kk} = profilo;
% Calcolare l’ampiezza della crepa
largh(kk) = conv_crepa(profilo);
% Calcolare i punti del segmento di larghezza
half_width = largh(kk) / 2;
segment_x = [c – half_width * normal_x(kk), c + half_width * normal_x(kk)];
segment_y = [r – half_width * normal_y(kk), r + half_width * normal_y(kk)];
vet_in(kk,1) = c – half_width * normal_x(kk);
vet_fin(kk,1) = c + half_width * normal_x(kk);
vet_in(kk,2) = r – half_width * normal_y(kk);
vet_fin(kk,2) = r + half_width * normal_y(kk);
% Visualizzare il segmento di larghezza
plot(segment_x, segment_y, ‘g’, ‘LineWidth’, 2);
end
hold off;
% Calcolare la media, la deviazione standard, il minimo e il massimo della larghezza della crepa
mean_width = mean(largh, ‘omitnan’);
std_width = std(largh, ‘omitnan’);
min_width = min(largh, [], ‘omitnan’);
max_width = max(largh, [], ‘omitnan’);
mean_widths = [mean_widths; mean_width];
std_widths = [std_widths; std_width];
min_widths = [min_widths; min_width];
max_widths = [max_widths; max_width];
% Calcolo dell’area all’interno delle curve usando trapz
% Creazione del poligono per calcolare l’area
all_x = [vet_in(:,1); flip(vet_fin(:,1))];
all_y = [vet_in(:,2); flip(vet_fin(:,2))];
% Rimuovi i NaN
valid_idx = ~isnan(all_x) & ~isnan(all_y);
all_x = all_x(valid_idx);
all_y = all_y(valid_idx);
% Assicurarsi che i punti formino un poligono chiuso
if length(all_x) > 1 && (all_x(1) ~= all_x(end) || all_y(1) ~= all_y(end))
all_x(end+1) = all_x(1);
all_y(end+1) = all_y(1);
end
% Calcolo dell’area del poligono usando trapz
area = trapz(all_x, all_y);
areas = [areas; area];
title(‘Area Between Curves per Slice’);
%% calcoli in mm
areas_mm = areas.* voxel_size^2
std_mm=std_widths.*voxel_size
mean_mm=mean_widths.*voxel_size
min_mm=min_widths.*voxel_size
max_mm=max_widths.*voxel_size Good morning everyone,
I am trying to extract the fracture aperture from a tomography image. I have written the code for the extraction, and everything works using the fitting smoothing spline (createFit function attached) for clu_sli_12.mat and I_12.mat, but not on clu_sli_1400.mat and I_1400.mat in which we have non-unique data (presented directly in the code below). The variable clu_sli_1400 represents the point cloud used as reference for selecting data in the tomography slice (variable I_1400). We tried using other functions in matlab, without success. Can anybody help suggesting a specific function for fitting this data?
thanks in advance for any help!!!!!!!!
clear;
close all;
clc;
warning off;
load(‘I_1400.mat’)
load(‘clu_sli_1400.mat’)
voxel_size=70.69*10^-3;
%% Iteration on the slices
mean_widths = [];
std_widths = [];
min_widths = [];
max_widths = [];
areas = [];
% for ii = 12 %we have to iterate to ii = 12 and ii = 1400 (the last one not working properly on the fitting)
% fitting data
X = clu_sli(:,1);
Y = clu_sli(:,2);
% Create model fitting
[fitresult, gof] = createFit(X, Y);
% Calcolare i valori della curva di fitting
vv = ppval(fitresult.p, X);
% Calcolare la prima derivata della curva di fitting
d1 = ppval(fnder(fitresult.p, 1), X);
% Calcolare la normale alla curva di fitting
epsilon = 1e-10; % Evita la divisione per zero
nn = 1 ./ (d1 + epsilon);
% Calcolare gli angoli delle normali
theta = atan(-1 ./ d1); % Angolo della normale (in radianti)
% Calcolare le componenti della normale
normal_x = cos(theta); % Componente x della normale
normal_y = sin(theta); % Componente y della normale
% Calcolare l’ampiezza della crepa e visualizzare i segmenti
span = 50;
largh = zeros(size(clu_sli, 1), 1);
% Creare una figura con due subplot
figure;
% Primo subplot: Visualizzare la slice con i pallini rossi
subplot(1, 2, 1);
pcolor(I);
shading interp;
axis equal;
hold on;
scatter(clu_sli(:,1), clu_sli(:,2), ‘r’);
xlabel(‘X’);
ylabel(‘Y’);
% Secondo subplot: Visualizzare la slice con i segmenti verdi
subplot(1, 2, 2);
pcolor(I);
shading interp;
axis equal;
hold on;
scatter(clu_sli(:,1), clu_sli(:,2), ‘r’);
plot(X, vv, ‘b’, ‘LineWidth’, 2);
quiver(X, vv, normal_x, normal_y, 0.5, ‘k’, ‘LineWidth’, 1);
intensity_profiles = cell(size(clu_sli, 1), 1);
vet_in = zeros(size(clu_sli, 1), 2);
vet_fin = zeros(size(clu_sli, 1), 2);
for kk = 1:size(clu_sli, 1)
c = round(X(kk));
r = round(vv(kk));
% Genera i pixel lungo la normale
x_profile = round(c + (-span:span) * normal_x(kk));
y_profile = round(r + (-span:span) * normal_y(kk));
% Assicurarsi che i pixel siano all’interno dell’immagine
valid_idx = x_profile > 0 & x_profile <= size(I, 2) & y_profile > 0 & y_profile <= size(I, 1);
x_profile = x_profile(valid_idx);
y_profile = y_profile(valid_idx);
% Estrarre i valori del profilo dall’immagine
profilo = I(sub2ind(size(I), y_profile, x_profile));
intensity_profiles{kk} = profilo;
% Calcolare l’ampiezza della crepa
largh(kk) = conv_crepa(profilo);
% Calcolare i punti del segmento di larghezza
half_width = largh(kk) / 2;
segment_x = [c – half_width * normal_x(kk), c + half_width * normal_x(kk)];
segment_y = [r – half_width * normal_y(kk), r + half_width * normal_y(kk)];
vet_in(kk,1) = c – half_width * normal_x(kk);
vet_fin(kk,1) = c + half_width * normal_x(kk);
vet_in(kk,2) = r – half_width * normal_y(kk);
vet_fin(kk,2) = r + half_width * normal_y(kk);
% Visualizzare il segmento di larghezza
plot(segment_x, segment_y, ‘g’, ‘LineWidth’, 2);
end
hold off;
% Calcolare la media, la deviazione standard, il minimo e il massimo della larghezza della crepa
mean_width = mean(largh, ‘omitnan’);
std_width = std(largh, ‘omitnan’);
min_width = min(largh, [], ‘omitnan’);
max_width = max(largh, [], ‘omitnan’);
mean_widths = [mean_widths; mean_width];
std_widths = [std_widths; std_width];
min_widths = [min_widths; min_width];
max_widths = [max_widths; max_width];
% Calcolo dell’area all’interno delle curve usando trapz
% Creazione del poligono per calcolare l’area
all_x = [vet_in(:,1); flip(vet_fin(:,1))];
all_y = [vet_in(:,2); flip(vet_fin(:,2))];
% Rimuovi i NaN
valid_idx = ~isnan(all_x) & ~isnan(all_y);
all_x = all_x(valid_idx);
all_y = all_y(valid_idx);
% Assicurarsi che i punti formino un poligono chiuso
if length(all_x) > 1 && (all_x(1) ~= all_x(end) || all_y(1) ~= all_y(end))
all_x(end+1) = all_x(1);
all_y(end+1) = all_y(1);
end
% Calcolo dell’area del poligono usando trapz
area = trapz(all_x, all_y);
areas = [areas; area];
title(‘Area Between Curves per Slice’);
%% calcoli in mm
areas_mm = areas.* voxel_size^2
std_mm=std_widths.*voxel_size
mean_mm=mean_widths.*voxel_size
min_mm=min_widths.*voxel_size
max_mm=max_widths.*voxel_size curve fitting, non-unique data, createfit MATLAB Answers — New Questions
A simple allocation of array places to zero does not work in MATLAB R2020B
I have a numeric array KSE
I have identified a number of locations where there are peaks,
locations =
Columns 1 through 10
147 827 3772 4762 5192 5618 6048 6481 6915 7350
Columns 11 through 20
7781 8206 8637 9070 9502 9938 10367 10793 11225 11657
Columns 21 through 26
12922 13876 20315 23377 24431 25492
I have identified in that array a number of locations where there are short lived transients, a number of which I wish to remove.
Those unwanted transients are identified by
ii =
1 2 3 21 22 23 24 25 26
The command
KSE(locations(ii)-50:locations(ii)+50)=0
is meant to replace 50 array elements on either side of the transient location with a zero.
It works well at the first location but not in the remaining 8 locations!
Is this a bug or am I doing some sort of stupid coding mistake?
Any soultions would be appreciated!I have a numeric array KSE
I have identified a number of locations where there are peaks,
locations =
Columns 1 through 10
147 827 3772 4762 5192 5618 6048 6481 6915 7350
Columns 11 through 20
7781 8206 8637 9070 9502 9938 10367 10793 11225 11657
Columns 21 through 26
12922 13876 20315 23377 24431 25492
I have identified in that array a number of locations where there are short lived transients, a number of which I wish to remove.
Those unwanted transients are identified by
ii =
1 2 3 21 22 23 24 25 26
The command
KSE(locations(ii)-50:locations(ii)+50)=0
is meant to replace 50 array elements on either side of the transient location with a zero.
It works well at the first location but not in the remaining 8 locations!
Is this a bug or am I doing some sort of stupid coding mistake?
Any soultions would be appreciated! I have a numeric array KSE
I have identified a number of locations where there are peaks,
locations =
Columns 1 through 10
147 827 3772 4762 5192 5618 6048 6481 6915 7350
Columns 11 through 20
7781 8206 8637 9070 9502 9938 10367 10793 11225 11657
Columns 21 through 26
12922 13876 20315 23377 24431 25492
I have identified in that array a number of locations where there are short lived transients, a number of which I wish to remove.
Those unwanted transients are identified by
ii =
1 2 3 21 22 23 24 25 26
The command
KSE(locations(ii)-50:locations(ii)+50)=0
is meant to replace 50 array elements on either side of the transient location with a zero.
It works well at the first location but not in the remaining 8 locations!
Is this a bug or am I doing some sort of stupid coding mistake?
Any soultions would be appreciated! setting array elements to zero MATLAB Answers — New Questions