Category: Matlab
Category Archives: Matlab
How to set a sample time in a Discrete Transfer Fcn??
I’m following the training of Simulink fundamentals, and I’m stucked trying to set the sample time on the parameters. Is not showing me that option to set it. I attached an image for you to view. Please I need some help with this is the only task that is left to end the course. Thanks in advance.I’m following the training of Simulink fundamentals, and I’m stucked trying to set the sample time on the parameters. Is not showing me that option to set it. I attached an image for you to view. Please I need some help with this is the only task that is left to end the course. Thanks in advance. I’m following the training of Simulink fundamentals, and I’m stucked trying to set the sample time on the parameters. Is not showing me that option to set it. I attached an image for you to view. Please I need some help with this is the only task that is left to end the course. Thanks in advance. simulink fundamentals, sample time, discrete transfer function, parameters, simulink MATLAB Answers — New Questions
Why does Python 3.6 fail to import MATLAB Engine and give a “DLL load failed” error?
I am using MATLAB R2018a. I have installed CPython 3.6.7 and installed MATLAB engine as mentioned in the documentation page obtained by running the following command on MATLAB R2018a:
web(fullfile(docroot, ‘matlab/matlab_external/install-the-matlab-engine-for-python.html’))
But I am getting the below error on executing "
import matlab.engine":
pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSION)
File "C:ProgramsPythonPython36libimportlib_
_init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named ‘matlabengineforpython3_6’
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:ProgramsPythonPython36libsite-packag
esmatlabengine__init__.py", line 59, in <module>
pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSIO
N)
File "C:ProgramsPythonPython36libimportlib_
_init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
File "<frozen importlib._bootstrap>", line 571, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 922, in create_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed: The specified procedure could not be found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:PythonPython36libsite-packag
esmatlabengine__init__.py", line 62, in <module>
‘MathWorks Technical Support for assistance: %s’ % e)
OSError: Please reinstall MATLAB Engine for Python or contact MathWorks Technical Support for assistance: DLL load failed: The specified procedure could not be found.
The file C:Program FilesMATLABR2018aexternenginespythondistmatlabenginewin64matlabengineforpython3_6.pyd also got created.
Please follow the below link to search for the required information regarding the current release:https://www.mathworks.com/help/I am using MATLAB R2018a. I have installed CPython 3.6.7 and installed MATLAB engine as mentioned in the documentation page obtained by running the following command on MATLAB R2018a:
web(fullfile(docroot, ‘matlab/matlab_external/install-the-matlab-engine-for-python.html’))
But I am getting the below error on executing "
import matlab.engine":
pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSION)
File "C:ProgramsPythonPython36libimportlib_
_init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named ‘matlabengineforpython3_6’
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:ProgramsPythonPython36libsite-packag
esmatlabengine__init__.py", line 59, in <module>
pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSIO
N)
File "C:ProgramsPythonPython36libimportlib_
_init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
File "<frozen importlib._bootstrap>", line 571, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 922, in create_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed: The specified procedure could not be found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:PythonPython36libsite-packag
esmatlabengine__init__.py", line 62, in <module>
‘MathWorks Technical Support for assistance: %s’ % e)
OSError: Please reinstall MATLAB Engine for Python or contact MathWorks Technical Support for assistance: DLL load failed: The specified procedure could not be found.
The file C:Program FilesMATLABR2018aexternenginespythondistmatlabenginewin64matlabengineforpython3_6.pyd also got created.
Please follow the below link to search for the required information regarding the current release:https://www.mathworks.com/help/ I am using MATLAB R2018a. I have installed CPython 3.6.7 and installed MATLAB engine as mentioned in the documentation page obtained by running the following command on MATLAB R2018a:
web(fullfile(docroot, ‘matlab/matlab_external/install-the-matlab-engine-for-python.html’))
But I am getting the below error on executing "
import matlab.engine":
pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSION)
File "C:ProgramsPythonPython36libimportlib_
_init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named ‘matlabengineforpython3_6’
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:ProgramsPythonPython36libsite-packag
esmatlabengine__init__.py", line 59, in <module>
pythonengine = importlib.import_module("matlabengineforpython"+_PYTHONVERSIO
N)
File "C:ProgramsPythonPython36libimportlib_
_init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 658, in _load_unlocked
File "<frozen importlib._bootstrap>", line 571, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 922, in create_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
ImportError: DLL load failed: The specified procedure could not be found.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:PythonPython36libsite-packag
esmatlabengine__init__.py", line 62, in <module>
‘MathWorks Technical Support for assistance: %s’ % e)
OSError: Please reinstall MATLAB Engine for Python or contact MathWorks Technical Support for assistance: DLL load failed: The specified procedure could not be found.
The file C:Program FilesMATLABR2018aexternenginespythondistmatlabenginewin64matlabengineforpython3_6.pyd also got created.
Please follow the below link to search for the required information regarding the current release:https://www.mathworks.com/help/ tbb, engine, api, python3 MATLAB Answers — New Questions
convert a cell Array into another cell
Hi, I have a cell array of A=1×490 cell,
A=
1×490 cell array
Columns 1 through 490
{512×200×32 single} {512×200×32 single} …..
How can I get
A=1×3136000 cell array
Columns 1 through 3136000
{512×1} {512×1} ….
PS:3136000=490*200*32
Thank you.
ChrisHi, I have a cell array of A=1×490 cell,
A=
1×490 cell array
Columns 1 through 490
{512×200×32 single} {512×200×32 single} …..
How can I get
A=1×3136000 cell array
Columns 1 through 3136000
{512×1} {512×1} ….
PS:3136000=490*200*32
Thank you.
Chris Hi, I have a cell array of A=1×490 cell,
A=
1×490 cell array
Columns 1 through 490
{512×200×32 single} {512×200×32 single} …..
How can I get
A=1×3136000 cell array
Columns 1 through 3136000
{512×1} {512×1} ….
PS:3136000=490*200*32
Thank you.
Chris cell array convert MATLAB Answers — New Questions
currentProject() function in Parallel Computing Toolbox
I have a workflow that uses the MATLAB project functions to retrieve information from the MATLAB project. I use currentProject() to get the matlab.project.Project object.
I am trying to run this workflow using the Parallel Computing Toolbox, but seems that the MATLAB project is not available in the MATLAB workers.
Tested it using this code:
parpool(2);
spmd
currentProject();
end
Does the MATLAB project gets transferred into the MATLAB workers, or only the MATLAB path?
Any workaround about how can I pull the Project Reference information in a distributed environment?
Thanks in advance!I have a workflow that uses the MATLAB project functions to retrieve information from the MATLAB project. I use currentProject() to get the matlab.project.Project object.
I am trying to run this workflow using the Parallel Computing Toolbox, but seems that the MATLAB project is not available in the MATLAB workers.
Tested it using this code:
parpool(2);
spmd
currentProject();
end
Does the MATLAB project gets transferred into the MATLAB workers, or only the MATLAB path?
Any workaround about how can I pull the Project Reference information in a distributed environment?
Thanks in advance! I have a workflow that uses the MATLAB project functions to retrieve information from the MATLAB project. I use currentProject() to get the matlab.project.Project object.
I am trying to run this workflow using the Parallel Computing Toolbox, but seems that the MATLAB project is not available in the MATLAB workers.
Tested it using this code:
parpool(2);
spmd
currentProject();
end
Does the MATLAB project gets transferred into the MATLAB workers, or only the MATLAB path?
Any workaround about how can I pull the Project Reference information in a distributed environment?
Thanks in advance! matlab project MATLAB Answers — New Questions
Does Image Acquisition Toolbox support FLIR (Point Grey) Blackfly S model camera?
I have a USB3 Version of model Blackfly S camera from FLIR (Point Grey). The camera is supported by the manufacturer provided Spinnaker SDK libraries.
Is this camera model supported by Image Acquisition Toolbox?I have a USB3 Version of model Blackfly S camera from FLIR (Point Grey). The camera is supported by the manufacturer provided Spinnaker SDK libraries.
Is this camera model supported by Image Acquisition Toolbox? I have a USB3 Version of model Blackfly S camera from FLIR (Point Grey). The camera is supported by the manufacturer provided Spinnaker SDK libraries.
Is this camera model supported by Image Acquisition Toolbox? flir, point, grey, blackfly, s, spinnaker, sdk MATLAB Answers — New Questions
How do you save a figure with a trasparent background?
How do you save a figure with a trasparent background? I want to save a figure as a png image that has a transparent background so I can put the image into PowerPoint and the PowerPoint graphic will show through the Matlab figure.How do you save a figure with a trasparent background? I want to save a figure as a png image that has a transparent background so I can put the image into PowerPoint and the PowerPoint graphic will show through the Matlab figure. How do you save a figure with a trasparent background? I want to save a figure as a png image that has a transparent background so I can put the image into PowerPoint and the PowerPoint graphic will show through the Matlab figure. transparent backgrounf figure, png MATLAB Answers — New Questions
How to find the index of the minimum value in a matrix.
Hi everyone,
So I have a 9×21 matrix, V, and I am trying to find the index (i,j) of the minimum (closest to zero) value in that matrix. I have tried using several forms of the min function, but it keeps returning multiple indices for the the minimum values in each column. I only want one index (i,j), that of the minimum value in the ENTIRE matrix.
How would I go about doing this? Thanks!Hi everyone,
So I have a 9×21 matrix, V, and I am trying to find the index (i,j) of the minimum (closest to zero) value in that matrix. I have tried using several forms of the min function, but it keeps returning multiple indices for the the minimum values in each column. I only want one index (i,j), that of the minimum value in the ENTIRE matrix.
How would I go about doing this? Thanks! Hi everyone,
So I have a 9×21 matrix, V, and I am trying to find the index (i,j) of the minimum (closest to zero) value in that matrix. I have tried using several forms of the min function, but it keeps returning multiple indices for the the minimum values in each column. I only want one index (i,j), that of the minimum value in the ENTIRE matrix.
How would I go about doing this? Thanks! functions, matrix MATLAB Answers — New Questions
How to use global variable in MATLAB discrete-event system block (not MATLAB Function Blocks)?
I want to use global variable in a way like Resource Scheduling Using MATLAB Discrete-Event System and Data Store Memory Blocks. Like the following: After defining the parameter in a Data Store Memory block and declare the corresponding parameter in a MATLAB Discrete-Event System block, that block can access the value. But I can’t implement this feature in my project. I have looked up a lot of information, but none of it has helped. Please help me solve this problem. Thanks!
The information from the diagnostic viewer is:
Warning:System object ignores the global variable ‘BoardDataCollectionProcessBoxDatum1’ added during ‘DatumEntry’ execution. The global variable is either not declared in ‘DatumEntry’ or is declared while using the MATLAB debugger.I want to use global variable in a way like Resource Scheduling Using MATLAB Discrete-Event System and Data Store Memory Blocks. Like the following: After defining the parameter in a Data Store Memory block and declare the corresponding parameter in a MATLAB Discrete-Event System block, that block can access the value. But I can’t implement this feature in my project. I have looked up a lot of information, but none of it has helped. Please help me solve this problem. Thanks!
The information from the diagnostic viewer is:
Warning:System object ignores the global variable ‘BoardDataCollectionProcessBoxDatum1’ added during ‘DatumEntry’ execution. The global variable is either not declared in ‘DatumEntry’ or is declared while using the MATLAB debugger. I want to use global variable in a way like Resource Scheduling Using MATLAB Discrete-Event System and Data Store Memory Blocks. Like the following: After defining the parameter in a Data Store Memory block and declare the corresponding parameter in a MATLAB Discrete-Event System block, that block can access the value. But I can’t implement this feature in my project. I have looked up a lot of information, but none of it has helped. Please help me solve this problem. Thanks!
The information from the diagnostic viewer is:
Warning:System object ignores the global variable ‘BoardDataCollectionProcessBoxDatum1’ added during ‘DatumEntry’ execution. The global variable is either not declared in ‘DatumEntry’ or is declared while using the MATLAB debugger. simulink, discreate event simulation MATLAB Answers — New Questions
volume of set of points in 3d space with gap
Hello,
I have a set of 3D points that represent an artery that has a bifurcation in it, so it splits from one to two branches. I am trying to find the volume. I have tried delaunay triangulation and convex hull but this results in the gap also being filled (see image). Is there any way to make the convex hull fit better to the true data set?
thanks!Hello,
I have a set of 3D points that represent an artery that has a bifurcation in it, so it splits from one to two branches. I am trying to find the volume. I have tried delaunay triangulation and convex hull but this results in the gap also being filled (see image). Is there any way to make the convex hull fit better to the true data set?
thanks! Hello,
I have a set of 3D points that represent an artery that has a bifurcation in it, so it splits from one to two branches. I am trying to find the volume. I have tried delaunay triangulation and convex hull but this results in the gap also being filled (see image). Is there any way to make the convex hull fit better to the true data set?
thanks! volume, convexhull, bifurcation, 3d MATLAB Answers — New Questions
Issue Plotting Array in Imagesc
I am trying to plot an array as an imagesc plot. The array is full of non-zero numbers, but imagesc plots them as zero. I think the issue is with scaling, but I don’t know how to fix it. Screenshots attached to show what I mean. How do I scale my imagesc plot so that the numbers in the array are visible appropriately? Tried looking it up on the documentation but couldn’t find a clear answer for my problem.I am trying to plot an array as an imagesc plot. The array is full of non-zero numbers, but imagesc plots them as zero. I think the issue is with scaling, but I don’t know how to fix it. Screenshots attached to show what I mean. How do I scale my imagesc plot so that the numbers in the array are visible appropriately? Tried looking it up on the documentation but couldn’t find a clear answer for my problem. I am trying to plot an array as an imagesc plot. The array is full of non-zero numbers, but imagesc plots them as zero. I think the issue is with scaling, but I don’t know how to fix it. Screenshots attached to show what I mean. How do I scale my imagesc plot so that the numbers in the array are visible appropriately? Tried looking it up on the documentation but couldn’t find a clear answer for my problem. imagesc MATLAB Answers — New Questions
Kindly guide how to add the single edit field for each RLC like [0.01, …] and different time interval [10, 20, 30] in app designer and also the phase result on interfaces
Kindly guide how to add the single edit field for each RLC like [0.01, …] and different time interval [10, 20, 30] in app designerKindly guide how to add the single edit field for each RLC like [0.01, …] and different time interval [10, 20, 30] in app designer Kindly guide how to add the single edit field for each RLC like [0.01, …] and different time interval [10, 20, 30] in app designer appdesigner MATLAB Answers — New Questions
Index 3D Array with 2D logical array
I have an logical array B and an 3D array A. I wish to extract and manipulate values of A for specific , whereby the values in the first two dimensions are given by B. I was hoping something like
A(B,[1 3 5])
would give me the values specified by B for the first, third and fifth slice of A, but MATLAB doesn’t allow this kind of indexing.
In particular, I would like to switch values given by B for certain (excuse the fauly syntax) akin to
A(B,[1 3 5]) = A(B,[2 4 6])
A minimum example of what I would like to achieve would be:
% coordinate mesh
[X,Y] = meshgrid(1:n,1:m);
% logical array B
B = (X-n/4).^2 + (Y-m/2).^2 < m;
% 3d array A
A = zeros(m,n,9);
A(:,:,1:4) = 1;
A(:,:,5:8) = 2;
A(:,:,9) = 3;
% switching of slices (in fauly syntax)
A(B,[1 2 3 ] = A(B,[5 6 7])
A(B,[5 6 7 ] = A(B,[1 2 3])
I need to do this switching of specific values in the 3. dimension for different slices of A and have not been able to come up with an efficient way of doing this. Any help would be greatly appreciated!I have an logical array B and an 3D array A. I wish to extract and manipulate values of A for specific , whereby the values in the first two dimensions are given by B. I was hoping something like
A(B,[1 3 5])
would give me the values specified by B for the first, third and fifth slice of A, but MATLAB doesn’t allow this kind of indexing.
In particular, I would like to switch values given by B for certain (excuse the fauly syntax) akin to
A(B,[1 3 5]) = A(B,[2 4 6])
A minimum example of what I would like to achieve would be:
% coordinate mesh
[X,Y] = meshgrid(1:n,1:m);
% logical array B
B = (X-n/4).^2 + (Y-m/2).^2 < m;
% 3d array A
A = zeros(m,n,9);
A(:,:,1:4) = 1;
A(:,:,5:8) = 2;
A(:,:,9) = 3;
% switching of slices (in fauly syntax)
A(B,[1 2 3 ] = A(B,[5 6 7])
A(B,[5 6 7 ] = A(B,[1 2 3])
I need to do this switching of specific values in the 3. dimension for different slices of A and have not been able to come up with an efficient way of doing this. Any help would be greatly appreciated! I have an logical array B and an 3D array A. I wish to extract and manipulate values of A for specific , whereby the values in the first two dimensions are given by B. I was hoping something like
A(B,[1 3 5])
would give me the values specified by B for the first, third and fifth slice of A, but MATLAB doesn’t allow this kind of indexing.
In particular, I would like to switch values given by B for certain (excuse the fauly syntax) akin to
A(B,[1 3 5]) = A(B,[2 4 6])
A minimum example of what I would like to achieve would be:
% coordinate mesh
[X,Y] = meshgrid(1:n,1:m);
% logical array B
B = (X-n/4).^2 + (Y-m/2).^2 < m;
% 3d array A
A = zeros(m,n,9);
A(:,:,1:4) = 1;
A(:,:,5:8) = 2;
A(:,:,9) = 3;
% switching of slices (in fauly syntax)
A(B,[1 2 3 ] = A(B,[5 6 7])
A(B,[5 6 7 ] = A(B,[1 2 3])
I need to do this switching of specific values in the 3. dimension for different slices of A and have not been able to come up with an efficient way of doing this. Any help would be greatly appreciated! 3d, matrix array, indexing, index, sub2ind MATLAB Answers — New Questions
Solving with ode45 with a solution dependant variable in the ode
Hi,
Let’s say I want to solve :
with , with all following the same ode as y(z).
I can theoretically solve each ode with RK4 at step z+dz and then calculate N(z+dz). But how do I do it using the already implemented RK4 function implemented in Matlab? Would something like this work or is there a way better solution?
while(z<zLim)%%This is just an idea of the algorithm I would use
zspan=[0 dz];%Solving the ODE for a very small zspan
if(z~=0)
y0=y(length(y));
else
y0=0;
end
[z,y] = ode45(@(z,y) N*y, zspan, y0);
%Calculate c(z),g(z),….
%Calculate N at step dz
z=z+dz;
end
ThanksHi,
Let’s say I want to solve :
with , with all following the same ode as y(z).
I can theoretically solve each ode with RK4 at step z+dz and then calculate N(z+dz). But how do I do it using the already implemented RK4 function implemented in Matlab? Would something like this work or is there a way better solution?
while(z<zLim)%%This is just an idea of the algorithm I would use
zspan=[0 dz];%Solving the ODE for a very small zspan
if(z~=0)
y0=y(length(y));
else
y0=0;
end
[z,y] = ode45(@(z,y) N*y, zspan, y0);
%Calculate c(z),g(z),….
%Calculate N at step dz
z=z+dz;
end
Thanks Hi,
Let’s say I want to solve :
with , with all following the same ode as y(z).
I can theoretically solve each ode with RK4 at step z+dz and then calculate N(z+dz). But how do I do it using the already implemented RK4 function implemented in Matlab? Would something like this work or is there a way better solution?
while(z<zLim)%%This is just an idea of the algorithm I would use
zspan=[0 dz];%Solving the ODE for a very small zspan
if(z~=0)
y0=y(length(y));
else
y0=0;
end
[z,y] = ode45(@(z,y) N*y, zspan, y0);
%Calculate c(z),g(z),….
%Calculate N at step dz
z=z+dz;
end
Thanks ode45, ode MATLAB Answers — New Questions
How to use fitnlm
Hello I am trying to fit acurve to my data but I don’t know where to begin or what to do? Any help will be appretiated!
This is the graph and code of my data. I have attached the excel file of my data.
A=xlsread(‘Plague_data.xlsx’);
t=A(:,12);
c=A(:,13);
figure (1)
Number.of.cases=plot(t,c,’.’,’color’,’b’)Hello I am trying to fit acurve to my data but I don’t know where to begin or what to do? Any help will be appretiated!
This is the graph and code of my data. I have attached the excel file of my data.
A=xlsread(‘Plague_data.xlsx’);
t=A(:,12);
c=A(:,13);
figure (1)
Number.of.cases=plot(t,c,’.’,’color’,’b’) Hello I am trying to fit acurve to my data but I don’t know where to begin or what to do? Any help will be appretiated!
This is the graph and code of my data. I have attached the excel file of my data.
A=xlsread(‘Plague_data.xlsx’);
t=A(:,12);
c=A(:,13);
figure (1)
Number.of.cases=plot(t,c,’.’,’color’,’b’) nonlinear fit, nonlinear regression, covid-19, covid19 MATLAB Answers — New Questions
Help me generate better spectrogram data using Matlab?
Hi everyone
I am trying to generate spectrograms for .mat EEG files to show the breakdown of frequencies over time. I have got a series of spectrograms that look like this but I am not sure how to alter the code so they are more useful. My code currently is this:
% Set the directory containing .mat files
dataDir = ‘C:UsersclloyDownloadsspectrogram_data_to_use’;
% Get a list of all .mat files in the directory
matFiles = dir(fullfile(dataDir, ‘*.mat’));
% Electrode information (modify as per your electrode configuration)
electrodes = 1:32; % Assuming electrodes are labeled from 1 to 32
% Loop through each file and generate spectrograms for each electrode
for k = 1:length(matFiles)
% Load the .mat file
matFilePath = fullfile(dataDir, matFiles(k).name);
dataStruct = load(matFilePath);
% Extract the Clean_data variable
if isfield(dataStruct, ‘Clean_data’)
Clean_data = dataStruct.Clean_data;
% Sampling frequency (Hz)
fs = 128; % Sampling rate is 128 Hz
% Size of Clean_data
[numElectrodes, numSamples] = size(Clean_data);
% Loop through each electrode and generate spectrogram
for elecIdx = 1:numElectrodes
% Get data for current electrode
electrodeData = Clean_data(elecIdx, :);
% Generate spectrogram
figure;
spectrogram(electrodeData, 256, [], [], fs, ‘yaxis’);
% Add title and labels
title([‘Spectrogram of Electrode ‘, num2str(elecIdx), ‘ – File: ‘, matFiles(k).name]);
xlabel(‘Time (s)’);
ylabel(‘Frequency (Hz)’);
% Customize y-axis labels for electrodes
ax = gca;
ax.YTickLabel = compose(‘%.1f’, ax.YTick);
% Save the figure as an image file
saveas(gcf, fullfile(dataDir, [matFiles(k).name, ‘_electrode_’, num2str(elecIdx), ‘_spectrogram.png’]));
% Close the figure to avoid excessive memory usage
close(gcf);
end
else
warning(‘File %s does not contain the variable "Clean_data". Skipping…’, matFiles(k).name);
continue;
end
end
Please let me know if theres anything I can do to alter it and make the spectrograms better!Hi everyone
I am trying to generate spectrograms for .mat EEG files to show the breakdown of frequencies over time. I have got a series of spectrograms that look like this but I am not sure how to alter the code so they are more useful. My code currently is this:
% Set the directory containing .mat files
dataDir = ‘C:UsersclloyDownloadsspectrogram_data_to_use’;
% Get a list of all .mat files in the directory
matFiles = dir(fullfile(dataDir, ‘*.mat’));
% Electrode information (modify as per your electrode configuration)
electrodes = 1:32; % Assuming electrodes are labeled from 1 to 32
% Loop through each file and generate spectrograms for each electrode
for k = 1:length(matFiles)
% Load the .mat file
matFilePath = fullfile(dataDir, matFiles(k).name);
dataStruct = load(matFilePath);
% Extract the Clean_data variable
if isfield(dataStruct, ‘Clean_data’)
Clean_data = dataStruct.Clean_data;
% Sampling frequency (Hz)
fs = 128; % Sampling rate is 128 Hz
% Size of Clean_data
[numElectrodes, numSamples] = size(Clean_data);
% Loop through each electrode and generate spectrogram
for elecIdx = 1:numElectrodes
% Get data for current electrode
electrodeData = Clean_data(elecIdx, :);
% Generate spectrogram
figure;
spectrogram(electrodeData, 256, [], [], fs, ‘yaxis’);
% Add title and labels
title([‘Spectrogram of Electrode ‘, num2str(elecIdx), ‘ – File: ‘, matFiles(k).name]);
xlabel(‘Time (s)’);
ylabel(‘Frequency (Hz)’);
% Customize y-axis labels for electrodes
ax = gca;
ax.YTickLabel = compose(‘%.1f’, ax.YTick);
% Save the figure as an image file
saveas(gcf, fullfile(dataDir, [matFiles(k).name, ‘_electrode_’, num2str(elecIdx), ‘_spectrogram.png’]));
% Close the figure to avoid excessive memory usage
close(gcf);
end
else
warning(‘File %s does not contain the variable "Clean_data". Skipping…’, matFiles(k).name);
continue;
end
end
Please let me know if theres anything I can do to alter it and make the spectrograms better! Hi everyone
I am trying to generate spectrograms for .mat EEG files to show the breakdown of frequencies over time. I have got a series of spectrograms that look like this but I am not sure how to alter the code so they are more useful. My code currently is this:
% Set the directory containing .mat files
dataDir = ‘C:UsersclloyDownloadsspectrogram_data_to_use’;
% Get a list of all .mat files in the directory
matFiles = dir(fullfile(dataDir, ‘*.mat’));
% Electrode information (modify as per your electrode configuration)
electrodes = 1:32; % Assuming electrodes are labeled from 1 to 32
% Loop through each file and generate spectrograms for each electrode
for k = 1:length(matFiles)
% Load the .mat file
matFilePath = fullfile(dataDir, matFiles(k).name);
dataStruct = load(matFilePath);
% Extract the Clean_data variable
if isfield(dataStruct, ‘Clean_data’)
Clean_data = dataStruct.Clean_data;
% Sampling frequency (Hz)
fs = 128; % Sampling rate is 128 Hz
% Size of Clean_data
[numElectrodes, numSamples] = size(Clean_data);
% Loop through each electrode and generate spectrogram
for elecIdx = 1:numElectrodes
% Get data for current electrode
electrodeData = Clean_data(elecIdx, :);
% Generate spectrogram
figure;
spectrogram(electrodeData, 256, [], [], fs, ‘yaxis’);
% Add title and labels
title([‘Spectrogram of Electrode ‘, num2str(elecIdx), ‘ – File: ‘, matFiles(k).name]);
xlabel(‘Time (s)’);
ylabel(‘Frequency (Hz)’);
% Customize y-axis labels for electrodes
ax = gca;
ax.YTickLabel = compose(‘%.1f’, ax.YTick);
% Save the figure as an image file
saveas(gcf, fullfile(dataDir, [matFiles(k).name, ‘_electrode_’, num2str(elecIdx), ‘_spectrogram.png’]));
% Close the figure to avoid excessive memory usage
close(gcf);
end
else
warning(‘File %s does not contain the variable "Clean_data". Skipping…’, matFiles(k).name);
continue;
end
end
Please let me know if theres anything I can do to alter it and make the spectrograms better! spectrograms eeg MATLAB Answers — New Questions
HOW DO I MAKE A FUNCTION THAT CHANGES MY FORCE VS. TIME GRAPH TO FORCE VS. POSITION
Hello, I plotted a graph that gave me force vs. position but I need to make it so it gives me force vs. time but I am not sure on how to convert the time. I am given the sample rate which is 20 samples per second and the crosspeed is 15 inches per minute. but if the sample rate fluctuates, how can I obtain the actual distance ? I hope this makes sense, anything helps
files = [
"Test 22 Sensor.txt" "Test 22 Instron.TXT";
%%"Test 17 Sensor.txt" "Test 17 Instron.TXT";
];
Valueshift=12.53-6.18;
% value that is adjusted in case the final cross value is not
% correct and the graphs do not match up
SampleRate=10;
% sample rate of the Instron machine
NamedGraphTitle=["2022.03.16 Test 22, .012in Uncoated, 7000lbs, 15in per min"];
TimeendX=20;
%the last value for the axis
% Import the data
for k=1:size(files)
TestSensor = readtable(files(k,1),opts);
TestInstron = readtable(files(k,2),opts_instron);
% transfer the table data to the array
sensor_data = table2array(TestSensor(2:height(TestSensor)-2,:));
instron_data = table2array(TestInstron(2:height(TestInstron),:));
% Plotting
%Pulling Force
plot(sensor_data_shift.*mask,sensor_data(:,3).*mask,’LineWidth’,1.5,’Color’,[0.267, 0.447, 0.769])% RGB Blue 68, 114, 196
hold on
%Normal Force
plot(instron_data(:,1)/SampleRate+gap,instron_data(:,3),’LineWidth’,1.5,’Color’,[0.929, 0.490, 0.192])% RGB Orange 237, 125, 49
%Friction
% RGB Grey 165, 165, 165
legend(‘Normal Force’,’Pulling Force’,’Friction*1000′)
grid on
title(NamedGraphTitle)
xlabel(‘Time(s)’)
ylabel(‘Force (lbs)’)
axis([16.5,TimeendX,0,7500])
hold off
endHello, I plotted a graph that gave me force vs. position but I need to make it so it gives me force vs. time but I am not sure on how to convert the time. I am given the sample rate which is 20 samples per second and the crosspeed is 15 inches per minute. but if the sample rate fluctuates, how can I obtain the actual distance ? I hope this makes sense, anything helps
files = [
"Test 22 Sensor.txt" "Test 22 Instron.TXT";
%%"Test 17 Sensor.txt" "Test 17 Instron.TXT";
];
Valueshift=12.53-6.18;
% value that is adjusted in case the final cross value is not
% correct and the graphs do not match up
SampleRate=10;
% sample rate of the Instron machine
NamedGraphTitle=["2022.03.16 Test 22, .012in Uncoated, 7000lbs, 15in per min"];
TimeendX=20;
%the last value for the axis
% Import the data
for k=1:size(files)
TestSensor = readtable(files(k,1),opts);
TestInstron = readtable(files(k,2),opts_instron);
% transfer the table data to the array
sensor_data = table2array(TestSensor(2:height(TestSensor)-2,:));
instron_data = table2array(TestInstron(2:height(TestInstron),:));
% Plotting
%Pulling Force
plot(sensor_data_shift.*mask,sensor_data(:,3).*mask,’LineWidth’,1.5,’Color’,[0.267, 0.447, 0.769])% RGB Blue 68, 114, 196
hold on
%Normal Force
plot(instron_data(:,1)/SampleRate+gap,instron_data(:,3),’LineWidth’,1.5,’Color’,[0.929, 0.490, 0.192])% RGB Orange 237, 125, 49
%Friction
% RGB Grey 165, 165, 165
legend(‘Normal Force’,’Pulling Force’,’Friction*1000′)
grid on
title(NamedGraphTitle)
xlabel(‘Time(s)’)
ylabel(‘Force (lbs)’)
axis([16.5,TimeendX,0,7500])
hold off
end Hello, I plotted a graph that gave me force vs. position but I need to make it so it gives me force vs. time but I am not sure on how to convert the time. I am given the sample rate which is 20 samples per second and the crosspeed is 15 inches per minute. but if the sample rate fluctuates, how can I obtain the actual distance ? I hope this makes sense, anything helps
files = [
"Test 22 Sensor.txt" "Test 22 Instron.TXT";
%%"Test 17 Sensor.txt" "Test 17 Instron.TXT";
];
Valueshift=12.53-6.18;
% value that is adjusted in case the final cross value is not
% correct and the graphs do not match up
SampleRate=10;
% sample rate of the Instron machine
NamedGraphTitle=["2022.03.16 Test 22, .012in Uncoated, 7000lbs, 15in per min"];
TimeendX=20;
%the last value for the axis
% Import the data
for k=1:size(files)
TestSensor = readtable(files(k,1),opts);
TestInstron = readtable(files(k,2),opts_instron);
% transfer the table data to the array
sensor_data = table2array(TestSensor(2:height(TestSensor)-2,:));
instron_data = table2array(TestInstron(2:height(TestInstron),:));
% Plotting
%Pulling Force
plot(sensor_data_shift.*mask,sensor_data(:,3).*mask,’LineWidth’,1.5,’Color’,[0.267, 0.447, 0.769])% RGB Blue 68, 114, 196
hold on
%Normal Force
plot(instron_data(:,1)/SampleRate+gap,instron_data(:,3),’LineWidth’,1.5,’Color’,[0.929, 0.490, 0.192])% RGB Orange 237, 125, 49
%Friction
% RGB Grey 165, 165, 165
legend(‘Normal Force’,’Pulling Force’,’Friction*1000′)
grid on
title(NamedGraphTitle)
xlabel(‘Time(s)’)
ylabel(‘Force (lbs)’)
axis([16.5,TimeendX,0,7500])
hold off
end plotting, convert, speed, time MATLAB Answers — New Questions
I want to segment an apple fruit image and i’m using histogram’s method but when i’m using the function: n=hist(reshape(double(rgb(:,:,i)),[480*640 1]),0.5:256); i have this error: To RESHAPE the number of elements must not change.
% load image (colorful fabric acquired with frame grabber and camera)
rgb = imread(‘7.png’); % Matrox frame grabber + Pulnix camera
imshow(rgb)
% explore color content using image viewer
imshow(rgb)
% smooth image (reduce noise/color variation)
rgb = imfilter(rgb,ones(3,3)/9);
imshow(rgb)
% view image and RGB layers (nonuniform illumination)
figure(1), set(1,’position’,[99 79 826 589])
subplot(2,2,1), subimage(rgb), title(‘fabric image’), axis off
subplot(2,2,2), map=gray(256); map(:,2:3)=0; subimage(rgb(:,:,1),map), title(‘red layer’), axis off
subplot(2,2,3), map=gray(256); map(:,[1 3])=0; subimage(rgb(:,:,2),map), title(‘green layer’), axis off
subplot(2,2,4), map=gray(256); map(:,1:2)=0; subimage(rgb(:,:,3),map), title(‘blue layer’), axis off
% RGB histograms (poor separability)
figure(1), set(1,’position’,[452 68 560 420])
figure(2), set(2,’position’,[16 269 560 420])
c=’rgb’;
for i=1:3
n=hist(reshape(double(rgb(:,:,i)),[480*640 1]),0.5:256);
line(0:255,n,’color’,c(i))
end% load image (colorful fabric acquired with frame grabber and camera)
rgb = imread(‘7.png’); % Matrox frame grabber + Pulnix camera
imshow(rgb)
% explore color content using image viewer
imshow(rgb)
% smooth image (reduce noise/color variation)
rgb = imfilter(rgb,ones(3,3)/9);
imshow(rgb)
% view image and RGB layers (nonuniform illumination)
figure(1), set(1,’position’,[99 79 826 589])
subplot(2,2,1), subimage(rgb), title(‘fabric image’), axis off
subplot(2,2,2), map=gray(256); map(:,2:3)=0; subimage(rgb(:,:,1),map), title(‘red layer’), axis off
subplot(2,2,3), map=gray(256); map(:,[1 3])=0; subimage(rgb(:,:,2),map), title(‘green layer’), axis off
subplot(2,2,4), map=gray(256); map(:,1:2)=0; subimage(rgb(:,:,3),map), title(‘blue layer’), axis off
% RGB histograms (poor separability)
figure(1), set(1,’position’,[452 68 560 420])
figure(2), set(2,’position’,[16 269 560 420])
c=’rgb’;
for i=1:3
n=hist(reshape(double(rgb(:,:,i)),[480*640 1]),0.5:256);
line(0:255,n,’color’,c(i))
end % load image (colorful fabric acquired with frame grabber and camera)
rgb = imread(‘7.png’); % Matrox frame grabber + Pulnix camera
imshow(rgb)
% explore color content using image viewer
imshow(rgb)
% smooth image (reduce noise/color variation)
rgb = imfilter(rgb,ones(3,3)/9);
imshow(rgb)
% view image and RGB layers (nonuniform illumination)
figure(1), set(1,’position’,[99 79 826 589])
subplot(2,2,1), subimage(rgb), title(‘fabric image’), axis off
subplot(2,2,2), map=gray(256); map(:,2:3)=0; subimage(rgb(:,:,1),map), title(‘red layer’), axis off
subplot(2,2,3), map=gray(256); map(:,[1 3])=0; subimage(rgb(:,:,2),map), title(‘green layer’), axis off
subplot(2,2,4), map=gray(256); map(:,1:2)=0; subimage(rgb(:,:,3),map), title(‘blue layer’), axis off
% RGB histograms (poor separability)
figure(1), set(1,’position’,[452 68 560 420])
figure(2), set(2,’position’,[16 269 560 420])
c=’rgb’;
for i=1:3
n=hist(reshape(double(rgb(:,:,i)),[480*640 1]),0.5:256);
line(0:255,n,’color’,c(i))
end color image segmentation for apple fruit MATLAB Answers — New Questions
parallel timers not executing as expected
I am trying to run two parallel timers. Below is a minimal example.
I would expect (or wish) that timerCallback2 is executed when timerCallback1 is in pause mode. But the function seems to be blocking. I also tried to add some drawnow calls.
Is there any way to execute multiple timer callbacks while another is still running, or is this intended behavior? Does MATLAB not process the event queue while another event is still running? Or are there different event queues for timer events and GUI events?
Thank you for your help!
timer1 = timer(Name="timer1", ExecutionMode="fixedSpacing", BusyMode="queue", TimerFcn=@timerCallback1, TasksToExecute=3, Period=1);
start(timer1)
timer2 = timer(Name="timer2", ExecutionMode="fixedSpacing", BusyMode="queue", TimerFcn=@timerCallback2, TasksToExecute=30, Period=0.1);
start(timer2)
function timerCallback1(~,~)
disp("start T1…")
pause(2)
disp("end T1…")
end
function timerCallback2(~, ~)
disp(" start T2…")
pause(0.05)
disp(" end T2…")
end
%% Output is:
% start T1…
% end T1…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T1…
% end T1…
% start T2…
% end T2…
% start T2…
% and so on….I am trying to run two parallel timers. Below is a minimal example.
I would expect (or wish) that timerCallback2 is executed when timerCallback1 is in pause mode. But the function seems to be blocking. I also tried to add some drawnow calls.
Is there any way to execute multiple timer callbacks while another is still running, or is this intended behavior? Does MATLAB not process the event queue while another event is still running? Or are there different event queues for timer events and GUI events?
Thank you for your help!
timer1 = timer(Name="timer1", ExecutionMode="fixedSpacing", BusyMode="queue", TimerFcn=@timerCallback1, TasksToExecute=3, Period=1);
start(timer1)
timer2 = timer(Name="timer2", ExecutionMode="fixedSpacing", BusyMode="queue", TimerFcn=@timerCallback2, TasksToExecute=30, Period=0.1);
start(timer2)
function timerCallback1(~,~)
disp("start T1…")
pause(2)
disp("end T1…")
end
function timerCallback2(~, ~)
disp(" start T2…")
pause(0.05)
disp(" end T2…")
end
%% Output is:
% start T1…
% end T1…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T1…
% end T1…
% start T2…
% end T2…
% start T2…
% and so on…. I am trying to run two parallel timers. Below is a minimal example.
I would expect (or wish) that timerCallback2 is executed when timerCallback1 is in pause mode. But the function seems to be blocking. I also tried to add some drawnow calls.
Is there any way to execute multiple timer callbacks while another is still running, or is this intended behavior? Does MATLAB not process the event queue while another event is still running? Or are there different event queues for timer events and GUI events?
Thank you for your help!
timer1 = timer(Name="timer1", ExecutionMode="fixedSpacing", BusyMode="queue", TimerFcn=@timerCallback1, TasksToExecute=3, Period=1);
start(timer1)
timer2 = timer(Name="timer2", ExecutionMode="fixedSpacing", BusyMode="queue", TimerFcn=@timerCallback2, TasksToExecute=30, Period=0.1);
start(timer2)
function timerCallback1(~,~)
disp("start T1…")
pause(2)
disp("end T1…")
end
function timerCallback2(~, ~)
disp(" start T2…")
pause(0.05)
disp(" end T2…")
end
%% Output is:
% start T1…
% end T1…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T2…
% end T2…
% start T1…
% end T1…
% start T2…
% end T2…
% start T2…
% and so on…. timer, event, callback MATLAB Answers — New Questions
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