Category: Matlab
Category Archives: Matlab
xcorr results: c written in long format, lags in wide format
I want to calculate the cross-correlation between ankle and hip movement.
My data are organised in a structure: model.filt.modelOutputs with 12500×3 matrices.
I attached an example file with only the filtered Ankle and Hip angles.
The data contains several movement cycles which can be identified by the starting frames stored in tStart.
When I use [c, lags] = xcorr, I get c as 1301×1 double and lags as 1×1301 double.
Can anyone explain, why this happens? When I use different example vectors, both results have the same orientation.
This is the part of my code, which reproduces the results::
load modelExample.mat
tStart = [1,611,1261];
[c, lags] = xcorr(modelExample.filt.RAnkleAngles(tStart(2):tStart(3),2), modelExample.filt.RHipAngles(tStart(2):tStart(3),2), ‘normalized’);I want to calculate the cross-correlation between ankle and hip movement.
My data are organised in a structure: model.filt.modelOutputs with 12500×3 matrices.
I attached an example file with only the filtered Ankle and Hip angles.
The data contains several movement cycles which can be identified by the starting frames stored in tStart.
When I use [c, lags] = xcorr, I get c as 1301×1 double and lags as 1×1301 double.
Can anyone explain, why this happens? When I use different example vectors, both results have the same orientation.
This is the part of my code, which reproduces the results::
load modelExample.mat
tStart = [1,611,1261];
[c, lags] = xcorr(modelExample.filt.RAnkleAngles(tStart(2):tStart(3),2), modelExample.filt.RHipAngles(tStart(2):tStart(3),2), ‘normalized’); I want to calculate the cross-correlation between ankle and hip movement.
My data are organised in a structure: model.filt.modelOutputs with 12500×3 matrices.
I attached an example file with only the filtered Ankle and Hip angles.
The data contains several movement cycles which can be identified by the starting frames stored in tStart.
When I use [c, lags] = xcorr, I get c as 1301×1 double and lags as 1×1301 double.
Can anyone explain, why this happens? When I use different example vectors, both results have the same orientation.
This is the part of my code, which reproduces the results::
load modelExample.mat
tStart = [1,611,1261];
[c, lags] = xcorr(modelExample.filt.RAnkleAngles(tStart(2):tStart(3),2), modelExample.filt.RHipAngles(tStart(2):tStart(3),2), ‘normalized’); xcorr MATLAB Answers — New Questions
Upgraded Matlab from 2022b to 2023b and I’ve noticed a floating point error
I have recently upgraded my Matlab version from 2022b to 2023b and I have noticed a floating point error when running my code in windows, but not when I run it in linux. I’m sure my code hasn’t changed at all so its unclear what’s happened. Any ideas why this change has happened?I have recently upgraded my Matlab version from 2022b to 2023b and I have noticed a floating point error when running my code in windows, but not when I run it in linux. I’m sure my code hasn’t changed at all so its unclear what’s happened. Any ideas why this change has happened? I have recently upgraded my Matlab version from 2022b to 2023b and I have noticed a floating point error when running my code in windows, but not when I run it in linux. I’m sure my code hasn’t changed at all so its unclear what’s happened. Any ideas why this change has happened? 2023b MATLAB Answers — New Questions
Upgraded Matlab from 2022b to 2023b and I’ve noticed a floating point error
I have recently upgraded my Matlab version from 2022b to 2023b and I have noticed a floating point error when running my code in windows, but not when I run it in linux. I’m sure my code hasn’t changed at all so its unclear what’s happened. Any ideas why this change has happened?I have recently upgraded my Matlab version from 2022b to 2023b and I have noticed a floating point error when running my code in windows, but not when I run it in linux. I’m sure my code hasn’t changed at all so its unclear what’s happened. Any ideas why this change has happened? I have recently upgraded my Matlab version from 2022b to 2023b and I have noticed a floating point error when running my code in windows, but not when I run it in linux. I’m sure my code hasn’t changed at all so its unclear what’s happened. Any ideas why this change has happened? 2023b MATLAB Answers — New Questions
Parallel Simulation VERY slow?
I have created a Simulink file which runs in 99 seconds. I decided to use parsim in matlab to make it even faster. I used the time step required for the workers to start in different time (and use specific data) and run this faster, but instead it requires 5100 seconds (~85 minutes). My guess would be that each worker uses ALL the data, and possibly runs the entirety of the simulation.
Below is the code I created. What do I need to change so that I can make it faster, or at least working properly, meaning that each worker will use the specified data (for example data between 0.04-0.08) and run this specific time.
% Create a parallel pool if not already available
if isempty(gcp(‘nocreate’))
parpool; % Create a parallel pool
end
% Load Model
model = ‘zigzag_example_matlab’;
load_system(model);
% Sweep parameters
sweep = (0.00:0.04:3.84);
numSims = numel(sweep);
% Preallocate SimulationInput array
simIn = Simulink.SimulationInput.empty(numSims, 0);
% Cell array of variable names
variableNames = {‘From Workspace’, ‘From Workspace1’, ‘From Workspace2’, ‘From Workspace3’, ‘From Workspace4’, …
‘From Workspace5’, ‘From Workspace6’, ‘From Workspace7’, ‘From Workspace8’, ‘From Workspace9’, …
‘From Workspace10’, ‘From Workspace11’};
% Create an array of SimulationInput objects and specify the sweep value for each simulation
for idx = 1:numSims
simIn(idx) = Simulink.SimulationInput(model);
% Set ‘SampleTime’ for each variable
for varIdx = 1:numel(variableNames)
variablePath = sprintf(‘zigzag_example_matlab/%s’, variableNames{varIdx});
simIn(idx) = simIn(idx).setBlockParameter(variablePath, ‘SampleTime’, num2str(sweep(idx)));
end
end
% Simulate the model
tic
simOut = parsim(simIn, ‘TransferBaseWorkspaceVariables’, ‘on’, ‘ShowSimulationManager’, ‘on’);
tocI have created a Simulink file which runs in 99 seconds. I decided to use parsim in matlab to make it even faster. I used the time step required for the workers to start in different time (and use specific data) and run this faster, but instead it requires 5100 seconds (~85 minutes). My guess would be that each worker uses ALL the data, and possibly runs the entirety of the simulation.
Below is the code I created. What do I need to change so that I can make it faster, or at least working properly, meaning that each worker will use the specified data (for example data between 0.04-0.08) and run this specific time.
% Create a parallel pool if not already available
if isempty(gcp(‘nocreate’))
parpool; % Create a parallel pool
end
% Load Model
model = ‘zigzag_example_matlab’;
load_system(model);
% Sweep parameters
sweep = (0.00:0.04:3.84);
numSims = numel(sweep);
% Preallocate SimulationInput array
simIn = Simulink.SimulationInput.empty(numSims, 0);
% Cell array of variable names
variableNames = {‘From Workspace’, ‘From Workspace1’, ‘From Workspace2’, ‘From Workspace3’, ‘From Workspace4’, …
‘From Workspace5’, ‘From Workspace6’, ‘From Workspace7’, ‘From Workspace8’, ‘From Workspace9’, …
‘From Workspace10’, ‘From Workspace11’};
% Create an array of SimulationInput objects and specify the sweep value for each simulation
for idx = 1:numSims
simIn(idx) = Simulink.SimulationInput(model);
% Set ‘SampleTime’ for each variable
for varIdx = 1:numel(variableNames)
variablePath = sprintf(‘zigzag_example_matlab/%s’, variableNames{varIdx});
simIn(idx) = simIn(idx).setBlockParameter(variablePath, ‘SampleTime’, num2str(sweep(idx)));
end
end
% Simulate the model
tic
simOut = parsim(simIn, ‘TransferBaseWorkspaceVariables’, ‘on’, ‘ShowSimulationManager’, ‘on’);
toc I have created a Simulink file which runs in 99 seconds. I decided to use parsim in matlab to make it even faster. I used the time step required for the workers to start in different time (and use specific data) and run this faster, but instead it requires 5100 seconds (~85 minutes). My guess would be that each worker uses ALL the data, and possibly runs the entirety of the simulation.
Below is the code I created. What do I need to change so that I can make it faster, or at least working properly, meaning that each worker will use the specified data (for example data between 0.04-0.08) and run this specific time.
% Create a parallel pool if not already available
if isempty(gcp(‘nocreate’))
parpool; % Create a parallel pool
end
% Load Model
model = ‘zigzag_example_matlab’;
load_system(model);
% Sweep parameters
sweep = (0.00:0.04:3.84);
numSims = numel(sweep);
% Preallocate SimulationInput array
simIn = Simulink.SimulationInput.empty(numSims, 0);
% Cell array of variable names
variableNames = {‘From Workspace’, ‘From Workspace1’, ‘From Workspace2’, ‘From Workspace3’, ‘From Workspace4’, …
‘From Workspace5’, ‘From Workspace6’, ‘From Workspace7’, ‘From Workspace8’, ‘From Workspace9’, …
‘From Workspace10’, ‘From Workspace11’};
% Create an array of SimulationInput objects and specify the sweep value for each simulation
for idx = 1:numSims
simIn(idx) = Simulink.SimulationInput(model);
% Set ‘SampleTime’ for each variable
for varIdx = 1:numel(variableNames)
variablePath = sprintf(‘zigzag_example_matlab/%s’, variableNames{varIdx});
simIn(idx) = simIn(idx).setBlockParameter(variablePath, ‘SampleTime’, num2str(sweep(idx)));
end
end
% Simulate the model
tic
simOut = parsim(simIn, ‘TransferBaseWorkspaceVariables’, ‘on’, ‘ShowSimulationManager’, ‘on’);
toc matlab, parallel computing toolbox, simulink, simulation MATLAB Answers — New Questions
How we can do the matrix and vector in vector form?
clc;
clear all ;
close all;
format long g;
%% developing the function for the reverse in the vector concate and reverse it
A = [1;2;3]
B = [4 5 6;8 9 11]
[numRows,numCols] = size(B)
%% new vector will be vector form
C = vertcat(A,[B])clc;
clear all ;
close all;
format long g;
%% developing the function for the reverse in the vector concate and reverse it
A = [1;2;3]
B = [4 5 6;8 9 11]
[numRows,numCols] = size(B)
%% new vector will be vector form
C = vertcat(A,[B]) clc;
clear all ;
close all;
format long g;
%% developing the function for the reverse in the vector concate and reverse it
A = [1;2;3]
B = [4 5 6;8 9 11]
[numRows,numCols] = size(B)
%% new vector will be vector form
C = vertcat(A,[B]) vector, mathematics, matlab, matrix, array, arrays, cell MATLAB Answers — New Questions
How we can do the matrix and vector in vector form?
clc;
clear all ;
close all;
format long g;
%% developing the function for the reverse in the vector concate and reverse it
A = [1;2;3]
B = [4 5 6;8 9 11]
[numRows,numCols] = size(B)
%% new vector will be vector form
C = vertcat(A,[B])clc;
clear all ;
close all;
format long g;
%% developing the function for the reverse in the vector concate and reverse it
A = [1;2;3]
B = [4 5 6;8 9 11]
[numRows,numCols] = size(B)
%% new vector will be vector form
C = vertcat(A,[B]) clc;
clear all ;
close all;
format long g;
%% developing the function for the reverse in the vector concate and reverse it
A = [1;2;3]
B = [4 5 6;8 9 11]
[numRows,numCols] = size(B)
%% new vector will be vector form
C = vertcat(A,[B]) vector, mathematics, matlab, matrix, array, arrays, cell MATLAB Answers — New Questions
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