Category: Matlab
Category Archives: Matlab
I have Backpropagation doubt
I’m trying to do neural network with 2 hidden layers and one neuron in the output layer without any toolboxes and just with matrix and vectors multiplications. To do this, I created fictional simple data as below to help me in this task:
%Data
x = 1:1000;
y1 = sind(x);
y2 = sind(x+30);
y3 = cosd(x);
y4 = cosd(x+30);
y5 = cosd(x+45);
% y6 will be the desired output data taht I would like my neural network
% try to predict
y6 = (y1 + y2 + y3 + y4 + y5);
Then, I coded as I thought to be be the right way, but my neural network can´t reach a good result, as below:
My doubt is if the result isn´t good because my implementation isn´t right or because I need to add more mechanisms im my neural network (like momentum, regularization and etc.) ?
I will post my code below sorry about the naem of some variables, but originally I wrote this code in portuguese. I will comment the code to help undestand it
%Nueral network achictecture
n_h1 = 10;
n_h2 = 11;
n_out = 1;
%Adjustable parameters
w1 = rand(5,n_h1);
b1 = ones(1,n_h1)*rand(1,1);
w2 = rand(n_h1,n_h2);
b2 = ones(1,n_h2)*rand(1,1);
w_out = rand(n_h2,n_out);
b_out = ones(1,n_out)*rand(1,1);
sig_a = 1;
learning_rate = 0.001;
limiar = 0.002;
%Helpful variables
max_epocas = 1000;
conj_entrada = [y1;y2;y3;y4;y5];
erros_epoca = [];
%Backpropagation
for epoch = 1:max_epocas
for i = 1:size(conj_entrada,2)
if i ==1
soma = 0;
else
end
enter = conj_entrada(:,i);
h1_in = [w1;b1]’*[enter;1];
h1_out = sig(h1_in,sig_a,’False’);
h2_in = [w2;b2]’*[h1_out;1];
h2_out = sig(h2_in,sig_a,’False’);
saida_in = [w_out;b_out]’*[h2_out;1];
saida_out = saida_in;
erro = y6(i) – saida_out;
soma = soma + (erro^2);
%Here starts the part of the code where the gradients are being
%calculated. Note that, here, I tried to folllow the chain rule.
%let me try to help in the understanding. Saida in portuguese is
%like output in english so when you read ,for example,
%d_erro_d_saida_out you need to know that this is the derivative of
%the error in relation with the output of the output layer. In the
%same way, entrada means input and pesos means weights
%output layer
%chain rule
d_erro_d_saida_out = -1*erro;
d_saida_d_entrada_out = 1; %linear
grad_saida = erro*d_saida_d_entrada_out;
d_entrada_d_pesos_out = h2_out;
d_erro_d_pesos_out = d_erro_d_saida_out*d_saida_d_entrada_out*d_entrada_d_pesos_out;
% Update the wights and bias
w_out = w_out -learning_rate*d_erro_d_pesos_out;
b_out = b_out -learning_rate*d_erro_d_saida_out*d_saida_d_entrada_out;
%Second hidden layer (The neighbor layer of the output layer)
%chain rule
d_erro_d_saida_h2 = -1*w_out*grad_saida;
d_saida_d_entrada_h2 = sig(h2_in,sig_a,’True’);
grad_h2 = sum(grad_saida)*d_saida_d_entrada_h2;
d_entrada_d_pesos_h2 = h1_out;
d_erro_d_pesos_h2 = d_entrada_d_pesos_h2*grad_h2′;
% Update the wights and bias
w2 = w2 -1*learning_rate*d_erro_d_pesos_h2;
b2 = b2 -1*learning_rate*sum(d_erro_d_saida_h2.*d_saida_d_entrada_h2,1);
%First hidden layer (The neighbor layer of the seccond hidden layer)
%chain rule
d_erro_d_saida_h1 = -1*w2*grad_h2;
d_saida_d_entrada_h1 = sig(h1_in,sig_a,’True’);
grad_h1 = sum(grad_h2)*d_saida_d_entrada_h1; %então daqui, tem que sair um 3×1
d_entrada_d_pesos_h1 = enter;
d_erro_d_pesos_h1 = d_entrada_d_pesos_h1*grad_h1′; %a segunda variável tem que resultar em um 1×3
% Update the wights and bias
w1 = w1 -1*learning_rate*d_erro_d_pesos_h1;
b1 = b1 -1*learning_rate*sum(d_erro_d_saida_h1.*d_saida_d_entrada_h1,1);
end
erro_atual = (soma/(2*size(x,2)));
erros_epoca = [erros_epoca;erro_atual];
if erros_epoca(epoch) <limiar
break
else
end
end
%testing the output of neural network
vetor_teste = 1:1000;
resposta_teste = zeros(1,size(vetor_teste,2));
for i = 1:size(vetor_teste,2)
enter_teste = conj_entrada(:,i);
h1_in_teste = [w1;b1]’*[enter_teste;1];
h1_out_teste = sig(h1_in_teste,sig_a,’False’);
h2_in_teste = [w2;b2]’*[h1_out_teste;1];
h2_out_teste = sig(h2_in_teste,sig_a,’False’);
saida_in_teste = [w_out;b_out]’*[h2_out_teste;1];
saida_out_teste = saida_in_teste; % a função de saída é linear;
resposta_teste(i) = saida_out_teste;
end
plot(1:size(erros_epoca,1),erros_epoca);
% plot(x,y3,’b’,vetor_teste,resposta_teste,’r’);
The code of my sigmoid activation function is below:
function [vetor_saida] = sig(vetor_entrada, const1, derivative)
if strcmp(derivative, ‘False’) == 1
vetor_saida = 1 ./ (1 + exp(-const1 * vetor_entrada));
else
sig_value = sig(vetor_entrada, const1, ‘False’);
vetor_saida = const1 * sig_value .* (1 – sig_value);
end
endI’m trying to do neural network with 2 hidden layers and one neuron in the output layer without any toolboxes and just with matrix and vectors multiplications. To do this, I created fictional simple data as below to help me in this task:
%Data
x = 1:1000;
y1 = sind(x);
y2 = sind(x+30);
y3 = cosd(x);
y4 = cosd(x+30);
y5 = cosd(x+45);
% y6 will be the desired output data taht I would like my neural network
% try to predict
y6 = (y1 + y2 + y3 + y4 + y5);
Then, I coded as I thought to be be the right way, but my neural network can´t reach a good result, as below:
My doubt is if the result isn´t good because my implementation isn´t right or because I need to add more mechanisms im my neural network (like momentum, regularization and etc.) ?
I will post my code below sorry about the naem of some variables, but originally I wrote this code in portuguese. I will comment the code to help undestand it
%Nueral network achictecture
n_h1 = 10;
n_h2 = 11;
n_out = 1;
%Adjustable parameters
w1 = rand(5,n_h1);
b1 = ones(1,n_h1)*rand(1,1);
w2 = rand(n_h1,n_h2);
b2 = ones(1,n_h2)*rand(1,1);
w_out = rand(n_h2,n_out);
b_out = ones(1,n_out)*rand(1,1);
sig_a = 1;
learning_rate = 0.001;
limiar = 0.002;
%Helpful variables
max_epocas = 1000;
conj_entrada = [y1;y2;y3;y4;y5];
erros_epoca = [];
%Backpropagation
for epoch = 1:max_epocas
for i = 1:size(conj_entrada,2)
if i ==1
soma = 0;
else
end
enter = conj_entrada(:,i);
h1_in = [w1;b1]’*[enter;1];
h1_out = sig(h1_in,sig_a,’False’);
h2_in = [w2;b2]’*[h1_out;1];
h2_out = sig(h2_in,sig_a,’False’);
saida_in = [w_out;b_out]’*[h2_out;1];
saida_out = saida_in;
erro = y6(i) – saida_out;
soma = soma + (erro^2);
%Here starts the part of the code where the gradients are being
%calculated. Note that, here, I tried to folllow the chain rule.
%let me try to help in the understanding. Saida in portuguese is
%like output in english so when you read ,for example,
%d_erro_d_saida_out you need to know that this is the derivative of
%the error in relation with the output of the output layer. In the
%same way, entrada means input and pesos means weights
%output layer
%chain rule
d_erro_d_saida_out = -1*erro;
d_saida_d_entrada_out = 1; %linear
grad_saida = erro*d_saida_d_entrada_out;
d_entrada_d_pesos_out = h2_out;
d_erro_d_pesos_out = d_erro_d_saida_out*d_saida_d_entrada_out*d_entrada_d_pesos_out;
% Update the wights and bias
w_out = w_out -learning_rate*d_erro_d_pesos_out;
b_out = b_out -learning_rate*d_erro_d_saida_out*d_saida_d_entrada_out;
%Second hidden layer (The neighbor layer of the output layer)
%chain rule
d_erro_d_saida_h2 = -1*w_out*grad_saida;
d_saida_d_entrada_h2 = sig(h2_in,sig_a,’True’);
grad_h2 = sum(grad_saida)*d_saida_d_entrada_h2;
d_entrada_d_pesos_h2 = h1_out;
d_erro_d_pesos_h2 = d_entrada_d_pesos_h2*grad_h2′;
% Update the wights and bias
w2 = w2 -1*learning_rate*d_erro_d_pesos_h2;
b2 = b2 -1*learning_rate*sum(d_erro_d_saida_h2.*d_saida_d_entrada_h2,1);
%First hidden layer (The neighbor layer of the seccond hidden layer)
%chain rule
d_erro_d_saida_h1 = -1*w2*grad_h2;
d_saida_d_entrada_h1 = sig(h1_in,sig_a,’True’);
grad_h1 = sum(grad_h2)*d_saida_d_entrada_h1; %então daqui, tem que sair um 3×1
d_entrada_d_pesos_h1 = enter;
d_erro_d_pesos_h1 = d_entrada_d_pesos_h1*grad_h1′; %a segunda variável tem que resultar em um 1×3
% Update the wights and bias
w1 = w1 -1*learning_rate*d_erro_d_pesos_h1;
b1 = b1 -1*learning_rate*sum(d_erro_d_saida_h1.*d_saida_d_entrada_h1,1);
end
erro_atual = (soma/(2*size(x,2)));
erros_epoca = [erros_epoca;erro_atual];
if erros_epoca(epoch) <limiar
break
else
end
end
%testing the output of neural network
vetor_teste = 1:1000;
resposta_teste = zeros(1,size(vetor_teste,2));
for i = 1:size(vetor_teste,2)
enter_teste = conj_entrada(:,i);
h1_in_teste = [w1;b1]’*[enter_teste;1];
h1_out_teste = sig(h1_in_teste,sig_a,’False’);
h2_in_teste = [w2;b2]’*[h1_out_teste;1];
h2_out_teste = sig(h2_in_teste,sig_a,’False’);
saida_in_teste = [w_out;b_out]’*[h2_out_teste;1];
saida_out_teste = saida_in_teste; % a função de saída é linear;
resposta_teste(i) = saida_out_teste;
end
plot(1:size(erros_epoca,1),erros_epoca);
% plot(x,y3,’b’,vetor_teste,resposta_teste,’r’);
The code of my sigmoid activation function is below:
function [vetor_saida] = sig(vetor_entrada, const1, derivative)
if strcmp(derivative, ‘False’) == 1
vetor_saida = 1 ./ (1 + exp(-const1 * vetor_entrada));
else
sig_value = sig(vetor_entrada, const1, ‘False’);
vetor_saida = const1 * sig_value .* (1 – sig_value);
end
end I’m trying to do neural network with 2 hidden layers and one neuron in the output layer without any toolboxes and just with matrix and vectors multiplications. To do this, I created fictional simple data as below to help me in this task:
%Data
x = 1:1000;
y1 = sind(x);
y2 = sind(x+30);
y3 = cosd(x);
y4 = cosd(x+30);
y5 = cosd(x+45);
% y6 will be the desired output data taht I would like my neural network
% try to predict
y6 = (y1 + y2 + y3 + y4 + y5);
Then, I coded as I thought to be be the right way, but my neural network can´t reach a good result, as below:
My doubt is if the result isn´t good because my implementation isn´t right or because I need to add more mechanisms im my neural network (like momentum, regularization and etc.) ?
I will post my code below sorry about the naem of some variables, but originally I wrote this code in portuguese. I will comment the code to help undestand it
%Nueral network achictecture
n_h1 = 10;
n_h2 = 11;
n_out = 1;
%Adjustable parameters
w1 = rand(5,n_h1);
b1 = ones(1,n_h1)*rand(1,1);
w2 = rand(n_h1,n_h2);
b2 = ones(1,n_h2)*rand(1,1);
w_out = rand(n_h2,n_out);
b_out = ones(1,n_out)*rand(1,1);
sig_a = 1;
learning_rate = 0.001;
limiar = 0.002;
%Helpful variables
max_epocas = 1000;
conj_entrada = [y1;y2;y3;y4;y5];
erros_epoca = [];
%Backpropagation
for epoch = 1:max_epocas
for i = 1:size(conj_entrada,2)
if i ==1
soma = 0;
else
end
enter = conj_entrada(:,i);
h1_in = [w1;b1]’*[enter;1];
h1_out = sig(h1_in,sig_a,’False’);
h2_in = [w2;b2]’*[h1_out;1];
h2_out = sig(h2_in,sig_a,’False’);
saida_in = [w_out;b_out]’*[h2_out;1];
saida_out = saida_in;
erro = y6(i) – saida_out;
soma = soma + (erro^2);
%Here starts the part of the code where the gradients are being
%calculated. Note that, here, I tried to folllow the chain rule.
%let me try to help in the understanding. Saida in portuguese is
%like output in english so when you read ,for example,
%d_erro_d_saida_out you need to know that this is the derivative of
%the error in relation with the output of the output layer. In the
%same way, entrada means input and pesos means weights
%output layer
%chain rule
d_erro_d_saida_out = -1*erro;
d_saida_d_entrada_out = 1; %linear
grad_saida = erro*d_saida_d_entrada_out;
d_entrada_d_pesos_out = h2_out;
d_erro_d_pesos_out = d_erro_d_saida_out*d_saida_d_entrada_out*d_entrada_d_pesos_out;
% Update the wights and bias
w_out = w_out -learning_rate*d_erro_d_pesos_out;
b_out = b_out -learning_rate*d_erro_d_saida_out*d_saida_d_entrada_out;
%Second hidden layer (The neighbor layer of the output layer)
%chain rule
d_erro_d_saida_h2 = -1*w_out*grad_saida;
d_saida_d_entrada_h2 = sig(h2_in,sig_a,’True’);
grad_h2 = sum(grad_saida)*d_saida_d_entrada_h2;
d_entrada_d_pesos_h2 = h1_out;
d_erro_d_pesos_h2 = d_entrada_d_pesos_h2*grad_h2′;
% Update the wights and bias
w2 = w2 -1*learning_rate*d_erro_d_pesos_h2;
b2 = b2 -1*learning_rate*sum(d_erro_d_saida_h2.*d_saida_d_entrada_h2,1);
%First hidden layer (The neighbor layer of the seccond hidden layer)
%chain rule
d_erro_d_saida_h1 = -1*w2*grad_h2;
d_saida_d_entrada_h1 = sig(h1_in,sig_a,’True’);
grad_h1 = sum(grad_h2)*d_saida_d_entrada_h1; %então daqui, tem que sair um 3×1
d_entrada_d_pesos_h1 = enter;
d_erro_d_pesos_h1 = d_entrada_d_pesos_h1*grad_h1′; %a segunda variável tem que resultar em um 1×3
% Update the wights and bias
w1 = w1 -1*learning_rate*d_erro_d_pesos_h1;
b1 = b1 -1*learning_rate*sum(d_erro_d_saida_h1.*d_saida_d_entrada_h1,1);
end
erro_atual = (soma/(2*size(x,2)));
erros_epoca = [erros_epoca;erro_atual];
if erros_epoca(epoch) <limiar
break
else
end
end
%testing the output of neural network
vetor_teste = 1:1000;
resposta_teste = zeros(1,size(vetor_teste,2));
for i = 1:size(vetor_teste,2)
enter_teste = conj_entrada(:,i);
h1_in_teste = [w1;b1]’*[enter_teste;1];
h1_out_teste = sig(h1_in_teste,sig_a,’False’);
h2_in_teste = [w2;b2]’*[h1_out_teste;1];
h2_out_teste = sig(h2_in_teste,sig_a,’False’);
saida_in_teste = [w_out;b_out]’*[h2_out_teste;1];
saida_out_teste = saida_in_teste; % a função de saída é linear;
resposta_teste(i) = saida_out_teste;
end
plot(1:size(erros_epoca,1),erros_epoca);
% plot(x,y3,’b’,vetor_teste,resposta_teste,’r’);
The code of my sigmoid activation function is below:
function [vetor_saida] = sig(vetor_entrada, const1, derivative)
if strcmp(derivative, ‘False’) == 1
vetor_saida = 1 ./ (1 + exp(-const1 * vetor_entrada));
else
sig_value = sig(vetor_entrada, const1, ‘False’);
vetor_saida = const1 * sig_value .* (1 – sig_value);
end
end neural network, backpropagation MATLAB Answers — New Questions
mex_C_win64 vs mingw64
I am having trouble executing mex files. Currently my compiler configurations looks like this:
>> mex.getCompilerConfigurations(‘C’)
ans =
CompilerConfiguration with properties:
Name: ‘MinGW64 Compiler (C)’
Manufacturer: ‘GNU’
Language: ‘C’
Version: ‘6.3.0’
Location: ‘C:MinGW8mingw64’
ShortName: ‘mingw64’
Priority: ‘E’
Details: [1×1 mex.CompilerConfigurationDetails]
LinkerName: ‘C:MinGW8mingw64bingcc’
LinkerVersion: ”
MexOpt: ‘C:Users<Username deducted>AppDataRoamingMathWorksMATLABR2022bmex_C_win64.xml’
However, other people in my organization mostly have MexOpt like so:
MexOpt: ‘C:Program FilesMATLABR2022bbinwin64mexoptsmingw64.xml’
Is it possible to align with others without manually editing compiler configs, if not how can I manually fix this?I am having trouble executing mex files. Currently my compiler configurations looks like this:
>> mex.getCompilerConfigurations(‘C’)
ans =
CompilerConfiguration with properties:
Name: ‘MinGW64 Compiler (C)’
Manufacturer: ‘GNU’
Language: ‘C’
Version: ‘6.3.0’
Location: ‘C:MinGW8mingw64’
ShortName: ‘mingw64’
Priority: ‘E’
Details: [1×1 mex.CompilerConfigurationDetails]
LinkerName: ‘C:MinGW8mingw64bingcc’
LinkerVersion: ”
MexOpt: ‘C:Users<Username deducted>AppDataRoamingMathWorksMATLABR2022bmex_C_win64.xml’
However, other people in my organization mostly have MexOpt like so:
MexOpt: ‘C:Program FilesMATLABR2022bbinwin64mexoptsmingw64.xml’
Is it possible to align with others without manually editing compiler configs, if not how can I manually fix this? I am having trouble executing mex files. Currently my compiler configurations looks like this:
>> mex.getCompilerConfigurations(‘C’)
ans =
CompilerConfiguration with properties:
Name: ‘MinGW64 Compiler (C)’
Manufacturer: ‘GNU’
Language: ‘C’
Version: ‘6.3.0’
Location: ‘C:MinGW8mingw64’
ShortName: ‘mingw64’
Priority: ‘E’
Details: [1×1 mex.CompilerConfigurationDetails]
LinkerName: ‘C:MinGW8mingw64bingcc’
LinkerVersion: ”
MexOpt: ‘C:Users<Username deducted>AppDataRoamingMathWorksMATLABR2022bmex_C_win64.xml’
However, other people in my organization mostly have MexOpt like so:
MexOpt: ‘C:Program FilesMATLABR2022bbinwin64mexoptsmingw64.xml’
Is it possible to align with others without manually editing compiler configs, if not how can I manually fix this? mex, compiler MATLAB Answers — New Questions
Why do the same system matlab and simulink get different step responses?
As I asked, I want to design a fractional pid controller for a model. Unfortunately, the results I got with step in matlab are quite different from those in simulink
.
Here the orange line is the output and the blue line is the offset,Now let me show you the situation of matlab.The specific parameters of the controller are consistent with the code below
cs=fopid(9.503084707494814e+03,1.889631254823942e+02,2.304958553299564e+02,0.058440555124293,1.558103446462550);%This is parameter of controller
gs=tf(118700,[1 1085 1224000]);%This is the transfer function of the controlled object
step(feedback(cs*gs,1))%Step Response of Closed-loop Transfer Function
This is the general situation. I feel confused now.As I asked, I want to design a fractional pid controller for a model. Unfortunately, the results I got with step in matlab are quite different from those in simulink
.
Here the orange line is the output and the blue line is the offset,Now let me show you the situation of matlab.The specific parameters of the controller are consistent with the code below
cs=fopid(9.503084707494814e+03,1.889631254823942e+02,2.304958553299564e+02,0.058440555124293,1.558103446462550);%This is parameter of controller
gs=tf(118700,[1 1085 1224000]);%This is the transfer function of the controlled object
step(feedback(cs*gs,1))%Step Response of Closed-loop Transfer Function
This is the general situation. I feel confused now. As I asked, I want to design a fractional pid controller for a model. Unfortunately, the results I got with step in matlab are quite different from those in simulink
.
Here the orange line is the output and the blue line is the offset,Now let me show you the situation of matlab.The specific parameters of the controller are consistent with the code below
cs=fopid(9.503084707494814e+03,1.889631254823942e+02,2.304958553299564e+02,0.058440555124293,1.558103446462550);%This is parameter of controller
gs=tf(118700,[1 1085 1224000]);%This is the transfer function of the controlled object
step(feedback(cs*gs,1))%Step Response of Closed-loop Transfer Function
This is the general situation. I feel confused now. matlab, simulink MATLAB Answers — New Questions
Calculating number of monthly events
Hi
I have events time series. (see attached)
How I can calculate monthly number of events.
Thanks for your help!Hi
I have events time series. (see attached)
How I can calculate monthly number of events.
Thanks for your help! Hi
I have events time series. (see attached)
How I can calculate monthly number of events.
Thanks for your help! calculating number of monthly events MATLAB Answers — New Questions
roc plot
area = roc(fileName,exp)
%
% fileName: The name of the output file. It is an image
% exp: a structure representing an experiment with three fields
% – exp.name: a string specifying the experiment name
% – exp.positive_n: the number of positive samples in the experiment
% – exp.likelihoods: likelihoods of each sample where the first
% exp.positive_n number of likelihoods belongs to the positive
% samples while others belong to the negative samples.
% area: a 1×1-dimensional cell array of the area under the roc curve.
true positive,false positive values of ground truth,edge detected image was calculated…then how apply these values to roc program…??????area = roc(fileName,exp)
%
% fileName: The name of the output file. It is an image
% exp: a structure representing an experiment with three fields
% – exp.name: a string specifying the experiment name
% – exp.positive_n: the number of positive samples in the experiment
% – exp.likelihoods: likelihoods of each sample where the first
% exp.positive_n number of likelihoods belongs to the positive
% samples while others belong to the negative samples.
% area: a 1×1-dimensional cell array of the area under the roc curve.
true positive,false positive values of ground truth,edge detected image was calculated…then how apply these values to roc program…?????? area = roc(fileName,exp)
%
% fileName: The name of the output file. It is an image
% exp: a structure representing an experiment with three fields
% – exp.name: a string specifying the experiment name
% – exp.positive_n: the number of positive samples in the experiment
% – exp.likelihoods: likelihoods of each sample where the first
% exp.positive_n number of likelihoods belongs to the positive
% samples while others belong to the negative samples.
% area: a 1×1-dimensional cell array of the area under the roc curve.
true positive,false positive values of ground truth,edge detected image was calculated…then how apply these values to roc program…?????? roc MATLAB Answers — New Questions
Is there a way to model sound wave interference patterns using Phased Array System Toolbox?
I am trying to find a way to model the constructive/destructive interference patterns for sound speakers in a room, i.e. concentrating sound in a specific part of the room through creating constructive interference from several non-directional (aka regular) speakers. I have been looking at the Phased Array System Toolbox (because I am thinking about an array of speakers) and think that might be the best fit for what I am looking for. Not sure if there is another Toolbox out there that does similar things or the Phased Array System is the best fit for this? Thank you!I am trying to find a way to model the constructive/destructive interference patterns for sound speakers in a room, i.e. concentrating sound in a specific part of the room through creating constructive interference from several non-directional (aka regular) speakers. I have been looking at the Phased Array System Toolbox (because I am thinking about an array of speakers) and think that might be the best fit for what I am looking for. Not sure if there is another Toolbox out there that does similar things or the Phased Array System is the best fit for this? Thank you! I am trying to find a way to model the constructive/destructive interference patterns for sound speakers in a room, i.e. concentrating sound in a specific part of the room through creating constructive interference from several non-directional (aka regular) speakers. I have been looking at the Phased Array System Toolbox (because I am thinking about an array of speakers) and think that might be the best fit for what I am looking for. Not sure if there is another Toolbox out there that does similar things or the Phased Array System is the best fit for this? Thank you! acoustic modeling, interference patterns MATLAB Answers — New Questions
Error in installing an apps
I have a problem installing apps, the command windows gives me this:
com.mathworks.jmi.MatlabException: The specified path is invalid.
at com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
at com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:265)
at com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:120)
at com.mathworks.jmi.Matlab.mtFeval(Matlab.java:1541)
at com.mathworks.jmi.MatlabWorker.feval(MatlabWorker.java:197)
at com.mathworks.appmanagement.InstallAppMatlabWorker.doOnMatlabThread(InstallAppMatlabWorker.java:20)
at com.mathworks.appmanagement.InstallAppMatlabWorker.doOnMatlabThread(InstallAppMatlabWorker.java:7)
at com.mathworks.appmanagement.AbstractAppManagementMatlabWorker.runOnMatlabThread(AbstractAppManagementMatlabWorker.java:21)
at com.mathworks.jmi.MatlabWorker$2.run(MatlabWorker.java:79)
at com.mathworks.jmi.NativeMatlab.dispatchMTRequests(NativeMatlab.java:440)
What should I do?I have a problem installing apps, the command windows gives me this:
com.mathworks.jmi.MatlabException: The specified path is invalid.
at com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
at com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:265)
at com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:120)
at com.mathworks.jmi.Matlab.mtFeval(Matlab.java:1541)
at com.mathworks.jmi.MatlabWorker.feval(MatlabWorker.java:197)
at com.mathworks.appmanagement.InstallAppMatlabWorker.doOnMatlabThread(InstallAppMatlabWorker.java:20)
at com.mathworks.appmanagement.InstallAppMatlabWorker.doOnMatlabThread(InstallAppMatlabWorker.java:7)
at com.mathworks.appmanagement.AbstractAppManagementMatlabWorker.runOnMatlabThread(AbstractAppManagementMatlabWorker.java:21)
at com.mathworks.jmi.MatlabWorker$2.run(MatlabWorker.java:79)
at com.mathworks.jmi.NativeMatlab.dispatchMTRequests(NativeMatlab.java:440)
What should I do? I have a problem installing apps, the command windows gives me this:
com.mathworks.jmi.MatlabException: The specified path is invalid.
at com.mathworks.jmi.NativeMatlab.SendMatlabMessage(Native Method)
at com.mathworks.jmi.NativeMatlab.sendMatlabMessage(NativeMatlab.java:265)
at com.mathworks.jmi.MatlabLooper.sendMatlabMessage(MatlabLooper.java:120)
at com.mathworks.jmi.Matlab.mtFeval(Matlab.java:1541)
at com.mathworks.jmi.MatlabWorker.feval(MatlabWorker.java:197)
at com.mathworks.appmanagement.InstallAppMatlabWorker.doOnMatlabThread(InstallAppMatlabWorker.java:20)
at com.mathworks.appmanagement.InstallAppMatlabWorker.doOnMatlabThread(InstallAppMatlabWorker.java:7)
at com.mathworks.appmanagement.AbstractAppManagementMatlabWorker.runOnMatlabThread(AbstractAppManagementMatlabWorker.java:21)
at com.mathworks.jmi.MatlabWorker$2.run(MatlabWorker.java:79)
at com.mathworks.jmi.NativeMatlab.dispatchMTRequests(NativeMatlab.java:440)
What should I do? install, apps MATLAB Answers — New Questions
how to create complete binary tree in matlab of sensor nodes
iam new to matlab please help me to create complete binary tree in matlabiam new to matlab please help me to create complete binary tree in matlab iam new to matlab please help me to create complete binary tree in matlab text, node creation MATLAB Answers — New Questions
How can I add new properties to a pointcloud?
I want to add a new property to a pointcloud, which is not in the standard properties of pointcloud.
I’ve got a pointcloud with one color image, from where I extract the Color inforamtion, and one NIR image, from where I get a greyscale value for each point, and I want to have every point to have an additional Property called ‘NIR’ with this value.
I tried :
pointcloud=pointCloud(posxyz,’Intensity’,intensityvalue,’NIR’,nirvalue)
Matlab gives me the following error:
Error using pointCloud>validateAndParseInputs (line 818)
‘NIR’ is not a recognized parameter. For a list of valid name-value pair arguments, see the
documentation for this function.
Error in pointCloud (line 142)
[xyzPoints, C, nv, I] = validateAndParseInputs(varargin{:});I want to add a new property to a pointcloud, which is not in the standard properties of pointcloud.
I’ve got a pointcloud with one color image, from where I extract the Color inforamtion, and one NIR image, from where I get a greyscale value for each point, and I want to have every point to have an additional Property called ‘NIR’ with this value.
I tried :
pointcloud=pointCloud(posxyz,’Intensity’,intensityvalue,’NIR’,nirvalue)
Matlab gives me the following error:
Error using pointCloud>validateAndParseInputs (line 818)
‘NIR’ is not a recognized parameter. For a list of valid name-value pair arguments, see the
documentation for this function.
Error in pointCloud (line 142)
[xyzPoints, C, nv, I] = validateAndParseInputs(varargin{:}); I want to add a new property to a pointcloud, which is not in the standard properties of pointcloud.
I’ve got a pointcloud with one color image, from where I extract the Color inforamtion, and one NIR image, from where I get a greyscale value for each point, and I want to have every point to have an additional Property called ‘NIR’ with this value.
I tried :
pointcloud=pointCloud(posxyz,’Intensity’,intensityvalue,’NIR’,nirvalue)
Matlab gives me the following error:
Error using pointCloud>validateAndParseInputs (line 818)
‘NIR’ is not a recognized parameter. For a list of valid name-value pair arguments, see the
documentation for this function.
Error in pointCloud (line 142)
[xyzPoints, C, nv, I] = validateAndParseInputs(varargin{:}); pointcloud, porperty MATLAB Answers — New Questions
GUI plot
Hie guys, i imported an excel file into my gui and i plotted it out together with the vertical lines that i need. However, with the same code, it does not work for the other axes in the same GUI.Below are my codes,
——–first axes code———-
plot(handles.axes1,c,d);
hold on;
XData=get(get(handles.axes1,’children’),’XData’);
YData=get(get(handles.axes1,’children’),’YData’);
y_BPFO = interp1(XData,YData,BPFO);
t=get(handles.axes1,’ylim’);
plot([BPFO BPFO],t,’-y’);
———–second axes(in the same GUI)——–
plot(handles.axes2,c,d);
hold on;
XData1=get(get(handles.axes2,’children’),’XData’);
YData1=get(get(handles.axes2,’children’),’YData’);
y_BPFO1 = interp1(XData1,YData1,BPFO1);
q=get(handles.axes2,’ylim’);
plot([BPFO1 BPFO1],q,’-y’);
——————————————–
I manage to get the first plot with all the data and vertical lines.
However, i cant get the plot for the second axes. Can someone help me out?
Regards,
EanHie guys, i imported an excel file into my gui and i plotted it out together with the vertical lines that i need. However, with the same code, it does not work for the other axes in the same GUI.Below are my codes,
——–first axes code———-
plot(handles.axes1,c,d);
hold on;
XData=get(get(handles.axes1,’children’),’XData’);
YData=get(get(handles.axes1,’children’),’YData’);
y_BPFO = interp1(XData,YData,BPFO);
t=get(handles.axes1,’ylim’);
plot([BPFO BPFO],t,’-y’);
———–second axes(in the same GUI)——–
plot(handles.axes2,c,d);
hold on;
XData1=get(get(handles.axes2,’children’),’XData’);
YData1=get(get(handles.axes2,’children’),’YData’);
y_BPFO1 = interp1(XData1,YData1,BPFO1);
q=get(handles.axes2,’ylim’);
plot([BPFO1 BPFO1],q,’-y’);
——————————————–
I manage to get the first plot with all the data and vertical lines.
However, i cant get the plot for the second axes. Can someone help me out?
Regards,
Ean Hie guys, i imported an excel file into my gui and i plotted it out together with the vertical lines that i need. However, with the same code, it does not work for the other axes in the same GUI.Below are my codes,
——–first axes code———-
plot(handles.axes1,c,d);
hold on;
XData=get(get(handles.axes1,’children’),’XData’);
YData=get(get(handles.axes1,’children’),’YData’);
y_BPFO = interp1(XData,YData,BPFO);
t=get(handles.axes1,’ylim’);
plot([BPFO BPFO],t,’-y’);
———–second axes(in the same GUI)——–
plot(handles.axes2,c,d);
hold on;
XData1=get(get(handles.axes2,’children’),’XData’);
YData1=get(get(handles.axes2,’children’),’YData’);
y_BPFO1 = interp1(XData1,YData1,BPFO1);
q=get(handles.axes2,’ylim’);
plot([BPFO1 BPFO1],q,’-y’);
——————————————–
I manage to get the first plot with all the data and vertical lines.
However, i cant get the plot for the second axes. Can someone help me out?
Regards,
Ean plot MATLAB Answers — New Questions
CCDF Plot
Dose any one knows to generate CDDF polots for OFDM …plese help..strugling with itDose any one knows to generate CDDF polots for OFDM …plese help..strugling with it Dose any one knows to generate CDDF polots for OFDM …plese help..strugling with it ccdf plot, ofdm MATLAB Answers — New Questions
contourm plotting
I have a text file containing Lats and Lons. I want to plot a geomap with 0.1 deg grid. Then the map use a color bar, showing the number of occurrences of the Lats and Longs.I have a text file containing Lats and Lons. I want to plot a geomap with 0.1 deg grid. Then the map use a color bar, showing the number of occurrences of the Lats and Longs. I have a text file containing Lats and Lons. I want to plot a geomap with 0.1 deg grid. Then the map use a color bar, showing the number of occurrences of the Lats and Longs. contourm MATLAB Answers — New Questions
why do I receive PSB option menu block block (mask) does not have a parameter named ‘MechanicalLoad’
when I compiled my mlapp with simulink model,it has warning me PSB option menu block block (mask) does not have a parameter named ‘MechanicalLoad’。when I compiled my mlapp with simulink model,it has warning me PSB option menu block block (mask) does not have a parameter named ‘MechanicalLoad’。 when I compiled my mlapp with simulink model,it has warning me PSB option menu block block (mask) does not have a parameter named ‘MechanicalLoad’。 simulink app designer MATLAB Answers — New Questions
How to create a custom profile in matlab plots
Hello Everyone,
I am trying to create a profile based on user defined inputs. The profile consists of different modes each having a certain duration and order as defined by the user.
I have uploaded a picture which shows how i want the profile to look like.
Additionally i have coded to some extent, but i am struggling to get it right.
Also i would like to break the number of cycles for dynamic elements and use ‘…’ to show continuity. However, on th etime axis i would like to have the actual value instead of shortened periods by discontinuity.
I kindly request for support and i thank you in advance.
Vconst.val = [1, 0.85, 0.6, 0.4];
Vconst.txt = {‘OCV’, ‘Idle’, ‘Mid Load’, ‘High Load’};
Vdyn.val = [0.8, 0.7, 0.8, 0.5, 1.5, 1];
Vdyn.txt = {‘Dynamic Low’, ‘Dyn low trough’, ‘Dynamic High’, ‘Dyn high trough’, ‘SUSD’, ‘SUSD trough’};
% Define the order of phases and durations
order = {‘OCV’, ‘SUSD’, ‘OCV’, ‘Mid Load’, ‘High Load’, ‘Mid Load’, ‘Dynamic Low’, ‘Mid Load’, ‘Dynamic High’, ‘OCV’}; % duration in s for Vconst elements, nr. of cycles for Vdyn elements
durations = [100, 10, 200, 100, 50, 50, 4, 50, 4, 100]; % Corresponding durations in seconds or cycles
% Initialize time and voltage vectors
time = [];
voltage = [];
current_time = 0;
% Generate time and voltage vectors
for i = 1:length(order)
phase = order{i};
duration = durations(i);
t = current_time + (0:0.1:duration);
if ismember(phase, {‘OCV’, ‘Idle’, ‘Mid Load’, ‘High Load’})
% Constant phases
t = current_time + (0:0.1:duration);
V_idx = find(strcmp(Vconst.txt, phase));
v = Vconst.val(V_idx) * ones(size(t));
time_act(i) = t(end);
else
% Dynamic phases
n_cycles = duration; % Number of dynamic cycles
t_dynamic_full = [];
v_dynamic_full = [];
Vdyn_idx = find(strcmp(Vdyn.txt, phase));
peak_height = Vdyn.val(Vdyn_idx);
trough_height = Vdyn.val(Vdyn_idx + 1);
nr_pts = 50;
for j = 1:n_cycles
t_cycle = current_time + (0:1:nr_pts);
tri_wave = sawtooth(2 * pi * (1/nr_pts) * (t_cycle – current_time), 0.5);
tri_wave = (peak_height – trough_height) * tri_wave / 2 + (peak_height + trough_height) / 2;
tri_wave(tri_wave > peak_height) = peak_height;
tri_wave(tri_wave < trough_height) = trough_height;
t_dynamic_full = [t_dynamic_full, t_cycle];
v_dynamic_full = [v_dynamic_full, tri_wave];
current_time = t_cycle(end);
end
time_act(i) = t_dynamic_full(end);
if n_cycles > 3
t_dynamic_1 = t_dynamic_full(1:nr_pts*2+2);
v_dynamic_1 = v_dynamic_full(1:nr_pts*2+2);
t_dynamic_2 = t_dynamic_full(nr_pts*3+3:nr_pts*4+4);
v_dynamic_2 = v_dynamic_full(nr_pts*3+3:nr_pts*4+4);
t_continuity = t_dynamic_full(nr_pts*2+4:nr_pts*3+2);
v_continuity = NaN * ones(size(t_continuity));
t = [t_dynamic_1, t_continuity, t_dynamic_2];
v = [v_dynamic_1, v_continuity, v_dynamic_2];
else
t = t_dynamic_full;
v = v_dynamic_full;
end
end
time = [time, t];
voltage = [voltage, v];
current_time = t(end);
if i>1
time_act(i) = time_act(i)+time_act(i-1);
else
end
end
% Plot the voltage over time
figure;
plot(time, voltage, ‘LineWidth’, 1.5);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
title(‘User Defined Plot with Flexible Phase Order and Durations’);
grid on;
ylim([0 2])
yticklabels([])Hello Everyone,
I am trying to create a profile based on user defined inputs. The profile consists of different modes each having a certain duration and order as defined by the user.
I have uploaded a picture which shows how i want the profile to look like.
Additionally i have coded to some extent, but i am struggling to get it right.
Also i would like to break the number of cycles for dynamic elements and use ‘…’ to show continuity. However, on th etime axis i would like to have the actual value instead of shortened periods by discontinuity.
I kindly request for support and i thank you in advance.
Vconst.val = [1, 0.85, 0.6, 0.4];
Vconst.txt = {‘OCV’, ‘Idle’, ‘Mid Load’, ‘High Load’};
Vdyn.val = [0.8, 0.7, 0.8, 0.5, 1.5, 1];
Vdyn.txt = {‘Dynamic Low’, ‘Dyn low trough’, ‘Dynamic High’, ‘Dyn high trough’, ‘SUSD’, ‘SUSD trough’};
% Define the order of phases and durations
order = {‘OCV’, ‘SUSD’, ‘OCV’, ‘Mid Load’, ‘High Load’, ‘Mid Load’, ‘Dynamic Low’, ‘Mid Load’, ‘Dynamic High’, ‘OCV’}; % duration in s for Vconst elements, nr. of cycles for Vdyn elements
durations = [100, 10, 200, 100, 50, 50, 4, 50, 4, 100]; % Corresponding durations in seconds or cycles
% Initialize time and voltage vectors
time = [];
voltage = [];
current_time = 0;
% Generate time and voltage vectors
for i = 1:length(order)
phase = order{i};
duration = durations(i);
t = current_time + (0:0.1:duration);
if ismember(phase, {‘OCV’, ‘Idle’, ‘Mid Load’, ‘High Load’})
% Constant phases
t = current_time + (0:0.1:duration);
V_idx = find(strcmp(Vconst.txt, phase));
v = Vconst.val(V_idx) * ones(size(t));
time_act(i) = t(end);
else
% Dynamic phases
n_cycles = duration; % Number of dynamic cycles
t_dynamic_full = [];
v_dynamic_full = [];
Vdyn_idx = find(strcmp(Vdyn.txt, phase));
peak_height = Vdyn.val(Vdyn_idx);
trough_height = Vdyn.val(Vdyn_idx + 1);
nr_pts = 50;
for j = 1:n_cycles
t_cycle = current_time + (0:1:nr_pts);
tri_wave = sawtooth(2 * pi * (1/nr_pts) * (t_cycle – current_time), 0.5);
tri_wave = (peak_height – trough_height) * tri_wave / 2 + (peak_height + trough_height) / 2;
tri_wave(tri_wave > peak_height) = peak_height;
tri_wave(tri_wave < trough_height) = trough_height;
t_dynamic_full = [t_dynamic_full, t_cycle];
v_dynamic_full = [v_dynamic_full, tri_wave];
current_time = t_cycle(end);
end
time_act(i) = t_dynamic_full(end);
if n_cycles > 3
t_dynamic_1 = t_dynamic_full(1:nr_pts*2+2);
v_dynamic_1 = v_dynamic_full(1:nr_pts*2+2);
t_dynamic_2 = t_dynamic_full(nr_pts*3+3:nr_pts*4+4);
v_dynamic_2 = v_dynamic_full(nr_pts*3+3:nr_pts*4+4);
t_continuity = t_dynamic_full(nr_pts*2+4:nr_pts*3+2);
v_continuity = NaN * ones(size(t_continuity));
t = [t_dynamic_1, t_continuity, t_dynamic_2];
v = [v_dynamic_1, v_continuity, v_dynamic_2];
else
t = t_dynamic_full;
v = v_dynamic_full;
end
end
time = [time, t];
voltage = [voltage, v];
current_time = t(end);
if i>1
time_act(i) = time_act(i)+time_act(i-1);
else
end
end
% Plot the voltage over time
figure;
plot(time, voltage, ‘LineWidth’, 1.5);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
title(‘User Defined Plot with Flexible Phase Order and Durations’);
grid on;
ylim([0 2])
yticklabels([]) Hello Everyone,
I am trying to create a profile based on user defined inputs. The profile consists of different modes each having a certain duration and order as defined by the user.
I have uploaded a picture which shows how i want the profile to look like.
Additionally i have coded to some extent, but i am struggling to get it right.
Also i would like to break the number of cycles for dynamic elements and use ‘…’ to show continuity. However, on th etime axis i would like to have the actual value instead of shortened periods by discontinuity.
I kindly request for support and i thank you in advance.
Vconst.val = [1, 0.85, 0.6, 0.4];
Vconst.txt = {‘OCV’, ‘Idle’, ‘Mid Load’, ‘High Load’};
Vdyn.val = [0.8, 0.7, 0.8, 0.5, 1.5, 1];
Vdyn.txt = {‘Dynamic Low’, ‘Dyn low trough’, ‘Dynamic High’, ‘Dyn high trough’, ‘SUSD’, ‘SUSD trough’};
% Define the order of phases and durations
order = {‘OCV’, ‘SUSD’, ‘OCV’, ‘Mid Load’, ‘High Load’, ‘Mid Load’, ‘Dynamic Low’, ‘Mid Load’, ‘Dynamic High’, ‘OCV’}; % duration in s for Vconst elements, nr. of cycles for Vdyn elements
durations = [100, 10, 200, 100, 50, 50, 4, 50, 4, 100]; % Corresponding durations in seconds or cycles
% Initialize time and voltage vectors
time = [];
voltage = [];
current_time = 0;
% Generate time and voltage vectors
for i = 1:length(order)
phase = order{i};
duration = durations(i);
t = current_time + (0:0.1:duration);
if ismember(phase, {‘OCV’, ‘Idle’, ‘Mid Load’, ‘High Load’})
% Constant phases
t = current_time + (0:0.1:duration);
V_idx = find(strcmp(Vconst.txt, phase));
v = Vconst.val(V_idx) * ones(size(t));
time_act(i) = t(end);
else
% Dynamic phases
n_cycles = duration; % Number of dynamic cycles
t_dynamic_full = [];
v_dynamic_full = [];
Vdyn_idx = find(strcmp(Vdyn.txt, phase));
peak_height = Vdyn.val(Vdyn_idx);
trough_height = Vdyn.val(Vdyn_idx + 1);
nr_pts = 50;
for j = 1:n_cycles
t_cycle = current_time + (0:1:nr_pts);
tri_wave = sawtooth(2 * pi * (1/nr_pts) * (t_cycle – current_time), 0.5);
tri_wave = (peak_height – trough_height) * tri_wave / 2 + (peak_height + trough_height) / 2;
tri_wave(tri_wave > peak_height) = peak_height;
tri_wave(tri_wave < trough_height) = trough_height;
t_dynamic_full = [t_dynamic_full, t_cycle];
v_dynamic_full = [v_dynamic_full, tri_wave];
current_time = t_cycle(end);
end
time_act(i) = t_dynamic_full(end);
if n_cycles > 3
t_dynamic_1 = t_dynamic_full(1:nr_pts*2+2);
v_dynamic_1 = v_dynamic_full(1:nr_pts*2+2);
t_dynamic_2 = t_dynamic_full(nr_pts*3+3:nr_pts*4+4);
v_dynamic_2 = v_dynamic_full(nr_pts*3+3:nr_pts*4+4);
t_continuity = t_dynamic_full(nr_pts*2+4:nr_pts*3+2);
v_continuity = NaN * ones(size(t_continuity));
t = [t_dynamic_1, t_continuity, t_dynamic_2];
v = [v_dynamic_1, v_continuity, v_dynamic_2];
else
t = t_dynamic_full;
v = v_dynamic_full;
end
end
time = [time, t];
voltage = [voltage, v];
current_time = t(end);
if i>1
time_act(i) = time_act(i)+time_act(i-1);
else
end
end
% Plot the voltage over time
figure;
plot(time, voltage, ‘LineWidth’, 1.5);
xlabel(‘Time (s)’);
ylabel(‘Voltage (V)’);
title(‘User Defined Plot with Flexible Phase Order and Durations’);
grid on;
ylim([0 2])
yticklabels([]) plot, profile creation, data handling MATLAB Answers — New Questions
polar plot
Hi everyone!
I want to plot a function like that:
<http://i44.tinypic.com/hu3v2q.jpg>
the plot is in fig. 138 (c) and its expression in Ms.
What’s the code?
because, I think, there is a scale factor, I use this code:
ts=linspace(0,2*pi,500);
Ms = 1-ts.*sin(ts)-0.5*cos(ts);
polar(ts,Ms)
but this generates a wrong plot.
How can I do this?
Thanks a lot for your answer!
PincoHi everyone!
I want to plot a function like that:
<http://i44.tinypic.com/hu3v2q.jpg>
the plot is in fig. 138 (c) and its expression in Ms.
What’s the code?
because, I think, there is a scale factor, I use this code:
ts=linspace(0,2*pi,500);
Ms = 1-ts.*sin(ts)-0.5*cos(ts);
polar(ts,Ms)
but this generates a wrong plot.
How can I do this?
Thanks a lot for your answer!
Pinco Hi everyone!
I want to plot a function like that:
<http://i44.tinypic.com/hu3v2q.jpg>
the plot is in fig. 138 (c) and its expression in Ms.
What’s the code?
because, I think, there is a scale factor, I use this code:
ts=linspace(0,2*pi,500);
Ms = 1-ts.*sin(ts)-0.5*cos(ts);
polar(ts,Ms)
but this generates a wrong plot.
How can I do this?
Thanks a lot for your answer!
Pinco polar, plot MATLAB Answers — New Questions
Application of multistage decimator filter to signal
Dear all
We had a piece of code to decimate data (decimation ratio (dec_factor) > 13) that read:
Hfd=fdesign.decimator(dec_factor,’Nyquist’);
Hm=design(Hfd,’multistage’);
signal_output=filter(Hm,signal_input);
Matlad is warning that
Warning: Multistage design using fdesign.decimator will be removed. Use designMultistageDecimator instead.
So we are replacing the codewith:
Astop = 80;
TW = 0.03*fs_sampling/2;
Hm=designMultistageDecimator(dec_factor,fs_sampling,TW,Astop,’CostMethod’,’design’);
We don´t know what to do with Hm in order to apply the filter to get signal_input.
Any ideas?
Thanks in advanceDear all
We had a piece of code to decimate data (decimation ratio (dec_factor) > 13) that read:
Hfd=fdesign.decimator(dec_factor,’Nyquist’);
Hm=design(Hfd,’multistage’);
signal_output=filter(Hm,signal_input);
Matlad is warning that
Warning: Multistage design using fdesign.decimator will be removed. Use designMultistageDecimator instead.
So we are replacing the codewith:
Astop = 80;
TW = 0.03*fs_sampling/2;
Hm=designMultistageDecimator(dec_factor,fs_sampling,TW,Astop,’CostMethod’,’design’);
We don´t know what to do with Hm in order to apply the filter to get signal_input.
Any ideas?
Thanks in advance Dear all
We had a piece of code to decimate data (decimation ratio (dec_factor) > 13) that read:
Hfd=fdesign.decimator(dec_factor,’Nyquist’);
Hm=design(Hfd,’multistage’);
signal_output=filter(Hm,signal_input);
Matlad is warning that
Warning: Multistage design using fdesign.decimator will be removed. Use designMultistageDecimator instead.
So we are replacing the codewith:
Astop = 80;
TW = 0.03*fs_sampling/2;
Hm=designMultistageDecimator(dec_factor,fs_sampling,TW,Astop,’CostMethod’,’design’);
We don´t know what to do with Hm in order to apply the filter to get signal_input.
Any ideas?
Thanks in advance filtering, multistage filtering MATLAB Answers — New Questions
issue with fmincon function.
I want to maximize rate using fmincon function. the problem is I have an error as "Arrays have incompatible sizes for this operation." and "Caused by: Failure in initial objective function evaluation. FMINCON cannot continue.". I provide a part of my code and the objective function here. I guess the problem is in the reshape part and it might be wrong. I would really appreciate it if someone could help me to write the objective function correctly.
when . I should mention that is a vector and is a matrix for .
here is my code.
%initial guess for P2 and W2
P2_0 = ones(Ns,1) * (tilde_P2 / Ns) / 2; % initial guess for P2
W2_0 = ones(Ms,Ns); %initial guess for W2
%combine initial guess in a single vector
x0 = [P2_0 ; W2_0(:)];
% Define the linear constraint (C2)
A = zeros(Np, Ns + Ms * Ns);
for l = 1:Np
A(l, 1:Ns) = xi’; % Place xi’ in the first Ns columns of each row
end
% Define the bounds(C1)
lb = [zeros(Ns, 1); -Inf(Ms * Ns, 1)]; % Lower bound (P2 >= 0, no lower bound for W2)
ub = [repmat(tilde_P2 / Ns, Ns, 1); Inf(Ms * Ns, 1)]; % Upper bound (P2 <= tilde_P2_max / Ns, no upper bound for W2)
%%%objective function
obj_fun = @(x) -((Nup – Nt) / Nup * sum(log(1 + x(1:Ns) ./ (sigma2 * reshape(x(Ns+1:end), Ms, Ns).^2))));
% Set options for fmincon
options = optimoptions(‘fmincon’, ‘Display’, ‘iter’, ‘Algorithm’, ‘interior-point’);
% Run the optimization
[x_opt, fval] = fmincon(obj_fun, x0, A, hat_zeta1, [], [], lb, ub, [], options);
% Extract optimized values for P2 and W2
P2_opt = x_opt(1:Ns);
W2_opt = reshape(x_opt(Ns+1:end), Ms, Ns);I want to maximize rate using fmincon function. the problem is I have an error as "Arrays have incompatible sizes for this operation." and "Caused by: Failure in initial objective function evaluation. FMINCON cannot continue.". I provide a part of my code and the objective function here. I guess the problem is in the reshape part and it might be wrong. I would really appreciate it if someone could help me to write the objective function correctly.
when . I should mention that is a vector and is a matrix for .
here is my code.
%initial guess for P2 and W2
P2_0 = ones(Ns,1) * (tilde_P2 / Ns) / 2; % initial guess for P2
W2_0 = ones(Ms,Ns); %initial guess for W2
%combine initial guess in a single vector
x0 = [P2_0 ; W2_0(:)];
% Define the linear constraint (C2)
A = zeros(Np, Ns + Ms * Ns);
for l = 1:Np
A(l, 1:Ns) = xi’; % Place xi’ in the first Ns columns of each row
end
% Define the bounds(C1)
lb = [zeros(Ns, 1); -Inf(Ms * Ns, 1)]; % Lower bound (P2 >= 0, no lower bound for W2)
ub = [repmat(tilde_P2 / Ns, Ns, 1); Inf(Ms * Ns, 1)]; % Upper bound (P2 <= tilde_P2_max / Ns, no upper bound for W2)
%%%objective function
obj_fun = @(x) -((Nup – Nt) / Nup * sum(log(1 + x(1:Ns) ./ (sigma2 * reshape(x(Ns+1:end), Ms, Ns).^2))));
% Set options for fmincon
options = optimoptions(‘fmincon’, ‘Display’, ‘iter’, ‘Algorithm’, ‘interior-point’);
% Run the optimization
[x_opt, fval] = fmincon(obj_fun, x0, A, hat_zeta1, [], [], lb, ub, [], options);
% Extract optimized values for P2 and W2
P2_opt = x_opt(1:Ns);
W2_opt = reshape(x_opt(Ns+1:end), Ms, Ns); I want to maximize rate using fmincon function. the problem is I have an error as "Arrays have incompatible sizes for this operation." and "Caused by: Failure in initial objective function evaluation. FMINCON cannot continue.". I provide a part of my code and the objective function here. I guess the problem is in the reshape part and it might be wrong. I would really appreciate it if someone could help me to write the objective function correctly.
when . I should mention that is a vector and is a matrix for .
here is my code.
%initial guess for P2 and W2
P2_0 = ones(Ns,1) * (tilde_P2 / Ns) / 2; % initial guess for P2
W2_0 = ones(Ms,Ns); %initial guess for W2
%combine initial guess in a single vector
x0 = [P2_0 ; W2_0(:)];
% Define the linear constraint (C2)
A = zeros(Np, Ns + Ms * Ns);
for l = 1:Np
A(l, 1:Ns) = xi’; % Place xi’ in the first Ns columns of each row
end
% Define the bounds(C1)
lb = [zeros(Ns, 1); -Inf(Ms * Ns, 1)]; % Lower bound (P2 >= 0, no lower bound for W2)
ub = [repmat(tilde_P2 / Ns, Ns, 1); Inf(Ms * Ns, 1)]; % Upper bound (P2 <= tilde_P2_max / Ns, no upper bound for W2)
%%%objective function
obj_fun = @(x) -((Nup – Nt) / Nup * sum(log(1 + x(1:Ns) ./ (sigma2 * reshape(x(Ns+1:end), Ms, Ns).^2))));
% Set options for fmincon
options = optimoptions(‘fmincon’, ‘Display’, ‘iter’, ‘Algorithm’, ‘interior-point’);
% Run the optimization
[x_opt, fval] = fmincon(obj_fun, x0, A, hat_zeta1, [], [], lb, ub, [], options);
% Extract optimized values for P2 and W2
P2_opt = x_opt(1:Ns);
W2_opt = reshape(x_opt(Ns+1:end), Ms, Ns); fmincon, error MATLAB Answers — New Questions
How to set legend marker size
How do I change the marker size on the legend ? I can change the font size but not marker.
l = legend(‘Orientation’, ‘Horizontal’, ‘RNN (Ours)’, ‘SLIC’, ‘SEEDS’, ‘LSC’, ‘ERS’, ‘FH’);
l.FontSize = 20;
%l.MarkerSize = 20; does not work
%l.markersize = 20; does not work
set(l,’Position’, [0.4 0 0.2 0.2], ‘Units’, ‘normalized’);
%set(l,’MarkerSize’, 20); does not workHow do I change the marker size on the legend ? I can change the font size but not marker.
l = legend(‘Orientation’, ‘Horizontal’, ‘RNN (Ours)’, ‘SLIC’, ‘SEEDS’, ‘LSC’, ‘ERS’, ‘FH’);
l.FontSize = 20;
%l.MarkerSize = 20; does not work
%l.markersize = 20; does not work
set(l,’Position’, [0.4 0 0.2 0.2], ‘Units’, ‘normalized’);
%set(l,’MarkerSize’, 20); does not work How do I change the marker size on the legend ? I can change the font size but not marker.
l = legend(‘Orientation’, ‘Horizontal’, ‘RNN (Ours)’, ‘SLIC’, ‘SEEDS’, ‘LSC’, ‘ERS’, ‘FH’);
l.FontSize = 20;
%l.MarkerSize = 20; does not work
%l.markersize = 20; does not work
set(l,’Position’, [0.4 0 0.2 0.2], ‘Units’, ‘normalized’);
%set(l,’MarkerSize’, 20); does not work plot, legend, markersize MATLAB Answers — New Questions
NVIDIA Jetson setup issue: coder.checkGpuInstall can’t find nvcc
I am trying to use the GPU coder to send converted code to my Jetson Orin Nano. However, when I use the coder.checkGpuInstall command, it says that it can’t find nvcc.
I followed the setup instructions with the variables here:
Documentation
and referenced the following questions before posting this one:
https://www.mathworks.com/matlabcentral/answers/506483-ncc-problem-in-jetson-nano
https://www.mathworks.com/matlabcentral/answers/2068206-checking-for-cuda-availability-on-the-target-checking-for-nvcc-in-the-target-system-path-war
This is a cropped version of my script:
if (boardName == "jetson")
if isempty(deviceAddress)
hwobj = jetson();
else
hwobj = jetson(deviceAddress,userName,password);
end
else
if isempty(deviceAddress)
hwobj = drive();
else
hwobj = drive(deviceAddress,userName,password);
end
end
if (boardName == "jetson")
envCfg = coder.gpuEnvConfig(‘jetson’);
else
envCfg = coder.gpuEnvConfig(‘drive’);
end
envCfg.BasicCodegen = 1;
envCfg.HardwareObject = hwobj;
coder.checkGpuInstall(envCfg);
and the output:
Checking for CUDA availability on the Target…
Checking for ‘nvcc’ in the target system path…
Checking for cuDNN library availability on the Target…
Checking for TensorRT library availability on the Target…
Checking for prerequisite libraries is complete.
Gathering hardware details…
Checking for third-party library availability on the Target…
Warning: Unable to find the SDL 1.2 library on the target.
> In nvidiaio.internal.checkForSdlLibs (line 14)
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Warning: Unable to find one of the packages "sox", "libsox-fmt-all" or "libsox-dev". Make sure to have installed these
packages on the target hardware using "apt-get". These are required for successful deployment of Audio File Read block
in Simulink.
> In nvidiaio.internal.checkSoXVersion (line 17)
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Warning: Unable to fetch information about GPU devices.
> In nvidiaio.internal.getGpuInfo (line 77)
In nvidiaboard/getGpuInfo
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Gathering hardware details is complete.
Board name : NVIDIA Jetson Orin Nano Developer Kit
CUDA Version : 12.2
cuDNN Version : 8.9
TensorRT Version : 8.6
GStreamer Version : 1.20.3
V4L2 Version : 1.22.1-2build1
SDL Version :
OpenCV Version : 4.8.0
Available Webcams :
Available GPUs :
Available Digital Pins : 7 11 12 13 15 16 18 19 21 22 23 24 26 29 31 32 33 35 36 37 38 40
Compatible GPU : FAILED (Unable to find GPU information. This is due to the missing of ‘nvcc’ on the system path. Update the ‘.bashrc’ script on the target to set up the required environment variables.)
CUDA Environment : PASSED
Runtime : PASSED
cuFFT : PASSED
cuSOLVER : PASSED
cuBLAS : PASSED
Basic Code Generation : PASSED
In accordance with the setup guide, I updated both the .bashrc file (and /etc/environment file for good measure) on the jetson, I have pasted them below:
.bashrc excerpt:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don’t do anything
case $- in
*i*) ;;
*)
export PATH=$PATH:/usr/local/cuda/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64
export ARM_COMPUTELIB=$ARM_COMPUTELIB:/usr/local/arm_compute
return;;
esac
# don’t put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
/etc/environment:
PATH="/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"
LANG="en_US.UTF-8"
LD_LIBRARY_PATH="/usr/local/cuda/lib64"
And to confirm, the jetson does show nvcc is installed correctly:
$ nvcc –version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2023 NVIDIA Corporation
Built on Tue_Aug_15_22:08:11_PDT_2023
Cuda compilation tools, release 12.2, V12.2.140
Build cuda_12.2.r12.2/compiler.33191640_0
Matlab version info:
MATLAB Version: 24.1.0.2628055 (R2024a) Update 4
Operating System: Linux 5.15.0-116-generic #126~20.04.1-Ubuntu SMP Mon Jul 1 15:40:07 UTC 2024 x86_64
Java Version: Java 1.8.0_202-b08 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
Any help on this topic would be much appreciated. Thank you!I am trying to use the GPU coder to send converted code to my Jetson Orin Nano. However, when I use the coder.checkGpuInstall command, it says that it can’t find nvcc.
I followed the setup instructions with the variables here:
Documentation
and referenced the following questions before posting this one:
https://www.mathworks.com/matlabcentral/answers/506483-ncc-problem-in-jetson-nano
https://www.mathworks.com/matlabcentral/answers/2068206-checking-for-cuda-availability-on-the-target-checking-for-nvcc-in-the-target-system-path-war
This is a cropped version of my script:
if (boardName == "jetson")
if isempty(deviceAddress)
hwobj = jetson();
else
hwobj = jetson(deviceAddress,userName,password);
end
else
if isempty(deviceAddress)
hwobj = drive();
else
hwobj = drive(deviceAddress,userName,password);
end
end
if (boardName == "jetson")
envCfg = coder.gpuEnvConfig(‘jetson’);
else
envCfg = coder.gpuEnvConfig(‘drive’);
end
envCfg.BasicCodegen = 1;
envCfg.HardwareObject = hwobj;
coder.checkGpuInstall(envCfg);
and the output:
Checking for CUDA availability on the Target…
Checking for ‘nvcc’ in the target system path…
Checking for cuDNN library availability on the Target…
Checking for TensorRT library availability on the Target…
Checking for prerequisite libraries is complete.
Gathering hardware details…
Checking for third-party library availability on the Target…
Warning: Unable to find the SDL 1.2 library on the target.
> In nvidiaio.internal.checkForSdlLibs (line 14)
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Warning: Unable to find one of the packages "sox", "libsox-fmt-all" or "libsox-dev". Make sure to have installed these
packages on the target hardware using "apt-get". These are required for successful deployment of Audio File Read block
in Simulink.
> In nvidiaio.internal.checkSoXVersion (line 17)
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Warning: Unable to fetch information about GPU devices.
> In nvidiaio.internal.getGpuInfo (line 77)
In nvidiaboard/getGpuInfo
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Gathering hardware details is complete.
Board name : NVIDIA Jetson Orin Nano Developer Kit
CUDA Version : 12.2
cuDNN Version : 8.9
TensorRT Version : 8.6
GStreamer Version : 1.20.3
V4L2 Version : 1.22.1-2build1
SDL Version :
OpenCV Version : 4.8.0
Available Webcams :
Available GPUs :
Available Digital Pins : 7 11 12 13 15 16 18 19 21 22 23 24 26 29 31 32 33 35 36 37 38 40
Compatible GPU : FAILED (Unable to find GPU information. This is due to the missing of ‘nvcc’ on the system path. Update the ‘.bashrc’ script on the target to set up the required environment variables.)
CUDA Environment : PASSED
Runtime : PASSED
cuFFT : PASSED
cuSOLVER : PASSED
cuBLAS : PASSED
Basic Code Generation : PASSED
In accordance with the setup guide, I updated both the .bashrc file (and /etc/environment file for good measure) on the jetson, I have pasted them below:
.bashrc excerpt:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don’t do anything
case $- in
*i*) ;;
*)
export PATH=$PATH:/usr/local/cuda/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64
export ARM_COMPUTELIB=$ARM_COMPUTELIB:/usr/local/arm_compute
return;;
esac
# don’t put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
/etc/environment:
PATH="/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"
LANG="en_US.UTF-8"
LD_LIBRARY_PATH="/usr/local/cuda/lib64"
And to confirm, the jetson does show nvcc is installed correctly:
$ nvcc –version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2023 NVIDIA Corporation
Built on Tue_Aug_15_22:08:11_PDT_2023
Cuda compilation tools, release 12.2, V12.2.140
Build cuda_12.2.r12.2/compiler.33191640_0
Matlab version info:
MATLAB Version: 24.1.0.2628055 (R2024a) Update 4
Operating System: Linux 5.15.0-116-generic #126~20.04.1-Ubuntu SMP Mon Jul 1 15:40:07 UTC 2024 x86_64
Java Version: Java 1.8.0_202-b08 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
Any help on this topic would be much appreciated. Thank you! I am trying to use the GPU coder to send converted code to my Jetson Orin Nano. However, when I use the coder.checkGpuInstall command, it says that it can’t find nvcc.
I followed the setup instructions with the variables here:
Documentation
and referenced the following questions before posting this one:
https://www.mathworks.com/matlabcentral/answers/506483-ncc-problem-in-jetson-nano
https://www.mathworks.com/matlabcentral/answers/2068206-checking-for-cuda-availability-on-the-target-checking-for-nvcc-in-the-target-system-path-war
This is a cropped version of my script:
if (boardName == "jetson")
if isempty(deviceAddress)
hwobj = jetson();
else
hwobj = jetson(deviceAddress,userName,password);
end
else
if isempty(deviceAddress)
hwobj = drive();
else
hwobj = drive(deviceAddress,userName,password);
end
end
if (boardName == "jetson")
envCfg = coder.gpuEnvConfig(‘jetson’);
else
envCfg = coder.gpuEnvConfig(‘drive’);
end
envCfg.BasicCodegen = 1;
envCfg.HardwareObject = hwobj;
coder.checkGpuInstall(envCfg);
and the output:
Checking for CUDA availability on the Target…
Checking for ‘nvcc’ in the target system path…
Checking for cuDNN library availability on the Target…
Checking for TensorRT library availability on the Target…
Checking for prerequisite libraries is complete.
Gathering hardware details…
Checking for third-party library availability on the Target…
Warning: Unable to find the SDL 1.2 library on the target.
> In nvidiaio.internal.checkForSdlLibs (line 14)
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Warning: Unable to find one of the packages "sox", "libsox-fmt-all" or "libsox-dev". Make sure to have installed these
packages on the target hardware using "apt-get". These are required for successful deployment of Audio File Read block
in Simulink.
> In nvidiaio.internal.checkSoXVersion (line 17)
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Warning: Unable to fetch information about GPU devices.
> In nvidiaio.internal.getGpuInfo (line 77)
In nvidiaboard/getGpuInfo
In nvidiaboard/checkAndGetHardwareConfig
In jetson
In gpu_jetson_setup (line 10)
Gathering hardware details is complete.
Board name : NVIDIA Jetson Orin Nano Developer Kit
CUDA Version : 12.2
cuDNN Version : 8.9
TensorRT Version : 8.6
GStreamer Version : 1.20.3
V4L2 Version : 1.22.1-2build1
SDL Version :
OpenCV Version : 4.8.0
Available Webcams :
Available GPUs :
Available Digital Pins : 7 11 12 13 15 16 18 19 21 22 23 24 26 29 31 32 33 35 36 37 38 40
Compatible GPU : FAILED (Unable to find GPU information. This is due to the missing of ‘nvcc’ on the system path. Update the ‘.bashrc’ script on the target to set up the required environment variables.)
CUDA Environment : PASSED
Runtime : PASSED
cuFFT : PASSED
cuSOLVER : PASSED
cuBLAS : PASSED
Basic Code Generation : PASSED
In accordance with the setup guide, I updated both the .bashrc file (and /etc/environment file for good measure) on the jetson, I have pasted them below:
.bashrc excerpt:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don’t do anything
case $- in
*i*) ;;
*)
export PATH=$PATH:/usr/local/cuda/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64
export ARM_COMPUTELIB=$ARM_COMPUTELIB:/usr/local/arm_compute
return;;
esac
# don’t put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
/etc/environment:
PATH="/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"
LANG="en_US.UTF-8"
LD_LIBRARY_PATH="/usr/local/cuda/lib64"
And to confirm, the jetson does show nvcc is installed correctly:
$ nvcc –version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2023 NVIDIA Corporation
Built on Tue_Aug_15_22:08:11_PDT_2023
Cuda compilation tools, release 12.2, V12.2.140
Build cuda_12.2.r12.2/compiler.33191640_0
Matlab version info:
MATLAB Version: 24.1.0.2628055 (R2024a) Update 4
Operating System: Linux 5.15.0-116-generic #126~20.04.1-Ubuntu SMP Mon Jul 1 15:40:07 UTC 2024 x86_64
Java Version: Java 1.8.0_202-b08 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
Any help on this topic would be much appreciated. Thank you! gpu, nvidia, jetson, nvcc, cuda, error, env, matlab coder, embedded coder, hardware, gpu coder MATLAB Answers — New Questions
How to create an attention layer for deep learning networks?
Hello,
Can you please let me know how to create an attention layer for deep learning classification networks? I have a simple 1D convolutional neural network and I want to create a layer that focuses on special parts of a signal as an attention mechanism.
I have been working on the wav2vec MATLAB code recently, but the best I found is the multi-head attention manual calculation. Can we make it as a layer to be included for the trainNetwork function?
For example, this is my current network, which is from this example:
numFilters = 128;
filterSize = 5;
dropoutFactor = 0.005;
numBlocks = 4;
layer = sequenceInputLayer(numFeatures,Normalization="zerocenter",Name="input");
lgraph = layerGraph(layer);
outputName = layer.Name;
for i = 1:numBlocks
dilationFactor = 2^(i-1);
layers = [
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal",Name="conv1_"+i)
layerNormalizationLayer
spatialDropoutLayer(dropoutFactor)
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal")
layerNormalizationLayer
reluLayer
spatialDropoutLayer(dropoutFactor)
additionLayer(2,Name="add_"+i)];
% Add and connect layers.
lgraph = addLayers(lgraph,layers);
lgraph = connectLayers(lgraph,outputName,"conv1_"+i);
% Skip connection.
if i == 1
% Include convolution in first skip connection.
layer = convolution1dLayer(1,numFilters,Name="convSkip");
lgraph = addLayers(lgraph,layer);
lgraph = connectLayers(lgraph,outputName,"convSkip");
lgraph = connectLayers(lgraph,"convSkip","add_" + i + "/in2");
else
lgraph = connectLayers(lgraph,outputName,"add_" + i + "/in2");
end
% Update layer output name.
outputName = "add_" + i;
end
layers = [
globalMaxPooling1dLayer("Name",’gapl’)
fullyConnectedLayer(numClasses,Name="fc")
softmaxLayer
classificationLayer(‘Classes’,unique(Y_train),’ClassWeights’,weights)];
lgraph = addLayers(lgraph,layers);
lgraph = connectLayers(lgraph,outputName,"gapl");
I appreciate your help!
regards,
MohanadHello,
Can you please let me know how to create an attention layer for deep learning classification networks? I have a simple 1D convolutional neural network and I want to create a layer that focuses on special parts of a signal as an attention mechanism.
I have been working on the wav2vec MATLAB code recently, but the best I found is the multi-head attention manual calculation. Can we make it as a layer to be included for the trainNetwork function?
For example, this is my current network, which is from this example:
numFilters = 128;
filterSize = 5;
dropoutFactor = 0.005;
numBlocks = 4;
layer = sequenceInputLayer(numFeatures,Normalization="zerocenter",Name="input");
lgraph = layerGraph(layer);
outputName = layer.Name;
for i = 1:numBlocks
dilationFactor = 2^(i-1);
layers = [
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal",Name="conv1_"+i)
layerNormalizationLayer
spatialDropoutLayer(dropoutFactor)
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal")
layerNormalizationLayer
reluLayer
spatialDropoutLayer(dropoutFactor)
additionLayer(2,Name="add_"+i)];
% Add and connect layers.
lgraph = addLayers(lgraph,layers);
lgraph = connectLayers(lgraph,outputName,"conv1_"+i);
% Skip connection.
if i == 1
% Include convolution in first skip connection.
layer = convolution1dLayer(1,numFilters,Name="convSkip");
lgraph = addLayers(lgraph,layer);
lgraph = connectLayers(lgraph,outputName,"convSkip");
lgraph = connectLayers(lgraph,"convSkip","add_" + i + "/in2");
else
lgraph = connectLayers(lgraph,outputName,"add_" + i + "/in2");
end
% Update layer output name.
outputName = "add_" + i;
end
layers = [
globalMaxPooling1dLayer("Name",’gapl’)
fullyConnectedLayer(numClasses,Name="fc")
softmaxLayer
classificationLayer(‘Classes’,unique(Y_train),’ClassWeights’,weights)];
lgraph = addLayers(lgraph,layers);
lgraph = connectLayers(lgraph,outputName,"gapl");
I appreciate your help!
regards,
Mohanad Hello,
Can you please let me know how to create an attention layer for deep learning classification networks? I have a simple 1D convolutional neural network and I want to create a layer that focuses on special parts of a signal as an attention mechanism.
I have been working on the wav2vec MATLAB code recently, but the best I found is the multi-head attention manual calculation. Can we make it as a layer to be included for the trainNetwork function?
For example, this is my current network, which is from this example:
numFilters = 128;
filterSize = 5;
dropoutFactor = 0.005;
numBlocks = 4;
layer = sequenceInputLayer(numFeatures,Normalization="zerocenter",Name="input");
lgraph = layerGraph(layer);
outputName = layer.Name;
for i = 1:numBlocks
dilationFactor = 2^(i-1);
layers = [
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal",Name="conv1_"+i)
layerNormalizationLayer
spatialDropoutLayer(dropoutFactor)
convolution1dLayer(filterSize,numFilters,DilationFactor=dilationFactor,Padding="causal")
layerNormalizationLayer
reluLayer
spatialDropoutLayer(dropoutFactor)
additionLayer(2,Name="add_"+i)];
% Add and connect layers.
lgraph = addLayers(lgraph,layers);
lgraph = connectLayers(lgraph,outputName,"conv1_"+i);
% Skip connection.
if i == 1
% Include convolution in first skip connection.
layer = convolution1dLayer(1,numFilters,Name="convSkip");
lgraph = addLayers(lgraph,layer);
lgraph = connectLayers(lgraph,outputName,"convSkip");
lgraph = connectLayers(lgraph,"convSkip","add_" + i + "/in2");
else
lgraph = connectLayers(lgraph,outputName,"add_" + i + "/in2");
end
% Update layer output name.
outputName = "add_" + i;
end
layers = [
globalMaxPooling1dLayer("Name",’gapl’)
fullyConnectedLayer(numClasses,Name="fc")
softmaxLayer
classificationLayer(‘Classes’,unique(Y_train),’ClassWeights’,weights)];
lgraph = addLayers(lgraph,layers);
lgraph = connectLayers(lgraph,outputName,"gapl");
I appreciate your help!
regards,
Mohanad deep learning, attention, cnn MATLAB Answers — New Questions