Category: Matlab
Category Archives: Matlab
Create 30 minute bins by reading time stamps
I have a file with time stamps, due to error in the files (gaps in time due to faulty equipment) binning 30 minute sections using the following code creates errors in the actograms produced.
function[Average] = Av_30min(y)
Average = zeros(288,size(y,2));
k = 1;
for l =1:288
Average(l,1) = mean(y(k:k+(round(length(y)/288)-1),1));
k = k+((round(length(y)/288)-1));
end
end
I want to read from say 11:30:00 – 12:00:00 and average this bin and so on and so forth. Can anyone help?
ThanksI have a file with time stamps, due to error in the files (gaps in time due to faulty equipment) binning 30 minute sections using the following code creates errors in the actograms produced.
function[Average] = Av_30min(y)
Average = zeros(288,size(y,2));
k = 1;
for l =1:288
Average(l,1) = mean(y(k:k+(round(length(y)/288)-1),1));
k = k+((round(length(y)/288)-1));
end
end
I want to read from say 11:30:00 – 12:00:00 and average this bin and so on and so forth. Can anyone help?
Thanks I have a file with time stamps, due to error in the files (gaps in time due to faulty equipment) binning 30 minute sections using the following code creates errors in the actograms produced.
function[Average] = Av_30min(y)
Average = zeros(288,size(y,2));
k = 1;
for l =1:288
Average(l,1) = mean(y(k:k+(round(length(y)/288)-1),1));
k = k+((round(length(y)/288)-1));
end
end
I want to read from say 11:30:00 – 12:00:00 and average this bin and so on and so forth. Can anyone help?
Thanks time MATLAB Answers — New Questions
Error with compiled app designer app using report generator toolbox.
Big picture, I am using app designer to write data processing apps for the laboratory where I work. The apps use base Matlab (v 2022b) and report generator to create data sheets for our reports. I am attempting to use Matlab Compiler to compile these into standalone desktop apps that I can distribute to my group. The apps run fine in the Matlab environment, but all encounter an error when trying to create a report sheet in the compiled version.
An excerpt from the code is shown below. The error occurs at some point during the execution of this code in the compiled app. As a side question, is it possible to see an error log in the compiled app (similar to how errors would be shown in the command window while working in the Matlab environment)?
I suspect that the error is occuring when the program tries to find the template path in the compiled version or when the document command is executed. All the template files are bundled with the compiled app installer.
makeDOMCompilable();
import mlreportgen.report.*
import mlreportgen.dom.*
%user prompt to enter name of generated report file
prompt = {‘Enter File Name:’};
dlgtitle = ‘Input’;
dims = [1 35];
definput = {”};
Filename = inputdlg(prompt,dlgtitle,dims,definput);
Filename = string(Filename);
%Locate template file and generate full path
whoAmI = mfilename(‘fullpath’);
[fullpath, ~, ~] = fileparts(whoAmI);
template = fullfile(fullpath,’Templates’,’SwellC_Template_New.dotx’);
% I suspect this is the line where the code is encountering an
% error.
D = Document(Filename,’docx’, template);
%There is more code in the block below to finish populating the
%template, but this is the general format.
open(D)
moveToNextHole(D);
append(D, app.ProjectEditField.Value);
moveToNextHole(D);
append(D, app.FeatureEditField.Value);
moveToNextHole(D);
append(D, app.IndexEditField.Value);
moveToNextHole(D);
append(D, app.BoreholeEditField.Value);
moveToNextHole(D);
%…
close(D);
f = msgbox("Report Generation Complete");Big picture, I am using app designer to write data processing apps for the laboratory where I work. The apps use base Matlab (v 2022b) and report generator to create data sheets for our reports. I am attempting to use Matlab Compiler to compile these into standalone desktop apps that I can distribute to my group. The apps run fine in the Matlab environment, but all encounter an error when trying to create a report sheet in the compiled version.
An excerpt from the code is shown below. The error occurs at some point during the execution of this code in the compiled app. As a side question, is it possible to see an error log in the compiled app (similar to how errors would be shown in the command window while working in the Matlab environment)?
I suspect that the error is occuring when the program tries to find the template path in the compiled version or when the document command is executed. All the template files are bundled with the compiled app installer.
makeDOMCompilable();
import mlreportgen.report.*
import mlreportgen.dom.*
%user prompt to enter name of generated report file
prompt = {‘Enter File Name:’};
dlgtitle = ‘Input’;
dims = [1 35];
definput = {”};
Filename = inputdlg(prompt,dlgtitle,dims,definput);
Filename = string(Filename);
%Locate template file and generate full path
whoAmI = mfilename(‘fullpath’);
[fullpath, ~, ~] = fileparts(whoAmI);
template = fullfile(fullpath,’Templates’,’SwellC_Template_New.dotx’);
% I suspect this is the line where the code is encountering an
% error.
D = Document(Filename,’docx’, template);
%There is more code in the block below to finish populating the
%template, but this is the general format.
open(D)
moveToNextHole(D);
append(D, app.ProjectEditField.Value);
moveToNextHole(D);
append(D, app.FeatureEditField.Value);
moveToNextHole(D);
append(D, app.IndexEditField.Value);
moveToNextHole(D);
append(D, app.BoreholeEditField.Value);
moveToNextHole(D);
%…
close(D);
f = msgbox("Report Generation Complete"); Big picture, I am using app designer to write data processing apps for the laboratory where I work. The apps use base Matlab (v 2022b) and report generator to create data sheets for our reports. I am attempting to use Matlab Compiler to compile these into standalone desktop apps that I can distribute to my group. The apps run fine in the Matlab environment, but all encounter an error when trying to create a report sheet in the compiled version.
An excerpt from the code is shown below. The error occurs at some point during the execution of this code in the compiled app. As a side question, is it possible to see an error log in the compiled app (similar to how errors would be shown in the command window while working in the Matlab environment)?
I suspect that the error is occuring when the program tries to find the template path in the compiled version or when the document command is executed. All the template files are bundled with the compiled app installer.
makeDOMCompilable();
import mlreportgen.report.*
import mlreportgen.dom.*
%user prompt to enter name of generated report file
prompt = {‘Enter File Name:’};
dlgtitle = ‘Input’;
dims = [1 35];
definput = {”};
Filename = inputdlg(prompt,dlgtitle,dims,definput);
Filename = string(Filename);
%Locate template file and generate full path
whoAmI = mfilename(‘fullpath’);
[fullpath, ~, ~] = fileparts(whoAmI);
template = fullfile(fullpath,’Templates’,’SwellC_Template_New.dotx’);
% I suspect this is the line where the code is encountering an
% error.
D = Document(Filename,’docx’, template);
%There is more code in the block below to finish populating the
%template, but this is the general format.
open(D)
moveToNextHole(D);
append(D, app.ProjectEditField.Value);
moveToNextHole(D);
append(D, app.FeatureEditField.Value);
moveToNextHole(D);
append(D, app.IndexEditField.Value);
moveToNextHole(D);
append(D, app.BoreholeEditField.Value);
moveToNextHole(D);
%…
close(D);
f = msgbox("Report Generation Complete"); app designer, report generator, compiler MATLAB Answers — New Questions
Error with compiled app designer app using report generator toolbox.
Big picture, I am using app designer to write data processing apps for the laboratory where I work. The apps use base Matlab (v 2022b) and report generator to create data sheets for our reports. I am attempting to use Matlab Compiler to compile these into standalone desktop apps that I can distribute to my group. The apps run fine in the Matlab environment, but all encounter an error when trying to create a report sheet in the compiled version.
An excerpt from the code is shown below. The error occurs at some point during the execution of this code in the compiled app. As a side question, is it possible to see an error log in the compiled app (similar to how errors would be shown in the command window while working in the Matlab environment)?
I suspect that the error is occuring when the program tries to find the template path in the compiled version or when the document command is executed. All the template files are bundled with the compiled app installer.
makeDOMCompilable();
import mlreportgen.report.*
import mlreportgen.dom.*
%user prompt to enter name of generated report file
prompt = {‘Enter File Name:’};
dlgtitle = ‘Input’;
dims = [1 35];
definput = {”};
Filename = inputdlg(prompt,dlgtitle,dims,definput);
Filename = string(Filename);
%Locate template file and generate full path
whoAmI = mfilename(‘fullpath’);
[fullpath, ~, ~] = fileparts(whoAmI);
template = fullfile(fullpath,’Templates’,’SwellC_Template_New.dotx’);
% I suspect this is the line where the code is encountering an
% error.
D = Document(Filename,’docx’, template);
%There is more code in the block below to finish populating the
%template, but this is the general format.
open(D)
moveToNextHole(D);
append(D, app.ProjectEditField.Value);
moveToNextHole(D);
append(D, app.FeatureEditField.Value);
moveToNextHole(D);
append(D, app.IndexEditField.Value);
moveToNextHole(D);
append(D, app.BoreholeEditField.Value);
moveToNextHole(D);
%…
close(D);
f = msgbox("Report Generation Complete");Big picture, I am using app designer to write data processing apps for the laboratory where I work. The apps use base Matlab (v 2022b) and report generator to create data sheets for our reports. I am attempting to use Matlab Compiler to compile these into standalone desktop apps that I can distribute to my group. The apps run fine in the Matlab environment, but all encounter an error when trying to create a report sheet in the compiled version.
An excerpt from the code is shown below. The error occurs at some point during the execution of this code in the compiled app. As a side question, is it possible to see an error log in the compiled app (similar to how errors would be shown in the command window while working in the Matlab environment)?
I suspect that the error is occuring when the program tries to find the template path in the compiled version or when the document command is executed. All the template files are bundled with the compiled app installer.
makeDOMCompilable();
import mlreportgen.report.*
import mlreportgen.dom.*
%user prompt to enter name of generated report file
prompt = {‘Enter File Name:’};
dlgtitle = ‘Input’;
dims = [1 35];
definput = {”};
Filename = inputdlg(prompt,dlgtitle,dims,definput);
Filename = string(Filename);
%Locate template file and generate full path
whoAmI = mfilename(‘fullpath’);
[fullpath, ~, ~] = fileparts(whoAmI);
template = fullfile(fullpath,’Templates’,’SwellC_Template_New.dotx’);
% I suspect this is the line where the code is encountering an
% error.
D = Document(Filename,’docx’, template);
%There is more code in the block below to finish populating the
%template, but this is the general format.
open(D)
moveToNextHole(D);
append(D, app.ProjectEditField.Value);
moveToNextHole(D);
append(D, app.FeatureEditField.Value);
moveToNextHole(D);
append(D, app.IndexEditField.Value);
moveToNextHole(D);
append(D, app.BoreholeEditField.Value);
moveToNextHole(D);
%…
close(D);
f = msgbox("Report Generation Complete"); Big picture, I am using app designer to write data processing apps for the laboratory where I work. The apps use base Matlab (v 2022b) and report generator to create data sheets for our reports. I am attempting to use Matlab Compiler to compile these into standalone desktop apps that I can distribute to my group. The apps run fine in the Matlab environment, but all encounter an error when trying to create a report sheet in the compiled version.
An excerpt from the code is shown below. The error occurs at some point during the execution of this code in the compiled app. As a side question, is it possible to see an error log in the compiled app (similar to how errors would be shown in the command window while working in the Matlab environment)?
I suspect that the error is occuring when the program tries to find the template path in the compiled version or when the document command is executed. All the template files are bundled with the compiled app installer.
makeDOMCompilable();
import mlreportgen.report.*
import mlreportgen.dom.*
%user prompt to enter name of generated report file
prompt = {‘Enter File Name:’};
dlgtitle = ‘Input’;
dims = [1 35];
definput = {”};
Filename = inputdlg(prompt,dlgtitle,dims,definput);
Filename = string(Filename);
%Locate template file and generate full path
whoAmI = mfilename(‘fullpath’);
[fullpath, ~, ~] = fileparts(whoAmI);
template = fullfile(fullpath,’Templates’,’SwellC_Template_New.dotx’);
% I suspect this is the line where the code is encountering an
% error.
D = Document(Filename,’docx’, template);
%There is more code in the block below to finish populating the
%template, but this is the general format.
open(D)
moveToNextHole(D);
append(D, app.ProjectEditField.Value);
moveToNextHole(D);
append(D, app.FeatureEditField.Value);
moveToNextHole(D);
append(D, app.IndexEditField.Value);
moveToNextHole(D);
append(D, app.BoreholeEditField.Value);
moveToNextHole(D);
%…
close(D);
f = msgbox("Report Generation Complete"); app designer, report generator, compiler MATLAB Answers — New Questions
Problem in Calculating NDVI Values Using Multispectral Images
I want to calculate NDVI values using multispectral images that range from -1 to 1 using the formula (NIR-R)/(NIR+R). NIR means the image in Near-Infrared band and R means the image in Red band. I apologize if there is any mistake and I humbly ask for guidance.
Following is the images in RGB, Red, and Near-Infrared that I have converted to jpg so I could upload it here, the original type is TIF.
Below is the code that I used to compute these images :
R = imread(‘RED.TIF’);
NIR = imread(‘NIR.TIF’);
NDVI = (NIR-R) ./ (NIR + R); % [In this step I couldn’t use / to compute, could you tell me why?]
NDVI = double(NDVI); % [Why the variable has to be changed to double type? Because if not the image couldn’t be shown.]
colormap(jet); colorbar; impixelinfo;
Why is the NDVI variable only contain 0s and 1s? As the NDVI value should be ranging from -1 to 1 and I want the value to be in 2 digits after decimal. How can I improve the image processing as the green area of plants is missing in the final results? Do I need another methods to calculate it?
Thank you for your attention, sir.I want to calculate NDVI values using multispectral images that range from -1 to 1 using the formula (NIR-R)/(NIR+R). NIR means the image in Near-Infrared band and R means the image in Red band. I apologize if there is any mistake and I humbly ask for guidance.
Following is the images in RGB, Red, and Near-Infrared that I have converted to jpg so I could upload it here, the original type is TIF.
Below is the code that I used to compute these images :
R = imread(‘RED.TIF’);
NIR = imread(‘NIR.TIF’);
NDVI = (NIR-R) ./ (NIR + R); % [In this step I couldn’t use / to compute, could you tell me why?]
NDVI = double(NDVI); % [Why the variable has to be changed to double type? Because if not the image couldn’t be shown.]
colormap(jet); colorbar; impixelinfo;
Why is the NDVI variable only contain 0s and 1s? As the NDVI value should be ranging from -1 to 1 and I want the value to be in 2 digits after decimal. How can I improve the image processing as the green area of plants is missing in the final results? Do I need another methods to calculate it?
Thank you for your attention, sir. I want to calculate NDVI values using multispectral images that range from -1 to 1 using the formula (NIR-R)/(NIR+R). NIR means the image in Near-Infrared band and R means the image in Red band. I apologize if there is any mistake and I humbly ask for guidance.
Following is the images in RGB, Red, and Near-Infrared that I have converted to jpg so I could upload it here, the original type is TIF.
Below is the code that I used to compute these images :
R = imread(‘RED.TIF’);
NIR = imread(‘NIR.TIF’);
NDVI = (NIR-R) ./ (NIR + R); % [In this step I couldn’t use / to compute, could you tell me why?]
NDVI = double(NDVI); % [Why the variable has to be changed to double type? Because if not the image couldn’t be shown.]
colormap(jet); colorbar; impixelinfo;
Why is the NDVI variable only contain 0s and 1s? As the NDVI value should be ranging from -1 to 1 and I want the value to be in 2 digits after decimal. How can I improve the image processing as the green area of plants is missing in the final results? Do I need another methods to calculate it?
Thank you for your attention, sir. ndvi, infrared MATLAB Answers — New Questions
How to get address of a memory in simulink?
I have used data store memory block and have associated one simulink signal to it.
For eg. MemtoStrDat is a simulink signal and it is used as data store name in data store memory block.
How to get the address of this memory MemtoStrDat in simulink?I have used data store memory block and have associated one simulink signal to it.
For eg. MemtoStrDat is a simulink signal and it is used as data store name in data store memory block.
How to get the address of this memory MemtoStrDat in simulink? I have used data store memory block and have associated one simulink signal to it.
For eg. MemtoStrDat is a simulink signal and it is used as data store name in data store memory block.
How to get the address of this memory MemtoStrDat in simulink? simulink, get address of a memory MATLAB Answers — New Questions
How to get address of a memory in simulink?
I have used data store memory block and have associated one simulink signal to it.
For eg. MemtoStrDat is a simulink signal and it is used as data store name in data store memory block.
How to get the address of this memory MemtoStrDat in simulink?I have used data store memory block and have associated one simulink signal to it.
For eg. MemtoStrDat is a simulink signal and it is used as data store name in data store memory block.
How to get the address of this memory MemtoStrDat in simulink? I have used data store memory block and have associated one simulink signal to it.
For eg. MemtoStrDat is a simulink signal and it is used as data store name in data store memory block.
How to get the address of this memory MemtoStrDat in simulink? simulink, get address of a memory MATLAB Answers — New Questions
step response of non linear model
pls tell me clearly with MATLAB code…i am not comfortable with simulink. how to get the step respone of non-linear ODE for 3*3 MIMO boiler systems. the following are the equations.. i want the step response of the output not for the states.
x1dot = (-0.0018*u2*x1^(9/8)) + (0.9*u1) – (0.15*u3);
x2dot = ((((0.73*u2)-0.16)*x1^(9/8)-x2))/10;
x3dot = ((141*u3)-((1.1*u2)-0.19)*x1)/85;
y1 = x1;
y2 = x2;
y3 = 0.05*((0.13073*x3) + (100*((1-(0.001538*x3))*((0.8*x1)-25.6))/(x3*(1.0394-0.00123404*x1))) +(((((0.854*u2) -0.147)*x1) + (45.59*u1) -(2.514*u3) -2.096)/9) -67.975);pls tell me clearly with MATLAB code…i am not comfortable with simulink. how to get the step respone of non-linear ODE for 3*3 MIMO boiler systems. the following are the equations.. i want the step response of the output not for the states.
x1dot = (-0.0018*u2*x1^(9/8)) + (0.9*u1) – (0.15*u3);
x2dot = ((((0.73*u2)-0.16)*x1^(9/8)-x2))/10;
x3dot = ((141*u3)-((1.1*u2)-0.19)*x1)/85;
y1 = x1;
y2 = x2;
y3 = 0.05*((0.13073*x3) + (100*((1-(0.001538*x3))*((0.8*x1)-25.6))/(x3*(1.0394-0.00123404*x1))) +(((((0.854*u2) -0.147)*x1) + (45.59*u1) -(2.514*u3) -2.096)/9) -67.975); pls tell me clearly with MATLAB code…i am not comfortable with simulink. how to get the step respone of non-linear ODE for 3*3 MIMO boiler systems. the following are the equations.. i want the step response of the output not for the states.
x1dot = (-0.0018*u2*x1^(9/8)) + (0.9*u1) – (0.15*u3);
x2dot = ((((0.73*u2)-0.16)*x1^(9/8)-x2))/10;
x3dot = ((141*u3)-((1.1*u2)-0.19)*x1)/85;
y1 = x1;
y2 = x2;
y3 = 0.05*((0.13073*x3) + (100*((1-(0.001538*x3))*((0.8*x1)-25.6))/(x3*(1.0394-0.00123404*x1))) +(((((0.854*u2) -0.147)*x1) + (45.59*u1) -(2.514*u3) -2.096)/9) -67.975); closed loop response MATLAB Answers — New Questions
Implementation of Moving target Indicator
can i implement mti on range doppler map by zeroing the velocity axis near zero?can i implement mti on range doppler map by zeroing the velocity axis near zero? can i implement mti on range doppler map by zeroing the velocity axis near zero? radar, mti, doppler MATLAB Answers — New Questions
Reading tektronix oscilloscope waveforms directly in matlab (DPO4104B)
I’m using a tektronix DPO4104B oscilloscope, currently saving waveforms as .csv from the OpenChoice app. However, I’d like to make my life easier and read/plot data directly into matlab, in a figure file.
I’ve tried following several documents to get the waveforms, such as this (https://uk.mathworks.com/help/instrument/read-a-waveform-using-a-tektronix-scope.html#), but with no luck. I’m using tekvisa v4.2 as the VISA resource, and matlab 2023b with the instrument control toolbox installed.
First problem is, if I try getting the address of the scope connection (done via USB cable), it returns an empty string.
resources(myscope)
ans =
‘
‘
This is worked around by getting the address from the VISA program, in my case it’s in this format ‘USB::0x0699::0x0405::C022561::INSTR’
But even when I set the resource field using this address, I still an unable to connect.
connect(myScope)
Failed to connect to the oscilloscope. Provide a
driver name and try again.
Getting the tektronix matlab driver in (DPO4104.mdd), and adding it to the oscilloscope properties, still yields no connection to the scope.
connect(myScope)
Failed to connect to the oscilloscope. Check
instrument connection.
Seems like I’m doing something majorly wrong, can someone help me?I’m using a tektronix DPO4104B oscilloscope, currently saving waveforms as .csv from the OpenChoice app. However, I’d like to make my life easier and read/plot data directly into matlab, in a figure file.
I’ve tried following several documents to get the waveforms, such as this (https://uk.mathworks.com/help/instrument/read-a-waveform-using-a-tektronix-scope.html#), but with no luck. I’m using tekvisa v4.2 as the VISA resource, and matlab 2023b with the instrument control toolbox installed.
First problem is, if I try getting the address of the scope connection (done via USB cable), it returns an empty string.
resources(myscope)
ans =
‘
‘
This is worked around by getting the address from the VISA program, in my case it’s in this format ‘USB::0x0699::0x0405::C022561::INSTR’
But even when I set the resource field using this address, I still an unable to connect.
connect(myScope)
Failed to connect to the oscilloscope. Provide a
driver name and try again.
Getting the tektronix matlab driver in (DPO4104.mdd), and adding it to the oscilloscope properties, still yields no connection to the scope.
connect(myScope)
Failed to connect to the oscilloscope. Check
instrument connection.
Seems like I’m doing something majorly wrong, can someone help me? I’m using a tektronix DPO4104B oscilloscope, currently saving waveforms as .csv from the OpenChoice app. However, I’d like to make my life easier and read/plot data directly into matlab, in a figure file.
I’ve tried following several documents to get the waveforms, such as this (https://uk.mathworks.com/help/instrument/read-a-waveform-using-a-tektronix-scope.html#), but with no luck. I’m using tekvisa v4.2 as the VISA resource, and matlab 2023b with the instrument control toolbox installed.
First problem is, if I try getting the address of the scope connection (done via USB cable), it returns an empty string.
resources(myscope)
ans =
‘
‘
This is worked around by getting the address from the VISA program, in my case it’s in this format ‘USB::0x0699::0x0405::C022561::INSTR’
But even when I set the resource field using this address, I still an unable to connect.
connect(myScope)
Failed to connect to the oscilloscope. Provide a
driver name and try again.
Getting the tektronix matlab driver in (DPO4104.mdd), and adding it to the oscilloscope properties, still yields no connection to the scope.
connect(myScope)
Failed to connect to the oscilloscope. Check
instrument connection.
Seems like I’m doing something majorly wrong, can someone help me? tektronix, instrument control, oscilloscope, visa MATLAB Answers — New Questions
Reading tektronix oscilloscope waveforms directly in matlab (DPO4104B)
I’m using a tektronix DPO4104B oscilloscope, currently saving waveforms as .csv from the OpenChoice app. However, I’d like to make my life easier and read/plot data directly into matlab, in a figure file.
I’ve tried following several documents to get the waveforms, such as this (https://uk.mathworks.com/help/instrument/read-a-waveform-using-a-tektronix-scope.html#), but with no luck. I’m using tekvisa v4.2 as the VISA resource, and matlab 2023b with the instrument control toolbox installed.
First problem is, if I try getting the address of the scope connection (done via USB cable), it returns an empty string.
resources(myscope)
ans =
‘
‘
This is worked around by getting the address from the VISA program, in my case it’s in this format ‘USB::0x0699::0x0405::C022561::INSTR’
But even when I set the resource field using this address, I still an unable to connect.
connect(myScope)
Failed to connect to the oscilloscope. Provide a
driver name and try again.
Getting the tektronix matlab driver in (DPO4104.mdd), and adding it to the oscilloscope properties, still yields no connection to the scope.
connect(myScope)
Failed to connect to the oscilloscope. Check
instrument connection.
Seems like I’m doing something majorly wrong, can someone help me?I’m using a tektronix DPO4104B oscilloscope, currently saving waveforms as .csv from the OpenChoice app. However, I’d like to make my life easier and read/plot data directly into matlab, in a figure file.
I’ve tried following several documents to get the waveforms, such as this (https://uk.mathworks.com/help/instrument/read-a-waveform-using-a-tektronix-scope.html#), but with no luck. I’m using tekvisa v4.2 as the VISA resource, and matlab 2023b with the instrument control toolbox installed.
First problem is, if I try getting the address of the scope connection (done via USB cable), it returns an empty string.
resources(myscope)
ans =
‘
‘
This is worked around by getting the address from the VISA program, in my case it’s in this format ‘USB::0x0699::0x0405::C022561::INSTR’
But even when I set the resource field using this address, I still an unable to connect.
connect(myScope)
Failed to connect to the oscilloscope. Provide a
driver name and try again.
Getting the tektronix matlab driver in (DPO4104.mdd), and adding it to the oscilloscope properties, still yields no connection to the scope.
connect(myScope)
Failed to connect to the oscilloscope. Check
instrument connection.
Seems like I’m doing something majorly wrong, can someone help me? I’m using a tektronix DPO4104B oscilloscope, currently saving waveforms as .csv from the OpenChoice app. However, I’d like to make my life easier and read/plot data directly into matlab, in a figure file.
I’ve tried following several documents to get the waveforms, such as this (https://uk.mathworks.com/help/instrument/read-a-waveform-using-a-tektronix-scope.html#), but with no luck. I’m using tekvisa v4.2 as the VISA resource, and matlab 2023b with the instrument control toolbox installed.
First problem is, if I try getting the address of the scope connection (done via USB cable), it returns an empty string.
resources(myscope)
ans =
‘
‘
This is worked around by getting the address from the VISA program, in my case it’s in this format ‘USB::0x0699::0x0405::C022561::INSTR’
But even when I set the resource field using this address, I still an unable to connect.
connect(myScope)
Failed to connect to the oscilloscope. Provide a
driver name and try again.
Getting the tektronix matlab driver in (DPO4104.mdd), and adding it to the oscilloscope properties, still yields no connection to the scope.
connect(myScope)
Failed to connect to the oscilloscope. Check
instrument connection.
Seems like I’m doing something majorly wrong, can someone help me? tektronix, instrument control, oscilloscope, visa MATLAB Answers — New Questions
Live Editor can not perfectly preview figures with boldmath
code for reproducing the problem :
close all;
data = [1,1,1,1;2,2,2,2;3,3,3,3;4,4,4,4];
bar(data)
hold on
grid on
xticks([1 2 3 4])
xtickangle(0)
ax = gca;
ax.TickLabelInterpreter = ‘latex’;
xTicklabels = { …
‘textbf{label 1} boldmath$E_1$’, …
‘textbf{label 2} boldmath$E_2$’, …
‘textbf{label 3} boldmath$E_3$’, …
‘textbf{label 4} boldmath$E_4$’};
set(gca,’XTickLabel’,xTicklabels);
ax.YTickLabel = strcat(‘textbf{‘,ax.YTickLabel,’}’); % include this line
xlabel("Different algorithms");
ylabel("Result of schemes");
lgd = legend( …
"1",…
"2",…
"3",…
"4",…
‘Location’,"northwest");
lgd.FontWeight = "bold";
ax.XAxis.FontWeight = ‘bold’;
ax.XAxis.LineWidth = 1;
ax.YAxis.FontWeight = ‘bold’;
ax.YAxis.LineWidth = 1;
ax.FontName = ‘times’;
hold off;
The image above is the expected result. However, the result I obtained in the live editor is as follows:code for reproducing the problem :
close all;
data = [1,1,1,1;2,2,2,2;3,3,3,3;4,4,4,4];
bar(data)
hold on
grid on
xticks([1 2 3 4])
xtickangle(0)
ax = gca;
ax.TickLabelInterpreter = ‘latex’;
xTicklabels = { …
‘textbf{label 1} boldmath$E_1$’, …
‘textbf{label 2} boldmath$E_2$’, …
‘textbf{label 3} boldmath$E_3$’, …
‘textbf{label 4} boldmath$E_4$’};
set(gca,’XTickLabel’,xTicklabels);
ax.YTickLabel = strcat(‘textbf{‘,ax.YTickLabel,’}’); % include this line
xlabel("Different algorithms");
ylabel("Result of schemes");
lgd = legend( …
"1",…
"2",…
"3",…
"4",…
‘Location’,"northwest");
lgd.FontWeight = "bold";
ax.XAxis.FontWeight = ‘bold’;
ax.XAxis.LineWidth = 1;
ax.YAxis.FontWeight = ‘bold’;
ax.YAxis.LineWidth = 1;
ax.FontName = ‘times’;
hold off;
The image above is the expected result. However, the result I obtained in the live editor is as follows: code for reproducing the problem :
close all;
data = [1,1,1,1;2,2,2,2;3,3,3,3;4,4,4,4];
bar(data)
hold on
grid on
xticks([1 2 3 4])
xtickangle(0)
ax = gca;
ax.TickLabelInterpreter = ‘latex’;
xTicklabels = { …
‘textbf{label 1} boldmath$E_1$’, …
‘textbf{label 2} boldmath$E_2$’, …
‘textbf{label 3} boldmath$E_3$’, …
‘textbf{label 4} boldmath$E_4$’};
set(gca,’XTickLabel’,xTicklabels);
ax.YTickLabel = strcat(‘textbf{‘,ax.YTickLabel,’}’); % include this line
xlabel("Different algorithms");
ylabel("Result of schemes");
lgd = legend( …
"1",…
"2",…
"3",…
"4",…
‘Location’,"northwest");
lgd.FontWeight = "bold";
ax.XAxis.FontWeight = ‘bold’;
ax.XAxis.LineWidth = 1;
ax.YAxis.FontWeight = ‘bold’;
ax.YAxis.LineWidth = 1;
ax.FontName = ‘times’;
hold off;
The image above is the expected result. However, the result I obtained in the live editor is as follows: live editor MATLAB Answers — New Questions
How to fix the error: Error using trainNetwork, Input data indices must be nonnegative integers.
I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs, @getmask);
testDs = transform(testDs, @getmask);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options);
%
%
%
%
%% You need the function below, getmask,
function outputCell = getmask(inputCell)
%GETMASK Convert region labels to a mask of labels of size equal to the
%size of the input ECG signal.
%
% inputCell is a two-element cell array containing an ECG signal vector
% and a table of region labels.
%
% outputCell is a two-element cell array containing the ECG signal vector
% and a categorical label vector mask of the same length as the signal.
% Copyright 2020 The MathWorks, Inc.
sig = inputCell{1};
roiTable = inputCell{2};
L = length(sig);
M = signalMask(roiTable);
% Get categorical mask and give priority to QRS regions when there is overlap
mask = catmask(M,L,’OverlapAction’,’prioritizeByList’,’PriorityList’,[2 1 3]);
% Set missing values to "n/a"
mask(ismissing(mask)) = "n/a";
outputCell = {sig,mask};
end
%
%
%
%
function outputCell = resizeData(inputCell)
%RESIZEDATA Break input ECG signal and label mask into segments of length
%5000.
%
% inputCell is a two-element cell array containing an ECG signal and a
% label mask.
%
% outputCell is a two-column cell array containing as many 5000-long
% signal segments and label masks that were possible to generate from the
% input data.
% Copyright 2019 The MathWorks, Inc.
targetLength = 5000;
sig = inputCell{1};
mask = inputCell{2};
% Get number of chunks
numChunks = floor(size(sig,1)/targetLength);
% Truncate signal and mask to integer number of chunks
sig = sig(1:numChunks*targetLength);
mask = mask(1:numChunks*targetLength);
% Create a cell array containing signal chunks
sigOut = reshape(sig,targetLength,numChunks)’;
sigOut = num2cell(sigOut,2);
% Create a cell array containing mask chunks
lblOut = reshape(mask,targetLength,numChunks)’;
lblOut = num2cell(lblOut,2);
% Output a two-column cell array with all chunks
outputCell = [sigOut, lblOut];
endI am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs, @getmask);
testDs = transform(testDs, @getmask);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options);
%
%
%
%
%% You need the function below, getmask,
function outputCell = getmask(inputCell)
%GETMASK Convert region labels to a mask of labels of size equal to the
%size of the input ECG signal.
%
% inputCell is a two-element cell array containing an ECG signal vector
% and a table of region labels.
%
% outputCell is a two-element cell array containing the ECG signal vector
% and a categorical label vector mask of the same length as the signal.
% Copyright 2020 The MathWorks, Inc.
sig = inputCell{1};
roiTable = inputCell{2};
L = length(sig);
M = signalMask(roiTable);
% Get categorical mask and give priority to QRS regions when there is overlap
mask = catmask(M,L,’OverlapAction’,’prioritizeByList’,’PriorityList’,[2 1 3]);
% Set missing values to "n/a"
mask(ismissing(mask)) = "n/a";
outputCell = {sig,mask};
end
%
%
%
%
function outputCell = resizeData(inputCell)
%RESIZEDATA Break input ECG signal and label mask into segments of length
%5000.
%
% inputCell is a two-element cell array containing an ECG signal and a
% label mask.
%
% outputCell is a two-column cell array containing as many 5000-long
% signal segments and label masks that were possible to generate from the
% input data.
% Copyright 2019 The MathWorks, Inc.
targetLength = 5000;
sig = inputCell{1};
mask = inputCell{2};
% Get number of chunks
numChunks = floor(size(sig,1)/targetLength);
% Truncate signal and mask to integer number of chunks
sig = sig(1:numChunks*targetLength);
mask = mask(1:numChunks*targetLength);
% Create a cell array containing signal chunks
sigOut = reshape(sig,targetLength,numChunks)’;
sigOut = num2cell(sigOut,2);
% Create a cell array containing mask chunks
lblOut = reshape(mask,targetLength,numChunks)’;
lblOut = num2cell(lblOut,2);
% Output a two-column cell array with all chunks
outputCell = [sigOut, lblOut];
end I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs, @getmask);
testDs = transform(testDs, @getmask);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options);
%
%
%
%
%% You need the function below, getmask,
function outputCell = getmask(inputCell)
%GETMASK Convert region labels to a mask of labels of size equal to the
%size of the input ECG signal.
%
% inputCell is a two-element cell array containing an ECG signal vector
% and a table of region labels.
%
% outputCell is a two-element cell array containing the ECG signal vector
% and a categorical label vector mask of the same length as the signal.
% Copyright 2020 The MathWorks, Inc.
sig = inputCell{1};
roiTable = inputCell{2};
L = length(sig);
M = signalMask(roiTable);
% Get categorical mask and give priority to QRS regions when there is overlap
mask = catmask(M,L,’OverlapAction’,’prioritizeByList’,’PriorityList’,[2 1 3]);
% Set missing values to "n/a"
mask(ismissing(mask)) = "n/a";
outputCell = {sig,mask};
end
%
%
%
%
function outputCell = resizeData(inputCell)
%RESIZEDATA Break input ECG signal and label mask into segments of length
%5000.
%
% inputCell is a two-element cell array containing an ECG signal and a
% label mask.
%
% outputCell is a two-column cell array containing as many 5000-long
% signal segments and label masks that were possible to generate from the
% input data.
% Copyright 2019 The MathWorks, Inc.
targetLength = 5000;
sig = inputCell{1};
mask = inputCell{2};
% Get number of chunks
numChunks = floor(size(sig,1)/targetLength);
% Truncate signal and mask to integer number of chunks
sig = sig(1:numChunks*targetLength);
mask = mask(1:numChunks*targetLength);
% Create a cell array containing signal chunks
sigOut = reshape(sig,targetLength,numChunks)’;
sigOut = num2cell(sigOut,2);
% Create a cell array containing mask chunks
lblOut = reshape(mask,targetLength,numChunks)’;
lblOut = num2cell(lblOut,2);
% Output a two-column cell array with all chunks
outputCell = [sigOut, lblOut];
end sequence-to-sequence classification, transformer encoder, ecg signal wave segmentation MATLAB Answers — New Questions
Incorrect order of input signals in Test Harness generated for If Action Subsystem
I am trying to generate a test harness for an If Action subsystem. When generating the test harness, I select the ‘Constant’ option for Sources to the test harness. When the test harness gets generated, I noticed that the ordering of the constant blocks seems to be incorrect. Here is a an image:
As can be seen, the third input to the subsystem happens to be the ‘Action Port’ as opposed to the first one. I am trying to generate a test harness for an If Action subsystem. When generating the test harness, I select the ‘Constant’ option for Sources to the test harness. When the test harness gets generated, I noticed that the ordering of the constant blocks seems to be incorrect. Here is a an image:
As can be seen, the third input to the subsystem happens to be the ‘Action Port’ as opposed to the first one. I am trying to generate a test harness for an If Action subsystem. When generating the test harness, I select the ‘Constant’ option for Sources to the test harness. When the test harness gets generated, I noticed that the ordering of the constant blocks seems to be incorrect. Here is a an image:
As can be seen, the third input to the subsystem happens to be the ‘Action Port’ as opposed to the first one. simulink, test, if, action, subsystem, harness, incorrect, order, inputs MATLAB Answers — New Questions
Hello. Could someone please suggest other components or blocks I can use to avoid using the step input block for the duty cycle?
Because I need the amplitude to reach 1.8V, and I only get 1V with the step input.Because I need the amplitude to reach 1.8V, and I only get 1V with the step input. Because I need the amplitude to reach 1.8V, and I only get 1V with the step input. #inputselector #multipleinputs, #bbc MATLAB Answers — New Questions
Simulink integrator block reset and integrate at single time step
Hello,
I am working on a system where I have two state variables, one of which is to be activated (becomes nonzero) in the middle of simulation.
I am using the "reset" feature of the integrator block to model the appearance of the state variable by feeding appropriate initial state value and triggering reset.
I noticed that when reset is triggered, the integrator block does only the reset part and skips integration, thus spending one timestep without integrating.
I was wondering whether it would be possible to do the reset and then integrate the variable all in one time step when reset is triggered.
Thank you!Hello,
I am working on a system where I have two state variables, one of which is to be activated (becomes nonzero) in the middle of simulation.
I am using the "reset" feature of the integrator block to model the appearance of the state variable by feeding appropriate initial state value and triggering reset.
I noticed that when reset is triggered, the integrator block does only the reset part and skips integration, thus spending one timestep without integrating.
I was wondering whether it would be possible to do the reset and then integrate the variable all in one time step when reset is triggered.
Thank you! Hello,
I am working on a system where I have two state variables, one of which is to be activated (becomes nonzero) in the middle of simulation.
I am using the "reset" feature of the integrator block to model the appearance of the state variable by feeding appropriate initial state value and triggering reset.
I noticed that when reset is triggered, the integrator block does only the reset part and skips integration, thus spending one timestep without integrating.
I was wondering whether it would be possible to do the reset and then integrate the variable all in one time step when reset is triggered.
Thank you! integration, simulink, integrator, simulation MATLAB Answers — New Questions
How to fix the error: Error using trainNetwork, Input data indices must be nonnegative integers.
I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options);I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options); I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options); sequence-to-sequence classification, transformer encoder, ecg signal wave segmentation MATLAB Answers — New Questions
How to fix the error: Error using trainNetwork, Input data indices must be nonnegative integers.
I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options);I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options); I am working on "wave segmentaion using deep learning" which can be found in the page: https://www.mathworks.com/help/signal/ug/waveform-segmentation-using-deep-learning.html#WaveformSegmentationUsingDeepLearningExample-15
This is a problem of sequence-to-sequnce classification. (e.g., input: (0.5, -5, 3, 10, 40, …); prediction: (P, T, T, T, n/a,…))
I apply Tranformer encoder based on the code by Ben (Matlab staff, https://www.mathworks.com/matlabcentral/answers/2014811-is-there-any-documentation-on-how-to-build-a-transformer-encoder-from-scratch-in-matlab ), and replace LSTM layer by a Transformer encoder. The modified code by me is given at the bottom.
When I run the section of network training, I got an error message as follows, and hopefully could get some help to fix the problem.
———————————————————————————————————————————————————————————————
Error in waveExtractionTest_TransEnc (line …)
filteredNet = trainNetwork(filteredTrainSignalss,trainLabels,net,options);
Caused by:
Error using nnet.internal.cnn.layer.util.EmbeddingDAGNetworkBaseStrategy/embedData
Input data indices must be nonnegative integers.
——————————————————————————————————————————————————————–
%% Download the data
dataURL = ‘https://www.mathworks.com/supportfiles/SPT/data/QTDatabaseECGData1.zip’;
dirQT = pwd;
datasetFolder = fullfile(dirQT,’QTDataset’);
zipFile = fullfile(dirQT,’QTDatabaseECGData.zip’);
if ~exist(datasetFolder,’dir’)
websave(zipFile,dataURL);
unzip(zipFile,dirQT);
end
%%
sds = signalDatastore(datasetFolder,’SignalVariableNames’,["ecgSignal","signalRegionLabels"])
%%
rng default
[trainIdx,~,testIdx] = dividerand(numel(sds.Files),0.8,0,0.2);
trainDs = subset(sds,trainIdx);
testDs = subset(sds,testIdx);
%%
trainDs = transform(trainDs,@resizeData);
testDs = transform(testDs,@resizeData);
%%
% Bandpass filter design
hFilt = designfilt(‘bandpassiir’, ‘StopbandFrequency1′,0.4215,’PassbandFrequency1’, 0.5, …
‘PassbandFrequency2′,40,’StopbandFrequency2’,53.345,…
‘StopbandAttenuation1′,60,’PassbandRipple’,0.1,’StopbandAttenuation2′,60,…
‘SampleRate’,250,’DesignMethod’,’ellip’);
% Create tall arrays from the transformed datastores and filter the signals
tallTrainSet = tall(trainDs);
tallTestSet = tall(testDs);
filteredTrainSignals = gather(cellfun(@(x)filter(hFilt,x),tallTrainSet(:,1),’UniformOutput’,false));
trainLabels = gather(tallTrainSet(:,2));
filteredTestSignals = gather(cellfun(@(x)filter(hFilt,x),tallTestSet(:,1),’UniformOutput’,false));
testLabels = gather(tallTestSet(:,2));
%% Create model
% We will use 2 encoder layers.
numHeads = 1;
numKeyChannels = 20;
feedforwardHiddenSize = 100;
modelHiddenSize = 20;
% Since the values in the sequence can be 1,2, …, 10 the "vocabulary" size is 10.
vocabSize = 100000; % the size of input sequence of one sample-training-data is 5000
inputSize = 1;
encoderLayers = [
sequenceInputLayer(1,Name="in") % input
wordEmbeddingLayer(modelHiddenSize,vocabSize,Name="embedding") % embedding
positionEmbeddingLayer(modelHiddenSize,vocabSize) % position embedding
additionLayer(2,Name="embed_add") % add the data and position embeddings
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 1
additionLayer(2,Name="attention_add") %
layerNormalizationLayer(Name="attention_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward_add") %
layerNormalizationLayer(Name="encoder1_out") %
selfAttentionLayer(numHeads,numKeyChannels) % encoder block 2
additionLayer(2,Name="attention2_add") %
layerNormalizationLayer(Name="attention2_norm") %
fullyConnectedLayer(feedforwardHiddenSize) %
reluLayer %
fullyConnectedLayer(modelHiddenSize) %
additionLayer(2,Name="feedforward2_add") %
layerNormalizationLayer() %
% indexing1dLayer %
% fullyConnectedLayer(inputSize)
fullyConnectedLayer(4)
softmaxLayer("Name","softmax")
classificationLayer("Name","classification")
]; % output head
%
net = layerGraph(encoderLayers);
net = connectLayers(net,"embed_add","attention_add/in2");
net = connectLayers(net,"embedding","embed_add/in2");
net = connectLayers(net,"attention_norm","feedforward_add/in2");
net = connectLayers(net,"encoder1_out","attention2_add/in2");
net = connectLayers(net,"attention2_norm","feedforward2_add/in2");
% net = initialize(net);
% analyze the network to see how data flows through it
analyzeNetwork(net)
%
%%
options = trainingOptions("adam", …
MaxEpochs = 10, …
MiniBatchSize = 50, …
Plots="training-progress", …
Shuffle="every-epoch", …
InitialLearnRate=1e-2, …
LearnRateDropFactor=0.9, …
LearnRateDropPeriod=3, …
LearnRateSchedule="piecewise");
%%
filteredNet = trainNetwork(filteredTrainSignals,trainLabels,net,options); sequence-to-sequence classification, transformer encoder, ecg signal wave segmentation MATLAB Answers — New Questions
Buoy move with ocean wave
Hello guys,
I am here to ask a simulation question. I am trying to model how to buoy makes up and down according to ocean waves. The problem is I couldn’t add the sine wave in the figure. Here is the code what i wrote;
clear all;clc
radiusofcrank = 1;
angular_velocity = 60; % angular velocity in radians per second
for t = linspace(0, 1, 1000)
x_crank = radiusofcrank * cos(angular_velocity * t); %motion of the crank radius
y_crank = radiusofcrank * sin(angular_velocity * t);
x_buoy = 0; %x axis of buoy
y_buoy = y_crank – 5; % makes buoy moves up and down
plot(x_crank, y_crank); %crank
hold on;
plot([0, x_crank], [0, y_crank], ‘black’); %crank radius
plot(x_buoy, y_buoy, ‘o’, ‘MarkerSize’, 50, ‘MarkerFaceColor’, ‘b’); %buoy
plot([x_crank, x_buoy], [y_crank, y_buoy], ‘-‘, ‘Color’, ‘b’); % Connecting rod
theta = linspace(0, 2*pi, 100); %plots circle (2pi = 360 degree)
circle_x = radiusofcrank * cos(theta);
circle_y = radiusofcrank * sin(theta);
plot(circle_x, circle_y);
hold off;
title(‘Buoy Motion’);
xlabel(‘X-coordinate’);
ylabel(‘Y-coordinate’);
axis equal;
grid on;
pause(0.01);
end
% Sine Wave
t = 0.1:100;
Wave_amplitude_sine = 3; % Amplitude of the sine wave
wave_frequency = 0.01; % Frequency of the sine wave (in Hz)
% Create the figure and plot initial sine wave
h = plot(t,sin(2 * pi * wave_frequency * t));
title(‘Ocean Wave’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
grid on;
for time = 0:1:1000
phase = 2 * pi * wave_frequency * time; % Update the phase based on time and speed
set(h, ‘YData’, sin(2 * pi * wave_frequency * t + phase));
pause(0.028);
end
I need your help. Thank you!Hello guys,
I am here to ask a simulation question. I am trying to model how to buoy makes up and down according to ocean waves. The problem is I couldn’t add the sine wave in the figure. Here is the code what i wrote;
clear all;clc
radiusofcrank = 1;
angular_velocity = 60; % angular velocity in radians per second
for t = linspace(0, 1, 1000)
x_crank = radiusofcrank * cos(angular_velocity * t); %motion of the crank radius
y_crank = radiusofcrank * sin(angular_velocity * t);
x_buoy = 0; %x axis of buoy
y_buoy = y_crank – 5; % makes buoy moves up and down
plot(x_crank, y_crank); %crank
hold on;
plot([0, x_crank], [0, y_crank], ‘black’); %crank radius
plot(x_buoy, y_buoy, ‘o’, ‘MarkerSize’, 50, ‘MarkerFaceColor’, ‘b’); %buoy
plot([x_crank, x_buoy], [y_crank, y_buoy], ‘-‘, ‘Color’, ‘b’); % Connecting rod
theta = linspace(0, 2*pi, 100); %plots circle (2pi = 360 degree)
circle_x = radiusofcrank * cos(theta);
circle_y = radiusofcrank * sin(theta);
plot(circle_x, circle_y);
hold off;
title(‘Buoy Motion’);
xlabel(‘X-coordinate’);
ylabel(‘Y-coordinate’);
axis equal;
grid on;
pause(0.01);
end
% Sine Wave
t = 0.1:100;
Wave_amplitude_sine = 3; % Amplitude of the sine wave
wave_frequency = 0.01; % Frequency of the sine wave (in Hz)
% Create the figure and plot initial sine wave
h = plot(t,sin(2 * pi * wave_frequency * t));
title(‘Ocean Wave’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
grid on;
for time = 0:1:1000
phase = 2 * pi * wave_frequency * time; % Update the phase based on time and speed
set(h, ‘YData’, sin(2 * pi * wave_frequency * t + phase));
pause(0.028);
end
I need your help. Thank you! Hello guys,
I am here to ask a simulation question. I am trying to model how to buoy makes up and down according to ocean waves. The problem is I couldn’t add the sine wave in the figure. Here is the code what i wrote;
clear all;clc
radiusofcrank = 1;
angular_velocity = 60; % angular velocity in radians per second
for t = linspace(0, 1, 1000)
x_crank = radiusofcrank * cos(angular_velocity * t); %motion of the crank radius
y_crank = radiusofcrank * sin(angular_velocity * t);
x_buoy = 0; %x axis of buoy
y_buoy = y_crank – 5; % makes buoy moves up and down
plot(x_crank, y_crank); %crank
hold on;
plot([0, x_crank], [0, y_crank], ‘black’); %crank radius
plot(x_buoy, y_buoy, ‘o’, ‘MarkerSize’, 50, ‘MarkerFaceColor’, ‘b’); %buoy
plot([x_crank, x_buoy], [y_crank, y_buoy], ‘-‘, ‘Color’, ‘b’); % Connecting rod
theta = linspace(0, 2*pi, 100); %plots circle (2pi = 360 degree)
circle_x = radiusofcrank * cos(theta);
circle_y = radiusofcrank * sin(theta);
plot(circle_x, circle_y);
hold off;
title(‘Buoy Motion’);
xlabel(‘X-coordinate’);
ylabel(‘Y-coordinate’);
axis equal;
grid on;
pause(0.01);
end
% Sine Wave
t = 0.1:100;
Wave_amplitude_sine = 3; % Amplitude of the sine wave
wave_frequency = 0.01; % Frequency of the sine wave (in Hz)
% Create the figure and plot initial sine wave
h = plot(t,sin(2 * pi * wave_frequency * t));
title(‘Ocean Wave’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
grid on;
for time = 0:1:1000
phase = 2 * pi * wave_frequency * time; % Update the phase based on time and speed
set(h, ‘YData’, sin(2 * pi * wave_frequency * t + phase));
pause(0.028);
end
I need your help. Thank you! model, sinewave, crank MATLAB Answers — New Questions
Simulation 3D Vehicle Lights
Hello,
When using the Simulation 3D vehicle with Ground Following block in Simulink, the lights appear on when all options are set to off. With the below setup and all lights set to off (all zeros)…
the lights remain on.
How do I turn these lights off?
Thanks!Hello,
When using the Simulation 3D vehicle with Ground Following block in Simulink, the lights appear on when all options are set to off. With the below setup and all lights set to off (all zeros)…
the lights remain on.
How do I turn these lights off?
Thanks! Hello,
When using the Simulation 3D vehicle with Ground Following block in Simulink, the lights appear on when all options are set to off. With the below setup and all lights set to off (all zeros)…
the lights remain on.
How do I turn these lights off?
Thanks! unreal engine, automated driving scenario MATLAB Answers — New Questions
How to change color of point depending on side of a line?
Hello,
I am producing a scatter plot using two columns of data from a .db file and would like to change the color of each of the data points based off their location relative to two lines in the figure. That is, if:
1) the point is to the left of some xline, that point should be some color
2) the point is to the right of the xline AND above some yline, let the point be another color
3) the point is to the right of the xline and below some yline, have it be yet another color
I don’t think I can include scatter in a for loop and don’t know if I should organize each of the points in the table data into separate "bins" to then scatter individually (don’t know how to do that either, to be honest).
Any and all help would be greatly appreciated. Thank you!Hello,
I am producing a scatter plot using two columns of data from a .db file and would like to change the color of each of the data points based off their location relative to two lines in the figure. That is, if:
1) the point is to the left of some xline, that point should be some color
2) the point is to the right of the xline AND above some yline, let the point be another color
3) the point is to the right of the xline and below some yline, have it be yet another color
I don’t think I can include scatter in a for loop and don’t know if I should organize each of the points in the table data into separate "bins" to then scatter individually (don’t know how to do that either, to be honest).
Any and all help would be greatly appreciated. Thank you! Hello,
I am producing a scatter plot using two columns of data from a .db file and would like to change the color of each of the data points based off their location relative to two lines in the figure. That is, if:
1) the point is to the left of some xline, that point should be some color
2) the point is to the right of the xline AND above some yline, let the point be another color
3) the point is to the right of the xline and below some yline, have it be yet another color
I don’t think I can include scatter in a for loop and don’t know if I should organize each of the points in the table data into separate "bins" to then scatter individually (don’t know how to do that either, to be honest).
Any and all help would be greatly appreciated. Thank you! scatter, color, figure, xline, yline, .db MATLAB Answers — New Questions