Category: Matlab
Category Archives: Matlab
How to find MATLAB function blocks??
Dear Community, can i get the answer to this question?
S = sfroot();
% Get block
handlesB = find(sfroot, ‘-isa’,’Stateflow.EMChart’);
This is the instruction I have used to find out the MATLAB Function blocks. But, this instruction also considers the MATLAB Function block present the the Simulink library. I would like to know whether there is any other command to find out MATLAB Function blocks which are just present in my created Model.Dear Community, can i get the answer to this question?
S = sfroot();
% Get block
handlesB = find(sfroot, ‘-isa’,’Stateflow.EMChart’);
This is the instruction I have used to find out the MATLAB Function blocks. But, this instruction also considers the MATLAB Function block present the the Simulink library. I would like to know whether there is any other command to find out MATLAB Function blocks which are just present in my created Model. Dear Community, can i get the answer to this question?
S = sfroot();
% Get block
handlesB = find(sfroot, ‘-isa’,’Stateflow.EMChart’);
This is the instruction I have used to find out the MATLAB Function blocks. But, this instruction also considers the MATLAB Function block present the the Simulink library. I would like to know whether there is any other command to find out MATLAB Function blocks which are just present in my created Model. matlab, matlab function block MATLAB Answers — New Questions
Servo Motor Control Issues
I’ve connected a servo motor to my arduino boad, (Elegoo 2560), and have been trying to cuse simulink to run the motor. Ideally I would like it to spin when an input is recieved, but I can’t make it spin at all for some reason. Attached are the simple set ups I’ve been trying to run, but I keep getting the error ‘error building’ with no details. Is there a visible reason for this error, or something I should change?I’ve connected a servo motor to my arduino boad, (Elegoo 2560), and have been trying to cuse simulink to run the motor. Ideally I would like it to spin when an input is recieved, but I can’t make it spin at all for some reason. Attached are the simple set ups I’ve been trying to run, but I keep getting the error ‘error building’ with no details. Is there a visible reason for this error, or something I should change? I’ve connected a servo motor to my arduino boad, (Elegoo 2560), and have been trying to cuse simulink to run the motor. Ideally I would like it to spin when an input is recieved, but I can’t make it spin at all for some reason. Attached are the simple set ups I’ve been trying to run, but I keep getting the error ‘error building’ with no details. Is there a visible reason for this error, or something I should change? arduino, servo motor, simulink, error MATLAB Answers — New Questions
ADS1115 With Simulink / Raspberry Pi (ADS1x15 Block) – Multi-Channel Read Issue?
Hi there,
I have a simulink model that is being deployed on a raspberry pi 4 model B. I am trying to use the ADS1x15 block from the "Simulink Support for Raspberry Pi Hardware" package. My issue is that I am not able to read from more than one channel at once. If I create two instances of the block, and select the appropriate channels, they output the same thing. Is this a known issue, or have I not configured the block or model properly? Or is there some workaround for this?
I saw a previous question posted on the Matlab Answers forum and the only answers seem to keep pointing at this one 8 year old video on youtube that creates an S-Function instead of using the dedicated library blocks (the video is also for Arduino, not raspberry pi).
Here is a screen capture of the model:
Here is block "ChannelA" properties (Note in the advanced tab, enable comparator is not checked):
Here is block "ChannelB" properties (Same as Channel A, but selected a different channel):
If the conversation mode is "Single Shot" then both blocks just output channel A.
If the conversation mode is continuous, then both blocks output whatever channel has most recently changed voltage. Very strange. It seems like the i2c information is being sent to both blocks although different channels are selected.
I have all of the hardware breadboarded and the voltages / connections are all correct. Ruled that out.
Some help with this blockset would be appreciated. I cannot seem to get this working. For testing this I am using the Simulink run on hardware feature with my raspberry pi and I am on version R2024a of maltab/simulink.
Thanks – Kyle.Hi there,
I have a simulink model that is being deployed on a raspberry pi 4 model B. I am trying to use the ADS1x15 block from the "Simulink Support for Raspberry Pi Hardware" package. My issue is that I am not able to read from more than one channel at once. If I create two instances of the block, and select the appropriate channels, they output the same thing. Is this a known issue, or have I not configured the block or model properly? Or is there some workaround for this?
I saw a previous question posted on the Matlab Answers forum and the only answers seem to keep pointing at this one 8 year old video on youtube that creates an S-Function instead of using the dedicated library blocks (the video is also for Arduino, not raspberry pi).
Here is a screen capture of the model:
Here is block "ChannelA" properties (Note in the advanced tab, enable comparator is not checked):
Here is block "ChannelB" properties (Same as Channel A, but selected a different channel):
If the conversation mode is "Single Shot" then both blocks just output channel A.
If the conversation mode is continuous, then both blocks output whatever channel has most recently changed voltage. Very strange. It seems like the i2c information is being sent to both blocks although different channels are selected.
I have all of the hardware breadboarded and the voltages / connections are all correct. Ruled that out.
Some help with this blockset would be appreciated. I cannot seem to get this working. For testing this I am using the Simulink run on hardware feature with my raspberry pi and I am on version R2024a of maltab/simulink.
Thanks – Kyle. Hi there,
I have a simulink model that is being deployed on a raspberry pi 4 model B. I am trying to use the ADS1x15 block from the "Simulink Support for Raspberry Pi Hardware" package. My issue is that I am not able to read from more than one channel at once. If I create two instances of the block, and select the appropriate channels, they output the same thing. Is this a known issue, or have I not configured the block or model properly? Or is there some workaround for this?
I saw a previous question posted on the Matlab Answers forum and the only answers seem to keep pointing at this one 8 year old video on youtube that creates an S-Function instead of using the dedicated library blocks (the video is also for Arduino, not raspberry pi).
Here is a screen capture of the model:
Here is block "ChannelA" properties (Note in the advanced tab, enable comparator is not checked):
Here is block "ChannelB" properties (Same as Channel A, but selected a different channel):
If the conversation mode is "Single Shot" then both blocks just output channel A.
If the conversation mode is continuous, then both blocks output whatever channel has most recently changed voltage. Very strange. It seems like the i2c information is being sent to both blocks although different channels are selected.
I have all of the hardware breadboarded and the voltages / connections are all correct. Ruled that out.
Some help with this blockset would be appreciated. I cannot seem to get this working. For testing this I am using the Simulink run on hardware feature with my raspberry pi and I am on version R2024a of maltab/simulink.
Thanks – Kyle. simulink, raspberry pi, ads1115, i2c MATLAB Answers — New Questions
function with multiple listeners freezing on R2024a. was working fine on R2022b
Hi,
I have created a function (with multiple embedded functions in the same .m file) that create a GUI to load a picture and add a "user defined" amount of line on it that the user can modify.
I don’t think i can share the full code but on the principle:
once the user has selected the figure, it gets put in an ax
the added curves are then saved as "children of the ax"
there are sliders button with listeners that are linked to those lines, through the list of children of the ax.
when the user select a curve in a drop-down list and move the associate slider, the selected line move on the graph.
the listeners are added in a loop as the code doesn’t know a priori how many lines the user would add.
I was quite proud of this code that was working exactly as intended on R2022b, when I coded it. I skipped entirely R2023 but I now installed R2024a and the code freezes when creating the first series of listeners. it does not issue any error mistake but I just hear my PC working very hard suddenly, with matlab using suddenly up to 20% of the CPU. I saw this thread
https://www.mathworks.com/matlabcentral/answers/287708-some-matlab-versions-crash-when-using-listener
regarding potentially the same issue but it was for R2015.
I tried as well to install R2023b and the code freezes as well. for comparison I use the exact same code with the same figure and the same amount of added line (20) on all three versions. this is what I get
R2022b: lines and listeners added in 6 sec. CPU usage max up to 25%
R2023b: lines and listeners added in >120 sec (I killed the process). CPU usage max up to 16 % at the start, but steady at 12% until I kill the process.
R2024a: lines and listeners added in >120 sec (I killed the process). CPU usage max up to 25 % at the start, but steady at 15% until I kill the process.
I tried as well with lower amount of line (5) and all three version worked. it was very fast for R2022b (<1sec) and took about 5 sec. for R2023b and R2024a.
My code is certainly not optimal. I was learning how to make a GUI while doing it and after the fact I saw how I could have make it better, but since it was working I did not bother…and of course now I don’t really "remember" all that I did back in 2022.
without seeing the code, would you be able to tell me what changed between R2022b and R2023b/R2024a that would make my code that much slowlier? would you have a quick fix?Hi,
I have created a function (with multiple embedded functions in the same .m file) that create a GUI to load a picture and add a "user defined" amount of line on it that the user can modify.
I don’t think i can share the full code but on the principle:
once the user has selected the figure, it gets put in an ax
the added curves are then saved as "children of the ax"
there are sliders button with listeners that are linked to those lines, through the list of children of the ax.
when the user select a curve in a drop-down list and move the associate slider, the selected line move on the graph.
the listeners are added in a loop as the code doesn’t know a priori how many lines the user would add.
I was quite proud of this code that was working exactly as intended on R2022b, when I coded it. I skipped entirely R2023 but I now installed R2024a and the code freezes when creating the first series of listeners. it does not issue any error mistake but I just hear my PC working very hard suddenly, with matlab using suddenly up to 20% of the CPU. I saw this thread
https://www.mathworks.com/matlabcentral/answers/287708-some-matlab-versions-crash-when-using-listener
regarding potentially the same issue but it was for R2015.
I tried as well to install R2023b and the code freezes as well. for comparison I use the exact same code with the same figure and the same amount of added line (20) on all three versions. this is what I get
R2022b: lines and listeners added in 6 sec. CPU usage max up to 25%
R2023b: lines and listeners added in >120 sec (I killed the process). CPU usage max up to 16 % at the start, but steady at 12% until I kill the process.
R2024a: lines and listeners added in >120 sec (I killed the process). CPU usage max up to 25 % at the start, but steady at 15% until I kill the process.
I tried as well with lower amount of line (5) and all three version worked. it was very fast for R2022b (<1sec) and took about 5 sec. for R2023b and R2024a.
My code is certainly not optimal. I was learning how to make a GUI while doing it and after the fact I saw how I could have make it better, but since it was working I did not bother…and of course now I don’t really "remember" all that I did back in 2022.
without seeing the code, would you be able to tell me what changed between R2022b and R2023b/R2024a that would make my code that much slowlier? would you have a quick fix? Hi,
I have created a function (with multiple embedded functions in the same .m file) that create a GUI to load a picture and add a "user defined" amount of line on it that the user can modify.
I don’t think i can share the full code but on the principle:
once the user has selected the figure, it gets put in an ax
the added curves are then saved as "children of the ax"
there are sliders button with listeners that are linked to those lines, through the list of children of the ax.
when the user select a curve in a drop-down list and move the associate slider, the selected line move on the graph.
the listeners are added in a loop as the code doesn’t know a priori how many lines the user would add.
I was quite proud of this code that was working exactly as intended on R2022b, when I coded it. I skipped entirely R2023 but I now installed R2024a and the code freezes when creating the first series of listeners. it does not issue any error mistake but I just hear my PC working very hard suddenly, with matlab using suddenly up to 20% of the CPU. I saw this thread
https://www.mathworks.com/matlabcentral/answers/287708-some-matlab-versions-crash-when-using-listener
regarding potentially the same issue but it was for R2015.
I tried as well to install R2023b and the code freezes as well. for comparison I use the exact same code with the same figure and the same amount of added line (20) on all three versions. this is what I get
R2022b: lines and listeners added in 6 sec. CPU usage max up to 25%
R2023b: lines and listeners added in >120 sec (I killed the process). CPU usage max up to 16 % at the start, but steady at 12% until I kill the process.
R2024a: lines and listeners added in >120 sec (I killed the process). CPU usage max up to 25 % at the start, but steady at 15% until I kill the process.
I tried as well with lower amount of line (5) and all three version worked. it was very fast for R2022b (<1sec) and took about 5 sec. for R2023b and R2024a.
My code is certainly not optimal. I was learning how to make a GUI while doing it and after the fact I saw how I could have make it better, but since it was working I did not bother…and of course now I don’t really "remember" all that I did back in 2022.
without seeing the code, would you be able to tell me what changed between R2022b and R2023b/R2024a that would make my code that much slowlier? would you have a quick fix? freezing code, addlisteners, r2023, r2024 MATLAB Answers — New Questions
How to convert this fplot to 3D plot view
syms z
t=0.2;
sc=0.6;
s1=z;
s2=2*(sqrt(t));
x=(s1./s2);
c5=exp((2*x*(sqrt(sc*t))));
c6=erfc((x*sqrt(sc))+(sqrt(t)));
c7=exp((-2*x*(sqrt(t*sc))));
c8=erfc((x*sqrt(sc))-(sqrt(t)));
q=((1/2)*((c5*c6)+(c7*c8)));
xlim([0 5]);
ylim([0 1]);
fplot(z,q)
hold on
legend ("sc=2.01","sc=","sc=0.6");
xlabel("η (Similarity parameter)");
ylabel("C (Concentration)");syms z
t=0.2;
sc=0.6;
s1=z;
s2=2*(sqrt(t));
x=(s1./s2);
c5=exp((2*x*(sqrt(sc*t))));
c6=erfc((x*sqrt(sc))+(sqrt(t)));
c7=exp((-2*x*(sqrt(t*sc))));
c8=erfc((x*sqrt(sc))-(sqrt(t)));
q=((1/2)*((c5*c6)+(c7*c8)));
xlim([0 5]);
ylim([0 1]);
fplot(z,q)
hold on
legend ("sc=2.01","sc=","sc=0.6");
xlabel("η (Similarity parameter)");
ylabel("C (Concentration)"); syms z
t=0.2;
sc=0.6;
s1=z;
s2=2*(sqrt(t));
x=(s1./s2);
c5=exp((2*x*(sqrt(sc*t))));
c6=erfc((x*sqrt(sc))+(sqrt(t)));
c7=exp((-2*x*(sqrt(t*sc))));
c8=erfc((x*sqrt(sc))-(sqrt(t)));
q=((1/2)*((c5*c6)+(c7*c8)));
xlim([0 5]);
ylim([0 1]);
fplot(z,q)
hold on
legend ("sc=2.01","sc=","sc=0.6");
xlabel("η (Similarity parameter)");
ylabel("C (Concentration)"); 3d plots, matlab function MATLAB Answers — New Questions
errors: Point Cloud Classification Using PointNet Deep Learning
‘modelGradients’ :
Generate Synthetic Signals Using Conditional GAN
Model-Based Reinforcement Learning Using Custom Training Loop
error: deep.internal.dlfeval (Line 17)
[varargout{1:nargout}] = fun(x{:});
error: deep.internal.dlfevalWithNestingCheck (Line 19)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
error: dlfeval (Line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:});
error:
[gradients, loss, state, acc] = dlfeval(@modelGradients,XTrain,YTrain,parameters,state);’modelGradients’ :
Generate Synthetic Signals Using Conditional GAN
Model-Based Reinforcement Learning Using Custom Training Loop
error: deep.internal.dlfeval (Line 17)
[varargout{1:nargout}] = fun(x{:});
error: deep.internal.dlfevalWithNestingCheck (Line 19)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
error: dlfeval (Line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:});
error:
[gradients, loss, state, acc] = dlfeval(@modelGradients,XTrain,YTrain,parameters,state); ‘modelGradients’ :
Generate Synthetic Signals Using Conditional GAN
Model-Based Reinforcement Learning Using Custom Training Loop
error: deep.internal.dlfeval (Line 17)
[varargout{1:nargout}] = fun(x{:});
error: deep.internal.dlfevalWithNestingCheck (Line 19)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
error: dlfeval (Line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:});
error:
[gradients, loss, state, acc] = dlfeval(@modelGradients,XTrain,YTrain,parameters,state); pointnet MATLAB Answers — New Questions
Regarding the plant creation in simulink.
How to create the general plant or custom plant to connect the ouputs from neural network predictive controller??How to create the general plant or custom plant to connect the ouputs from neural network predictive controller?? How to create the general plant or custom plant to connect the ouputs from neural network predictive controller?? plant, neural network predictive controller MATLAB Answers — New Questions
how to open .mhd file
DEAR ALL,
Anyone know how to open this image as attached. the file format is .mhdDEAR ALL,
Anyone know how to open this image as attached. the file format is .mhd DEAR ALL,
Anyone know how to open this image as attached. the file format is .mhd image processing, image analysis, image acquisition, digital image processing MATLAB Answers — New Questions
How to change xlim to specific range only?
a=xlsread(‘output1.xlsx’,’final graph’);
xaxis=0:9;
yaxis=a(:,2);
yaxis1=a(:,3);
yaxis=a(:,4);
yaxis2=a(:,5);
figure
plot(xaxis,yaxis)
hold on
plot(xaxis,yaxis1)
hold on
plot(xaxis,yaxis2)
how to change xlim to specific to 0 :3:9 ylim to 30:30:300 how to insert data tips or markers at each point of xaxisa=xlsread(‘output1.xlsx’,’final graph’);
xaxis=0:9;
yaxis=a(:,2);
yaxis1=a(:,3);
yaxis=a(:,4);
yaxis2=a(:,5);
figure
plot(xaxis,yaxis)
hold on
plot(xaxis,yaxis1)
hold on
plot(xaxis,yaxis2)
how to change xlim to specific to 0 :3:9 ylim to 30:30:300 how to insert data tips or markers at each point of xaxis a=xlsread(‘output1.xlsx’,’final graph’);
xaxis=0:9;
yaxis=a(:,2);
yaxis1=a(:,3);
yaxis=a(:,4);
yaxis2=a(:,5);
figure
plot(xaxis,yaxis)
hold on
plot(xaxis,yaxis1)
hold on
plot(xaxis,yaxis2)
how to change xlim to specific to 0 :3:9 ylim to 30:30:300 how to insert data tips or markers at each point of xaxis tick marks MATLAB Answers — New Questions
How to correctly calculate three-phase voltage at the PCC parallel point when placing a STATCOM?
I simulated STATCOM model and found that the calculated voltage at PCC point is not correct with the discrete solver used, how to get the correct voltage? Here is the model file I built.Thanks.It seems that the PCC voltage is not solved correctly.I simulated STATCOM model and found that the calculated voltage at PCC point is not correct with the discrete solver used, how to get the correct voltage? Here is the model file I built.Thanks.It seems that the PCC voltage is not solved correctly. I simulated STATCOM model and found that the calculated voltage at PCC point is not correct with the discrete solver used, how to get the correct voltage? Here is the model file I built.Thanks.It seems that the PCC voltage is not solved correctly. power_electronics_control, static reactive power compensator, three-phase inverter MATLAB Answers — New Questions
Why is matlab creating multiple figures
I have a picture of the code and part of what its doing when I run it but it is creating hundreds of figures of the two plots I’m trying to create. Clearly I’m missing somethingI have a picture of the code and part of what its doing when I run it but it is creating hundreds of figures of the two plots I’m trying to create. Clearly I’m missing something I have a picture of the code and part of what its doing when I run it but it is creating hundreds of figures of the two plots I’m trying to create. Clearly I’m missing something matlab MATLAB Answers — New Questions
how to get data from fig use matlab
hi, i want get four colums data from the following fig, how to use matlab to realize this.hi, i want get four colums data from the following fig, how to use matlab to realize this. hi, i want get four colums data from the following fig, how to use matlab to realize this. matlab, data read MATLAB Answers — New Questions
Programmatically to get member data type in In Bus Element Block
Hello everyone
i would like to get data type of member in the bus element
could anyone suggest me with an example codeHello everyone
i would like to get data type of member in the bus element
could anyone suggest me with an example code Hello everyone
i would like to get data type of member in the bus element
could anyone suggest me with an example code in bus element MATLAB Answers — New Questions
Error using mkdir with “lock folders” in a parfor loop
I am writing parfor loops and using folders as "lock files" for thread safety because mkdir is atomic and I believe is therefore the best option in MATLAB for a "lock file". However, I am getting the following error:
Error using makeLockFile
The system cannot find the path specified.
This error occurs on the line in makeLockFile containing
mkdir(pidPath);
Here is my code for makeLockFile (top), releaseLockFile (middle), and the helper function getMATLABPids (bottom):
What I am trying to do is:
Create a "lock folder". This folder has the same path as a .mat file (except the extension of course). If it exists, that means a MATLAB instance is using the corresponding .mat file.
If successful, create a subfolder named as the instance’s process ID, and return. This is where the issue is!
If unsuccessful, that means another process has locked this variable. In that case, remove any previous (now inactive) process’s lock subfolders that were left behind due to interrupted processes (this ensures that a process that is no longer running is not the sole reason for a lock). Then try deleting the lock folder. If that fails, pause and repeat.
When I encounter the above error, I can restart the process and then it runs all the way through, so I know it’s not a path correctness issue.
I don’t know how to debug this any further, I’ve been using disp() but can’t make heads or tails of why mkdir would ever fail in this context.
function [pidPath, status] = makeLockFile(lockFolderPath)
%% PURPOSE: CREATE A LOCK FOLDER, BECAUSE MKDIR IS ATOMIC.
% Clean the lockFolderPath and add the process ID.
[folderPath, folderName] = fileparts(lockFolderPath);
pid = num2str(feature(‘getpid’)); % Get MATLAB instance’s process ID.
lockFolderPath = [folderPath filesep folderName];
pidPath = [lockFolderPath filesep pid];
status=false;
while ~status
disp([‘PID: ‘ pid ‘ Lock Folder: ‘ lockFolderPath]);
[status, message, messageID] = mkdir(lockFolderPath);
try
if ~status
% The variable is locked.
% Get the listing of all folders in the variable folder
items = dir(lockFolderPath);
folderItems = items([items.isdir]);
folderNames = {folderItems.name};
folderNames(ismember(folderNames, {‘.’, ‘..’})) = []; % Remove ‘.’ and ‘..’
% Get all of the active MATLAB PID’s
pids = getMATLABPids();
% Remove the inactive (leftover from previous processes) PID’s
inactivePIDs = folderNames(~ismember(folderNames, pids));
for i = 1:length(inactivePIDs)
rmdir([lockFolderPath filesep inactivePIDs{i}]);
end
% Try releasing the lock folder. Has no effect if folder is not
% empty (i.e. active process folders present)
releaseLockFile(pidPath);
continue;
else
% Make the folder for this specific process ID
mkdir(pidPath);
end
catch ME
disp([‘ERROR PID: ‘ pid ‘ Lock Folder Path: ‘ pidPath]);
disp({ME.stack.file});
disp({ME.stack.name});
disp({ME.stack.line});
rethrow(ME);
end
end
end
function [] = releaseLockFile(pidPath)
%% PURPOSE: RELEASE THE LOCK FILE.
status = rmdir(pidPath); % PID-specific folder.
pid = feature(‘getpid’);
lockFolderPath = fileparts(pidPath); % Parent folder (the lock folder)
status = rmdir(lockFolderPath); % Remove the folder only if it is empty.
end
function [pids] = getMATLABPids()
%% PURPOSE: GET ALL OF THE PROCESS ID’S FOR ALL MATLAB INSTANCES
if ispc==1
% Execute the command to get a list of all running MATLAB processes
[status, result] = system(‘tasklist /FI "IMAGENAME eq matlab.exe" /FO LIST’);
% Check if the command was successful
if status == 0
% Process the result to extract PIDs
lines = strsplit(result, ‘n’);
pids = [];
for i = 1:length(lines)
line = strtrim(lines{i});
if startsWith(line, ‘PID:’)
pid = extractAfter(line, ‘PID:’);
pids = [pids; {pid}];
end
end
else
error(‘Failed to execute system command. Status: %d’, status);
end
else
% Execute the command to get PIDs of running MATLAB processes
[status, result] = system(‘pgrep matlab’);
% Check if the command was successful
if status == 0
% Process the result to extract PIDs
pids = strsplit(strtrim(result));
else
error(‘Failed to execute system command. Status: %d’, status);
end
end
endI am writing parfor loops and using folders as "lock files" for thread safety because mkdir is atomic and I believe is therefore the best option in MATLAB for a "lock file". However, I am getting the following error:
Error using makeLockFile
The system cannot find the path specified.
This error occurs on the line in makeLockFile containing
mkdir(pidPath);
Here is my code for makeLockFile (top), releaseLockFile (middle), and the helper function getMATLABPids (bottom):
What I am trying to do is:
Create a "lock folder". This folder has the same path as a .mat file (except the extension of course). If it exists, that means a MATLAB instance is using the corresponding .mat file.
If successful, create a subfolder named as the instance’s process ID, and return. This is where the issue is!
If unsuccessful, that means another process has locked this variable. In that case, remove any previous (now inactive) process’s lock subfolders that were left behind due to interrupted processes (this ensures that a process that is no longer running is not the sole reason for a lock). Then try deleting the lock folder. If that fails, pause and repeat.
When I encounter the above error, I can restart the process and then it runs all the way through, so I know it’s not a path correctness issue.
I don’t know how to debug this any further, I’ve been using disp() but can’t make heads or tails of why mkdir would ever fail in this context.
function [pidPath, status] = makeLockFile(lockFolderPath)
%% PURPOSE: CREATE A LOCK FOLDER, BECAUSE MKDIR IS ATOMIC.
% Clean the lockFolderPath and add the process ID.
[folderPath, folderName] = fileparts(lockFolderPath);
pid = num2str(feature(‘getpid’)); % Get MATLAB instance’s process ID.
lockFolderPath = [folderPath filesep folderName];
pidPath = [lockFolderPath filesep pid];
status=false;
while ~status
disp([‘PID: ‘ pid ‘ Lock Folder: ‘ lockFolderPath]);
[status, message, messageID] = mkdir(lockFolderPath);
try
if ~status
% The variable is locked.
% Get the listing of all folders in the variable folder
items = dir(lockFolderPath);
folderItems = items([items.isdir]);
folderNames = {folderItems.name};
folderNames(ismember(folderNames, {‘.’, ‘..’})) = []; % Remove ‘.’ and ‘..’
% Get all of the active MATLAB PID’s
pids = getMATLABPids();
% Remove the inactive (leftover from previous processes) PID’s
inactivePIDs = folderNames(~ismember(folderNames, pids));
for i = 1:length(inactivePIDs)
rmdir([lockFolderPath filesep inactivePIDs{i}]);
end
% Try releasing the lock folder. Has no effect if folder is not
% empty (i.e. active process folders present)
releaseLockFile(pidPath);
continue;
else
% Make the folder for this specific process ID
mkdir(pidPath);
end
catch ME
disp([‘ERROR PID: ‘ pid ‘ Lock Folder Path: ‘ pidPath]);
disp({ME.stack.file});
disp({ME.stack.name});
disp({ME.stack.line});
rethrow(ME);
end
end
end
function [] = releaseLockFile(pidPath)
%% PURPOSE: RELEASE THE LOCK FILE.
status = rmdir(pidPath); % PID-specific folder.
pid = feature(‘getpid’);
lockFolderPath = fileparts(pidPath); % Parent folder (the lock folder)
status = rmdir(lockFolderPath); % Remove the folder only if it is empty.
end
function [pids] = getMATLABPids()
%% PURPOSE: GET ALL OF THE PROCESS ID’S FOR ALL MATLAB INSTANCES
if ispc==1
% Execute the command to get a list of all running MATLAB processes
[status, result] = system(‘tasklist /FI "IMAGENAME eq matlab.exe" /FO LIST’);
% Check if the command was successful
if status == 0
% Process the result to extract PIDs
lines = strsplit(result, ‘n’);
pids = [];
for i = 1:length(lines)
line = strtrim(lines{i});
if startsWith(line, ‘PID:’)
pid = extractAfter(line, ‘PID:’);
pids = [pids; {pid}];
end
end
else
error(‘Failed to execute system command. Status: %d’, status);
end
else
% Execute the command to get PIDs of running MATLAB processes
[status, result] = system(‘pgrep matlab’);
% Check if the command was successful
if status == 0
% Process the result to extract PIDs
pids = strsplit(strtrim(result));
else
error(‘Failed to execute system command. Status: %d’, status);
end
end
end I am writing parfor loops and using folders as "lock files" for thread safety because mkdir is atomic and I believe is therefore the best option in MATLAB for a "lock file". However, I am getting the following error:
Error using makeLockFile
The system cannot find the path specified.
This error occurs on the line in makeLockFile containing
mkdir(pidPath);
Here is my code for makeLockFile (top), releaseLockFile (middle), and the helper function getMATLABPids (bottom):
What I am trying to do is:
Create a "lock folder". This folder has the same path as a .mat file (except the extension of course). If it exists, that means a MATLAB instance is using the corresponding .mat file.
If successful, create a subfolder named as the instance’s process ID, and return. This is where the issue is!
If unsuccessful, that means another process has locked this variable. In that case, remove any previous (now inactive) process’s lock subfolders that were left behind due to interrupted processes (this ensures that a process that is no longer running is not the sole reason for a lock). Then try deleting the lock folder. If that fails, pause and repeat.
When I encounter the above error, I can restart the process and then it runs all the way through, so I know it’s not a path correctness issue.
I don’t know how to debug this any further, I’ve been using disp() but can’t make heads or tails of why mkdir would ever fail in this context.
function [pidPath, status] = makeLockFile(lockFolderPath)
%% PURPOSE: CREATE A LOCK FOLDER, BECAUSE MKDIR IS ATOMIC.
% Clean the lockFolderPath and add the process ID.
[folderPath, folderName] = fileparts(lockFolderPath);
pid = num2str(feature(‘getpid’)); % Get MATLAB instance’s process ID.
lockFolderPath = [folderPath filesep folderName];
pidPath = [lockFolderPath filesep pid];
status=false;
while ~status
disp([‘PID: ‘ pid ‘ Lock Folder: ‘ lockFolderPath]);
[status, message, messageID] = mkdir(lockFolderPath);
try
if ~status
% The variable is locked.
% Get the listing of all folders in the variable folder
items = dir(lockFolderPath);
folderItems = items([items.isdir]);
folderNames = {folderItems.name};
folderNames(ismember(folderNames, {‘.’, ‘..’})) = []; % Remove ‘.’ and ‘..’
% Get all of the active MATLAB PID’s
pids = getMATLABPids();
% Remove the inactive (leftover from previous processes) PID’s
inactivePIDs = folderNames(~ismember(folderNames, pids));
for i = 1:length(inactivePIDs)
rmdir([lockFolderPath filesep inactivePIDs{i}]);
end
% Try releasing the lock folder. Has no effect if folder is not
% empty (i.e. active process folders present)
releaseLockFile(pidPath);
continue;
else
% Make the folder for this specific process ID
mkdir(pidPath);
end
catch ME
disp([‘ERROR PID: ‘ pid ‘ Lock Folder Path: ‘ pidPath]);
disp({ME.stack.file});
disp({ME.stack.name});
disp({ME.stack.line});
rethrow(ME);
end
end
end
function [] = releaseLockFile(pidPath)
%% PURPOSE: RELEASE THE LOCK FILE.
status = rmdir(pidPath); % PID-specific folder.
pid = feature(‘getpid’);
lockFolderPath = fileparts(pidPath); % Parent folder (the lock folder)
status = rmdir(lockFolderPath); % Remove the folder only if it is empty.
end
function [pids] = getMATLABPids()
%% PURPOSE: GET ALL OF THE PROCESS ID’S FOR ALL MATLAB INSTANCES
if ispc==1
% Execute the command to get a list of all running MATLAB processes
[status, result] = system(‘tasklist /FI "IMAGENAME eq matlab.exe" /FO LIST’);
% Check if the command was successful
if status == 0
% Process the result to extract PIDs
lines = strsplit(result, ‘n’);
pids = [];
for i = 1:length(lines)
line = strtrim(lines{i});
if startsWith(line, ‘PID:’)
pid = extractAfter(line, ‘PID:’);
pids = [pids; {pid}];
end
end
else
error(‘Failed to execute system command. Status: %d’, status);
end
else
% Execute the command to get PIDs of running MATLAB processes
[status, result] = system(‘pgrep matlab’);
% Check if the command was successful
if status == 0
% Process the result to extract PIDs
pids = strsplit(strtrim(result));
else
error(‘Failed to execute system command. Status: %d’, status);
end
end
end parallel computing, parallel computing toolbox, mkdir, path, lock, system MATLAB Answers — New Questions
MathJax in Matlab Help Browser
Anyone know if it’s possible to do this?
Matlab’s web viewer (using web command on local file) shows HTML files that use MathJax just fine. However, when I index the HTML file in a helptoc.xml, so that the file can be viewed in the Help Browser, the MathJax rendered equations are not shown. I assume the javascript that loads MathJax isn’t even being run when viewing the file in the Help Browser, but perhaps there is a way.
MathML would be acceptible (and probably superior) but the Help Browser does not seem to support MathML at all.
I no interest in using Live Script or any other publishing solution built into Matlab. The HTML is coming from a source external to Matlab.Anyone know if it’s possible to do this?
Matlab’s web viewer (using web command on local file) shows HTML files that use MathJax just fine. However, when I index the HTML file in a helptoc.xml, so that the file can be viewed in the Help Browser, the MathJax rendered equations are not shown. I assume the javascript that loads MathJax isn’t even being run when viewing the file in the Help Browser, but perhaps there is a way.
MathML would be acceptible (and probably superior) but the Help Browser does not seem to support MathML at all.
I no interest in using Live Script or any other publishing solution built into Matlab. The HTML is coming from a source external to Matlab. Anyone know if it’s possible to do this?
Matlab’s web viewer (using web command on local file) shows HTML files that use MathJax just fine. However, when I index the HTML file in a helptoc.xml, so that the file can be viewed in the Help Browser, the MathJax rendered equations are not shown. I assume the javascript that loads MathJax isn’t even being run when viewing the file in the Help Browser, but perhaps there is a way.
MathML would be acceptible (and probably superior) but the Help Browser does not seem to support MathML at all.
I no interest in using Live Script or any other publishing solution built into Matlab. The HTML is coming from a source external to Matlab. matlab, mathjax, help browser MATLAB Answers — New Questions
How to remove pwd residue with auto-correlation
I have a sum of sine waves with transmission loss applied in a row.
And pwd is 10e-3. Because of this, the residue of the previous pwd remains in the part where the signal is not generated,
blurring the entire signal. My mentor said that I can remove it using auto-correlation.
However, he said to remove it using the filter format instead of using functions such as xcorr.
I don’t understand this part. If there is an expert in this field, please let me know what the intended part is along with the method.
I’ve attached a picture plotting one row of those signals.
If you need any further information, please let me know and I will get back to you as soon as possible.
%sampling F
Fs = 100e3; %
time_step = 1 / Fs;
distance_step = 2 * time_step * soundSpeed;
max_time = min(L_values(:));
pwd = 10e-3;
tt = 0 : time_step : pwd;
F = 1000; %sine wave F
input_sig = sin(2 * pi * F * tt);
round_distance = soundSpeed * dist_time; %soundspeed = 1500(m/s)
TL = 40 * log10(round_distance);
TL_signal = input_sig * 10^(-TL/20);I have a sum of sine waves with transmission loss applied in a row.
And pwd is 10e-3. Because of this, the residue of the previous pwd remains in the part where the signal is not generated,
blurring the entire signal. My mentor said that I can remove it using auto-correlation.
However, he said to remove it using the filter format instead of using functions such as xcorr.
I don’t understand this part. If there is an expert in this field, please let me know what the intended part is along with the method.
I’ve attached a picture plotting one row of those signals.
If you need any further information, please let me know and I will get back to you as soon as possible.
%sampling F
Fs = 100e3; %
time_step = 1 / Fs;
distance_step = 2 * time_step * soundSpeed;
max_time = min(L_values(:));
pwd = 10e-3;
tt = 0 : time_step : pwd;
F = 1000; %sine wave F
input_sig = sin(2 * pi * F * tt);
round_distance = soundSpeed * dist_time; %soundspeed = 1500(m/s)
TL = 40 * log10(round_distance);
TL_signal = input_sig * 10^(-TL/20); I have a sum of sine waves with transmission loss applied in a row.
And pwd is 10e-3. Because of this, the residue of the previous pwd remains in the part where the signal is not generated,
blurring the entire signal. My mentor said that I can remove it using auto-correlation.
However, he said to remove it using the filter format instead of using functions such as xcorr.
I don’t understand this part. If there is an expert in this field, please let me know what the intended part is along with the method.
I’ve attached a picture plotting one row of those signals.
If you need any further information, please let me know and I will get back to you as soon as possible.
%sampling F
Fs = 100e3; %
time_step = 1 / Fs;
distance_step = 2 * time_step * soundSpeed;
max_time = min(L_values(:));
pwd = 10e-3;
tt = 0 : time_step : pwd;
F = 1000; %sine wave F
input_sig = sin(2 * pi * F * tt);
round_distance = soundSpeed * dist_time; %soundspeed = 1500(m/s)
TL = 40 * log10(round_distance);
TL_signal = input_sig * 10^(-TL/20); autocorrelation, correlation, signal, transmissionloss, signalprocessing MATLAB Answers — New Questions
ERA SystemID and Compare() function
I am attempting to use era() to idetify a state space realization of my system and validate it using the compare() function. The system I am trying to identify is a steel cube with a heater attached to one side. The system starts at a state state of 0C and then heater applies an impulse flux to distrube the system.
When I use the compare() function to validate my system I see a good fit, but weird initial conditons. I am exspecting the inital conditons to be equal to 0 since all the data starts from steady state = 0C, however the compare() function estimates non-zeros initial conditions. Why is this happening?
Attached is my code and estiamtion / validation data sets.
Thanks in advance.I am attempting to use era() to idetify a state space realization of my system and validate it using the compare() function. The system I am trying to identify is a steel cube with a heater attached to one side. The system starts at a state state of 0C and then heater applies an impulse flux to distrube the system.
When I use the compare() function to validate my system I see a good fit, but weird initial conditons. I am exspecting the inital conditons to be equal to 0 since all the data starts from steady state = 0C, however the compare() function estimates non-zeros initial conditions. Why is this happening?
Attached is my code and estiamtion / validation data sets.
Thanks in advance. I am attempting to use era() to idetify a state space realization of my system and validate it using the compare() function. The system I am trying to identify is a steel cube with a heater attached to one side. The system starts at a state state of 0C and then heater applies an impulse flux to distrube the system.
When I use the compare() function to validate my system I see a good fit, but weird initial conditons. I am exspecting the inital conditons to be equal to 0 since all the data starts from steady state = 0C, however the compare() function estimates non-zeros initial conditions. Why is this happening?
Attached is my code and estiamtion / validation data sets.
Thanks in advance. system identification, validation MATLAB Answers — New Questions
update vector data to start with a different value at specific point.
Dear community, I’d like to ask your support to find a solution for below condition.
I have 6 vectors. time, CtTHiRes, HiResCalc, CtTgrdCalc, idx8 and TS_tClntEngOut
my goal is to calculate HiResCalc which it will have same values as CtTHiRes using CtTgrdCalc.
for ii = 2:N+1
if exist (‘time’)
HiResCalc(ii) = CtTgrdCalc(ii-1) + HiResCalc(ii-1);
end
I’m stuck trying to update HiResCalc…..
what I need to do is when idx8 = 0, HiResCalc should be updated and get whathever the valu is in TS_tClntEngOut, in this case the update happens at second 250 but it can be anyother time.
after HiResCalc is updated, calculation should continue as shonw in the script above but I don’t know how to make it…..
for ia= 1:length(HiResCalc);
if idx8(ia) == 0
HiResCalc(ia,1) = TS_tClntEngOut(ia);
end
end
here is an image for your reffrence…
as before any feedback will be highly appreciatedDear community, I’d like to ask your support to find a solution for below condition.
I have 6 vectors. time, CtTHiRes, HiResCalc, CtTgrdCalc, idx8 and TS_tClntEngOut
my goal is to calculate HiResCalc which it will have same values as CtTHiRes using CtTgrdCalc.
for ii = 2:N+1
if exist (‘time’)
HiResCalc(ii) = CtTgrdCalc(ii-1) + HiResCalc(ii-1);
end
I’m stuck trying to update HiResCalc…..
what I need to do is when idx8 = 0, HiResCalc should be updated and get whathever the valu is in TS_tClntEngOut, in this case the update happens at second 250 but it can be anyother time.
after HiResCalc is updated, calculation should continue as shonw in the script above but I don’t know how to make it…..
for ia= 1:length(HiResCalc);
if idx8(ia) == 0
HiResCalc(ia,1) = TS_tClntEngOut(ia);
end
end
here is an image for your reffrence…
as before any feedback will be highly appreciated Dear community, I’d like to ask your support to find a solution for below condition.
I have 6 vectors. time, CtTHiRes, HiResCalc, CtTgrdCalc, idx8 and TS_tClntEngOut
my goal is to calculate HiResCalc which it will have same values as CtTHiRes using CtTgrdCalc.
for ii = 2:N+1
if exist (‘time’)
HiResCalc(ii) = CtTgrdCalc(ii-1) + HiResCalc(ii-1);
end
I’m stuck trying to update HiResCalc…..
what I need to do is when idx8 = 0, HiResCalc should be updated and get whathever the valu is in TS_tClntEngOut, in this case the update happens at second 250 but it can be anyother time.
after HiResCalc is updated, calculation should continue as shonw in the script above but I don’t know how to make it…..
for ia= 1:length(HiResCalc);
if idx8(ia) == 0
HiResCalc(ia,1) = TS_tClntEngOut(ia);
end
end
here is an image for your reffrence…
as before any feedback will be highly appreciated data, analysis MATLAB Answers — New Questions
Size of the left side different from the right side
Hi everyone, I’m facing a problem with assignment because of different sizes.
I’m pretty sure the sizes are the same, its look like MATLAB refer to the input size instead of the output (in the relevant function).
the error massege: "Unable to perform assignment because the size of the left side is 1-by-6 and the size of the right side
is 1-by-108".
thanks a lot!
the problematic line:
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
My code -main function:
SParraydata=table2array(SPdata);
personalSPdata=zeros(51444,2);
PersonalSPQmain=zeros(8574,6);
PersonalSPAnsmain=zeros(8574,6);
j=1;
for i=1:8574
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
personalSPdata(j:j+5,2) = sixSPAnsLines(PersonalSPQmain(i,:),PersonalSPAnsmain(i,:));
j=j+5;
end
The relevent function:
function [PersonalSPQ,PersonalSPAns] = PersonalSPQforResponder(SPAnsVector)
PersonalSPQ=zeros(1,6);
PersonalSPAns=zeros(1,6);
j=1;
for i=1:108
if isempty(SPAnsVector(1,i))==0
PersonalSPQ(1,j)=i;
PersonalSPAns(1,j)=SPAnsVector(1,i);
j=j+1;
end
end
endHi everyone, I’m facing a problem with assignment because of different sizes.
I’m pretty sure the sizes are the same, its look like MATLAB refer to the input size instead of the output (in the relevant function).
the error massege: "Unable to perform assignment because the size of the left side is 1-by-6 and the size of the right side
is 1-by-108".
thanks a lot!
the problematic line:
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
My code -main function:
SParraydata=table2array(SPdata);
personalSPdata=zeros(51444,2);
PersonalSPQmain=zeros(8574,6);
PersonalSPAnsmain=zeros(8574,6);
j=1;
for i=1:8574
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
personalSPdata(j:j+5,2) = sixSPAnsLines(PersonalSPQmain(i,:),PersonalSPAnsmain(i,:));
j=j+5;
end
The relevent function:
function [PersonalSPQ,PersonalSPAns] = PersonalSPQforResponder(SPAnsVector)
PersonalSPQ=zeros(1,6);
PersonalSPAns=zeros(1,6);
j=1;
for i=1:108
if isempty(SPAnsVector(1,i))==0
PersonalSPQ(1,j)=i;
PersonalSPAns(1,j)=SPAnsVector(1,i);
j=j+1;
end
end
end Hi everyone, I’m facing a problem with assignment because of different sizes.
I’m pretty sure the sizes are the same, its look like MATLAB refer to the input size instead of the output (in the relevant function).
the error massege: "Unable to perform assignment because the size of the left side is 1-by-6 and the size of the right side
is 1-by-108".
thanks a lot!
the problematic line:
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
My code -main function:
SParraydata=table2array(SPdata);
personalSPdata=zeros(51444,2);
PersonalSPQmain=zeros(8574,6);
PersonalSPAnsmain=zeros(8574,6);
j=1;
for i=1:8574
[PersonalSPQmain(i,:),PersonalSPAnsmain(i,:)] = PersonalSPQforResponder(SParraydata(i,:));
personalSPdata(j:j+5,2) = sixSPAnsLines(PersonalSPQmain(i,:),PersonalSPAnsmain(i,:));
j=j+5;
end
The relevent function:
function [PersonalSPQ,PersonalSPAns] = PersonalSPQforResponder(SPAnsVector)
PersonalSPQ=zeros(1,6);
PersonalSPAns=zeros(1,6);
j=1;
for i=1:108
if isempty(SPAnsVector(1,i))==0
PersonalSPQ(1,j)=i;
PersonalSPAns(1,j)=SPAnsVector(1,i);
j=j+1;
end
end
end size, assigment, error MATLAB Answers — New Questions
MATLAB Arduino Uno Simulink doesn’t have option for Connected IO Mode
Hello;
I’m trying to use Simulink to get input from Beckhoff TwinCAT (reading an EtherCAT sensor) and then output it to an Arduino as a set of PWM waves (to control some coil currents). To do this, I’m trying to link the TwinCAT integration to the Simulink Support Package for Arduino Hardware on MATLAB R2021a on a laptop running MATLAB R2021a; however, I don’t see the option to switch the mode to Connected IO in the top Hardware bar. I have tried enabling Connected IO in the hardware settings for the Arduino Uno on Simulink, but the option is still not showing up.
Is there something else I am missing?Hello;
I’m trying to use Simulink to get input from Beckhoff TwinCAT (reading an EtherCAT sensor) and then output it to an Arduino as a set of PWM waves (to control some coil currents). To do this, I’m trying to link the TwinCAT integration to the Simulink Support Package for Arduino Hardware on MATLAB R2021a on a laptop running MATLAB R2021a; however, I don’t see the option to switch the mode to Connected IO in the top Hardware bar. I have tried enabling Connected IO in the hardware settings for the Arduino Uno on Simulink, but the option is still not showing up.
Is there something else I am missing? Hello;
I’m trying to use Simulink to get input from Beckhoff TwinCAT (reading an EtherCAT sensor) and then output it to an Arduino as a set of PWM waves (to control some coil currents). To do this, I’m trying to link the TwinCAT integration to the Simulink Support Package for Arduino Hardware on MATLAB R2021a on a laptop running MATLAB R2021a; however, I don’t see the option to switch the mode to Connected IO in the top Hardware bar. I have tried enabling Connected IO in the hardware settings for the Arduino Uno on Simulink, but the option is still not showing up.
Is there something else I am missing? r2021a, simulink, arduino MATLAB Answers — New Questions