Tag Archives: matlab
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
readtable struggling to interpret spreadsheet as numbers
Hi folks,
I’m trying to use the readtable function to interpret a spreadsheet "Alberta.csv". I’ve tried using detectImportOpts, sadly the variables are arranged in rows and readtable seems to want to detect them as columns.
The next attempt was as follows:
seriesAL = table2dataset(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
or
seriesAL = table2array(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
then if I try to complete an operation:
rgdp_AL = log(0.001 .* seriesAL{:,40})
Matlab tells me I’m using too many input arguments… If I enter:
seriesAL(:,40), I’m failing to get numbers, yet seriesAL{} doesn’t want to provide the full column of values!
I’m getting very confused by the way Matlab uses tables, cells, structs, etc… Can anyone help me get numbers?Hi folks,
I’m trying to use the readtable function to interpret a spreadsheet "Alberta.csv". I’ve tried using detectImportOpts, sadly the variables are arranged in rows and readtable seems to want to detect them as columns.
The next attempt was as follows:
seriesAL = table2dataset(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
or
seriesAL = table2array(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
then if I try to complete an operation:
rgdp_AL = log(0.001 .* seriesAL{:,40})
Matlab tells me I’m using too many input arguments… If I enter:
seriesAL(:,40), I’m failing to get numbers, yet seriesAL{} doesn’t want to provide the full column of values!
I’m getting very confused by the way Matlab uses tables, cells, structs, etc… Can anyone help me get numbers? Hi folks,
I’m trying to use the readtable function to interpret a spreadsheet "Alberta.csv". I’ve tried using detectImportOpts, sadly the variables are arranged in rows and readtable seems to want to detect them as columns.
The next attempt was as follows:
seriesAL = table2dataset(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
or
seriesAL = table2array(rows2vars(readtable("Alberta.csv", ReadRowNames=1, MissingRule="omitrow")));
then if I try to complete an operation:
rgdp_AL = log(0.001 .* seriesAL{:,40})
Matlab tells me I’m using too many input arguments… If I enter:
seriesAL(:,40), I’m failing to get numbers, yet seriesAL{} doesn’t want to provide the full column of values!
I’m getting very confused by the way Matlab uses tables, cells, structs, etc… Can anyone help me get numbers? readtable, struct MATLAB Answers — New Questions
find best fit ellipse to a set of data points
I’m new to matlab so I don’t know how to use it that well yet; however, I have to find the best fit ellipse for a set of data points I have for a project and I’ve been struggling to find a code that would help me do this. Does anyone know what code I could use? Thanks for your help!I’m new to matlab so I don’t know how to use it that well yet; however, I have to find the best fit ellipse for a set of data points I have for a project and I’ve been struggling to find a code that would help me do this. Does anyone know what code I could use? Thanks for your help! I’m new to matlab so I don’t know how to use it that well yet; however, I have to find the best fit ellipse for a set of data points I have for a project and I’ve been struggling to find a code that would help me do this. Does anyone know what code I could use? Thanks for your help! best fit, ellipse, curve fitting MATLAB Answers — New Questions
Multilayer Perceptron with More Than One Output and Data Interpretation?
I haven’t used Matlab’s ML or deep learning toolbox since maybe 2022. In the last year, it seems like MathWorks intentionally made the ML portion of Matlab unusable. I’m hoping someone here can help me out because rolling back my matlab two years will make a lot of my recent work unstable. I’ve done my best to document my process here. Error messages are given in italics for ease of reading.
I have some data that is represented by four doubles that are normalzied to between 0 and 1. I would like to use these four doubles to predict two doubles that are also between 0 and 1. I would like to make a multilayer perceptron that will take in the four values and spit out the two values. However, createMLPNetwork doesn’t appear to support multiple outputs – at least, the documentation for it doesn’t explain how to do so. So I have tried to make a MLP from scratch using the following code:
%% Prep NN architecture
layers = [
inputLayer([4, 1], "CU", name="in")
flattenLayer
fullyConnectedLayer(20, name="fc1")
reluLayer
fullyConnectedLayerB(16, name="fc2")
reluLayer
fullyConnectedLayer(12, name="fc3")
reluLayer
fullyConnectedLayer(numel(data{1,1}), name="output")
softmaxLayer
];
net = dlnetwork(layers);
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Attempting to run this gives me the following results:
Error using trainnet (line 46)
Error forming mini-batch for network input "in". Data interpreted with format "CU". To specify a different format, use the InputDataFormats option.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Caused by:
The data format must have a batch dimension.
I tried to get around using the generic inputLayer function by using the more specific functions like featureInputLayer but replacing the inputLayer with a featureInputLayer throws the following:
Error using trainnet (line 46)
Number of observations in predictors (4) and targets (2) must match. Check that the data and network are consistent.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
So that won’t work because I only have two output data points. The same happened when I tried imageInputLayer. Then I tried replacing "CU" with other values – the following error is for "BU" but the other errors are the same – but got the following:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 104)
net = dlnetwork(layers);
Caused by:
Layer ‘fc1’: Invalid input data for fully connected layer. The input data must have exactly one channel dimension.
So then I tried flattening the output and got the following error:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 105)
net = dlnetwork(layers);
Caused by:
Layer ‘flatten’: Invalid input data. Layer expects data with a channel dimension, but received input data with format "BU".
I’m really not sure what to do here. I have no idea why MathWorks would make this so much more difficult to use and give so much less, and more opaque, documentation. If anyone has any ideas on how to make this work, I’d be happy to hear them. In the meantime, I’m going to take another crack at the createMLPNetwork function and hope that when MathWorks says "a black-box continuous-time or discrete-time neural state-space model with identifiable (estimable) network weights and bias," by "states" they mean "outputs."I haven’t used Matlab’s ML or deep learning toolbox since maybe 2022. In the last year, it seems like MathWorks intentionally made the ML portion of Matlab unusable. I’m hoping someone here can help me out because rolling back my matlab two years will make a lot of my recent work unstable. I’ve done my best to document my process here. Error messages are given in italics for ease of reading.
I have some data that is represented by four doubles that are normalzied to between 0 and 1. I would like to use these four doubles to predict two doubles that are also between 0 and 1. I would like to make a multilayer perceptron that will take in the four values and spit out the two values. However, createMLPNetwork doesn’t appear to support multiple outputs – at least, the documentation for it doesn’t explain how to do so. So I have tried to make a MLP from scratch using the following code:
%% Prep NN architecture
layers = [
inputLayer([4, 1], "CU", name="in")
flattenLayer
fullyConnectedLayer(20, name="fc1")
reluLayer
fullyConnectedLayerB(16, name="fc2")
reluLayer
fullyConnectedLayer(12, name="fc3")
reluLayer
fullyConnectedLayer(numel(data{1,1}), name="output")
softmaxLayer
];
net = dlnetwork(layers);
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Attempting to run this gives me the following results:
Error using trainnet (line 46)
Error forming mini-batch for network input "in". Data interpreted with format "CU". To specify a different format, use the InputDataFormats option.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Caused by:
The data format must have a batch dimension.
I tried to get around using the generic inputLayer function by using the more specific functions like featureInputLayer but replacing the inputLayer with a featureInputLayer throws the following:
Error using trainnet (line 46)
Number of observations in predictors (4) and targets (2) must match. Check that the data and network are consistent.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
So that won’t work because I only have two output data points. The same happened when I tried imageInputLayer. Then I tried replacing "CU" with other values – the following error is for "BU" but the other errors are the same – but got the following:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 104)
net = dlnetwork(layers);
Caused by:
Layer ‘fc1’: Invalid input data for fully connected layer. The input data must have exactly one channel dimension.
So then I tried flattening the output and got the following error:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 105)
net = dlnetwork(layers);
Caused by:
Layer ‘flatten’: Invalid input data. Layer expects data with a channel dimension, but received input data with format "BU".
I’m really not sure what to do here. I have no idea why MathWorks would make this so much more difficult to use and give so much less, and more opaque, documentation. If anyone has any ideas on how to make this work, I’d be happy to hear them. In the meantime, I’m going to take another crack at the createMLPNetwork function and hope that when MathWorks says "a black-box continuous-time or discrete-time neural state-space model with identifiable (estimable) network weights and bias," by "states" they mean "outputs." I haven’t used Matlab’s ML or deep learning toolbox since maybe 2022. In the last year, it seems like MathWorks intentionally made the ML portion of Matlab unusable. I’m hoping someone here can help me out because rolling back my matlab two years will make a lot of my recent work unstable. I’ve done my best to document my process here. Error messages are given in italics for ease of reading.
I have some data that is represented by four doubles that are normalzied to between 0 and 1. I would like to use these four doubles to predict two doubles that are also between 0 and 1. I would like to make a multilayer perceptron that will take in the four values and spit out the two values. However, createMLPNetwork doesn’t appear to support multiple outputs – at least, the documentation for it doesn’t explain how to do so. So I have tried to make a MLP from scratch using the following code:
%% Prep NN architecture
layers = [
inputLayer([4, 1], "CU", name="in")
flattenLayer
fullyConnectedLayer(20, name="fc1")
reluLayer
fullyConnectedLayerB(16, name="fc2")
reluLayer
fullyConnectedLayer(12, name="fc3")
reluLayer
fullyConnectedLayer(numel(data{1,1}), name="output")
softmaxLayer
];
net = dlnetwork(layers);
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Attempting to run this gives me the following results:
Error using trainnet (line 46)
Error forming mini-batch for network input "in". Data interpreted with format "CU". To specify a different format, use the InputDataFormats option.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
Caused by:
The data format must have a batch dimension.
I tried to get around using the generic inputLayer function by using the more specific functions like featureInputLayer but replacing the inputLayer with a featureInputLayer throws the following:
Error using trainnet (line 46)
Number of observations in predictors (4) and targets (2) must match. Check that the data and network are consistent.
Error in trainRutileModel (line 107)
[trainedNet, info] = trainnet(train, layers, "mse", opts);
So that won’t work because I only have two output data points. The same happened when I tried imageInputLayer. Then I tried replacing "CU" with other values – the following error is for "BU" but the other errors are the same – but got the following:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 104)
net = dlnetwork(layers);
Caused by:
Layer ‘fc1’: Invalid input data for fully connected layer. The input data must have exactly one channel dimension.
So then I tried flattening the output and got the following error:
Error using dlnetwork/initialize (line 558)
Invalid network.
Error in dlnetwork (line 167)
net = initialize(net, dlX{:});
Error in trainRutileModel (line 105)
net = dlnetwork(layers);
Caused by:
Layer ‘flatten’: Invalid input data. Layer expects data with a channel dimension, but received input data with format "BU".
I’m really not sure what to do here. I have no idea why MathWorks would make this so much more difficult to use and give so much less, and more opaque, documentation. If anyone has any ideas on how to make this work, I’d be happy to hear them. In the meantime, I’m going to take another crack at the createMLPNetwork function and hope that when MathWorks says "a black-box continuous-time or discrete-time neural state-space model with identifiable (estimable) network weights and bias," by "states" they mean "outputs." multilayer perceptron, mlp, neural network, inputlayer MATLAB Answers — New Questions
Determine the indice of real maximum using accumarray function
I’m doing signal analysis on the peaks and valleys of a sinusoidal signal. Using accumarray has been quite effective at determining the extrema, but I’m seriously struggling with what should be a simple part of my implementation. Currently the returned peakLoc values are not integer timesteps, but a decimal average of all the timesteps that are considered part of the peak. The only new functionality I need is to get the real integer timestep for the highest (or lowest) extrema. Whether there is an option for the single accumarray line with @mean or another way, I don’t care. Over the past three days I have been slopping together different nested loops to try to pin down the behavior I want and I’m sure there’s got to be a simple way to accomplish this.
I’m sure there’s a lot of other ways I could improve this code, but I just need it working. I’m not experienced and constantly bang my head against indexing problems (whether mixing up dimension, logical indexing oddities, etc.) and other beginner problems.
function [peakLoc, peakVal] = getExtrema(durThreshold, PEThreshold, gettingMax, PEAverage, timestep)
% Gets passed duration (# of consecutive timesteps above zero) and PE threshold (0).
% Returns the timestep and PE value for all of Maximum or of Minimum extrema.
if gettingMax == true
isPeak = PEAverage > PEThreshold;
else
isPeak = PEAverage < PEThreshold;
end
CC = bwconncomp(isPeak);
peakID = labelmatrix(CC);
peakLabel = unique(peakID);
peakSize = accumarray(peakID(:)+1,1);
peakSize(1) = 0; % set the # of <0 elements to 0
realPeakLabels = peakLabel(peakSize >= durThreshold);
isRealPeak = ismember(peakID,realPeakLabels);
% Now find the max in the real peaks (realPeakLabels?), accumarray will help
peakID(~isRealPeak) = 0;
if gettingMax == true
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@max,NaN);
else
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@min,NaN);
end
%% Get the right peakLoc, not the @mean
% @mean is approximation of the timestep where the real peak value occurs
peakLoc = accumarray(peakID(:)+1,timestep(:),[numel(peakSize) 1],@mean,NaN);
peakLoc = zeros(length(peakLabel),1);
j = 1;
for i = timestep
% Get the right index
if peakID(i) > j
j = peakID(i);
end
if ismember(j, realPeakLabels)
if gettingMax == true
if PEAverage(i) > peakVal(j)
peakLoc(j) = timestep(i);
end
else
if PEAverage(i) < peakVal(j)
peakLoc(j) = timestep(i);
end
end
end
end
peakVal(1) = NaN;
peakLoc(peakLoc == 0) = NaN;
endI’m doing signal analysis on the peaks and valleys of a sinusoidal signal. Using accumarray has been quite effective at determining the extrema, but I’m seriously struggling with what should be a simple part of my implementation. Currently the returned peakLoc values are not integer timesteps, but a decimal average of all the timesteps that are considered part of the peak. The only new functionality I need is to get the real integer timestep for the highest (or lowest) extrema. Whether there is an option for the single accumarray line with @mean or another way, I don’t care. Over the past three days I have been slopping together different nested loops to try to pin down the behavior I want and I’m sure there’s got to be a simple way to accomplish this.
I’m sure there’s a lot of other ways I could improve this code, but I just need it working. I’m not experienced and constantly bang my head against indexing problems (whether mixing up dimension, logical indexing oddities, etc.) and other beginner problems.
function [peakLoc, peakVal] = getExtrema(durThreshold, PEThreshold, gettingMax, PEAverage, timestep)
% Gets passed duration (# of consecutive timesteps above zero) and PE threshold (0).
% Returns the timestep and PE value for all of Maximum or of Minimum extrema.
if gettingMax == true
isPeak = PEAverage > PEThreshold;
else
isPeak = PEAverage < PEThreshold;
end
CC = bwconncomp(isPeak);
peakID = labelmatrix(CC);
peakLabel = unique(peakID);
peakSize = accumarray(peakID(:)+1,1);
peakSize(1) = 0; % set the # of <0 elements to 0
realPeakLabels = peakLabel(peakSize >= durThreshold);
isRealPeak = ismember(peakID,realPeakLabels);
% Now find the max in the real peaks (realPeakLabels?), accumarray will help
peakID(~isRealPeak) = 0;
if gettingMax == true
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@max,NaN);
else
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@min,NaN);
end
%% Get the right peakLoc, not the @mean
% @mean is approximation of the timestep where the real peak value occurs
peakLoc = accumarray(peakID(:)+1,timestep(:),[numel(peakSize) 1],@mean,NaN);
peakLoc = zeros(length(peakLabel),1);
j = 1;
for i = timestep
% Get the right index
if peakID(i) > j
j = peakID(i);
end
if ismember(j, realPeakLabels)
if gettingMax == true
if PEAverage(i) > peakVal(j)
peakLoc(j) = timestep(i);
end
else
if PEAverage(i) < peakVal(j)
peakLoc(j) = timestep(i);
end
end
end
end
peakVal(1) = NaN;
peakLoc(peakLoc == 0) = NaN;
end I’m doing signal analysis on the peaks and valleys of a sinusoidal signal. Using accumarray has been quite effective at determining the extrema, but I’m seriously struggling with what should be a simple part of my implementation. Currently the returned peakLoc values are not integer timesteps, but a decimal average of all the timesteps that are considered part of the peak. The only new functionality I need is to get the real integer timestep for the highest (or lowest) extrema. Whether there is an option for the single accumarray line with @mean or another way, I don’t care. Over the past three days I have been slopping together different nested loops to try to pin down the behavior I want and I’m sure there’s got to be a simple way to accomplish this.
I’m sure there’s a lot of other ways I could improve this code, but I just need it working. I’m not experienced and constantly bang my head against indexing problems (whether mixing up dimension, logical indexing oddities, etc.) and other beginner problems.
function [peakLoc, peakVal] = getExtrema(durThreshold, PEThreshold, gettingMax, PEAverage, timestep)
% Gets passed duration (# of consecutive timesteps above zero) and PE threshold (0).
% Returns the timestep and PE value for all of Maximum or of Minimum extrema.
if gettingMax == true
isPeak = PEAverage > PEThreshold;
else
isPeak = PEAverage < PEThreshold;
end
CC = bwconncomp(isPeak);
peakID = labelmatrix(CC);
peakLabel = unique(peakID);
peakSize = accumarray(peakID(:)+1,1);
peakSize(1) = 0; % set the # of <0 elements to 0
realPeakLabels = peakLabel(peakSize >= durThreshold);
isRealPeak = ismember(peakID,realPeakLabels);
% Now find the max in the real peaks (realPeakLabels?), accumarray will help
peakID(~isRealPeak) = 0;
if gettingMax == true
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@max,NaN);
else
peakVal = accumarray(peakID(:)+1,PEAverage(:),[numel(peakSize) 1],@min,NaN);
end
%% Get the right peakLoc, not the @mean
% @mean is approximation of the timestep where the real peak value occurs
peakLoc = accumarray(peakID(:)+1,timestep(:),[numel(peakSize) 1],@mean,NaN);
peakLoc = zeros(length(peakLabel),1);
j = 1;
for i = timestep
% Get the right index
if peakID(i) > j
j = peakID(i);
end
if ismember(j, realPeakLabels)
if gettingMax == true
if PEAverage(i) > peakVal(j)
peakLoc(j) = timestep(i);
end
else
if PEAverage(i) < peakVal(j)
peakLoc(j) = timestep(i);
end
end
end
end
peakVal(1) = NaN;
peakLoc(peakLoc == 0) = NaN;
end signal processing MATLAB Answers — New Questions
How can I make a power load which uses different power for a day?
I want to make a power load which consumes different power for a day. I have a data that shows how much power was consumed by a building for a day.
So I used Dynamic load block, but I failed to load the data to the block.
How can I make it?I want to make a power load which consumes different power for a day. I have a data that shows how much power was consumed by a building for a day.
So I used Dynamic load block, but I failed to load the data to the block.
How can I make it? I want to make a power load which consumes different power for a day. I have a data that shows how much power was consumed by a building for a day.
So I used Dynamic load block, but I failed to load the data to the block.
How can I make it? load, variable, variable load MATLAB Answers — New Questions