Category: Matlab
Category Archives: Matlab
Extracting xyzpoints from Point Cloud
I want to extract xyz points data from Point Cloud model.
pointCloud with properties:
Location: [14816040×3 single]
Count: 14816040
XLimits: [-122.5566 183.8412]
YLimits: [-214.3051 106.7991]
ZLimits: [-4.3266 6.3947]
Color: [14816040×3 uint8]
Normal: [14816040×3 single]
Intensity: []
I am using two provided ways but not getting any results.
1st Code
ptCloud = pcread(‘M.ply’);
ptCloud;
xyzPoints = ptCloud.Location;
x = xyzPoints(:,:,1);
y = xyzPoints(:,:,2);
z = xyzPoints(:,:,3);
points3D = [x(:)’; y(:)’, z(:)’];
ERROR
Index in position 3 exceeds array bounds. Index must not exceed 1.
Error in xyzextract (line 8)
y = xyzPoints(:,:,2);
2nd function is
ptCloud;
pts = rosReadXYZ(ptCloud)
ERROR
Error using rosReadXYZ
Expected input to be one of these types:
struct
Instead its type was pointCloud.
Error in rosReadXYZ (line 46)
validateattributes(msg,{‘struct’},{‘scalar’},’rosReadXYZ’);
Error in xyzextract (line 13)
pts = rosReadXYZ(ptCloud,"PreserveStructureOnRead",true);
Kindly advise, I just want to extract xyz points from Point Cloud.I want to extract xyz points data from Point Cloud model.
pointCloud with properties:
Location: [14816040×3 single]
Count: 14816040
XLimits: [-122.5566 183.8412]
YLimits: [-214.3051 106.7991]
ZLimits: [-4.3266 6.3947]
Color: [14816040×3 uint8]
Normal: [14816040×3 single]
Intensity: []
I am using two provided ways but not getting any results.
1st Code
ptCloud = pcread(‘M.ply’);
ptCloud;
xyzPoints = ptCloud.Location;
x = xyzPoints(:,:,1);
y = xyzPoints(:,:,2);
z = xyzPoints(:,:,3);
points3D = [x(:)’; y(:)’, z(:)’];
ERROR
Index in position 3 exceeds array bounds. Index must not exceed 1.
Error in xyzextract (line 8)
y = xyzPoints(:,:,2);
2nd function is
ptCloud;
pts = rosReadXYZ(ptCloud)
ERROR
Error using rosReadXYZ
Expected input to be one of these types:
struct
Instead its type was pointCloud.
Error in rosReadXYZ (line 46)
validateattributes(msg,{‘struct’},{‘scalar’},’rosReadXYZ’);
Error in xyzextract (line 13)
pts = rosReadXYZ(ptCloud,"PreserveStructureOnRead",true);
Kindly advise, I just want to extract xyz points from Point Cloud. I want to extract xyz points data from Point Cloud model.
pointCloud with properties:
Location: [14816040×3 single]
Count: 14816040
XLimits: [-122.5566 183.8412]
YLimits: [-214.3051 106.7991]
ZLimits: [-4.3266 6.3947]
Color: [14816040×3 uint8]
Normal: [14816040×3 single]
Intensity: []
I am using two provided ways but not getting any results.
1st Code
ptCloud = pcread(‘M.ply’);
ptCloud;
xyzPoints = ptCloud.Location;
x = xyzPoints(:,:,1);
y = xyzPoints(:,:,2);
z = xyzPoints(:,:,3);
points3D = [x(:)’; y(:)’, z(:)’];
ERROR
Index in position 3 exceeds array bounds. Index must not exceed 1.
Error in xyzextract (line 8)
y = xyzPoints(:,:,2);
2nd function is
ptCloud;
pts = rosReadXYZ(ptCloud)
ERROR
Error using rosReadXYZ
Expected input to be one of these types:
struct
Instead its type was pointCloud.
Error in rosReadXYZ (line 46)
validateattributes(msg,{‘struct’},{‘scalar’},’rosReadXYZ’);
Error in xyzextract (line 13)
pts = rosReadXYZ(ptCloud,"PreserveStructureOnRead",true);
Kindly advise, I just want to extract xyz points from Point Cloud. point cloud MATLAB Answers — New Questions
Packed bed storage modeling probelm
Hello, I have to make a numerical model of a packed bed storage full of spheres where I have to predict both fluid temperature and solid temperature across the bed length. Its a transient 1D coupled heat transfer problem where I know only the fluid inlet temperature. I am a newbie at matlab and I tried to develop code with the help of chatgpt for charging phase but it doesn’t work. I also have to derive code for storage and discharging phase. Can you kindly help me with it?
rhoS = 2750; % Solid density [kg/m^3]
cpS = 850; % Solid specific heat capacity [J/(kg*K)]
ks = 1.28; % Effective thermal conductivity of solid [W/(m*K)]
epsilon = 0.36; % Void fraction
has = 47223.11473; % Heat transfer coefficient between solid and fluid [W/(m^2*K)]
Uw = 4.5118; % External heat transfer coefficient [W/(m^2*K)]
Tinfinity = 21 + 273.15; % Ambient temperature [K]
TinF = 83 + 273.15; % Inlet fluid temperature [K]
TinS = 21 + 273.15; % Initial solid temperature [K]
L = .14605; % Height of the packed bed [m]
u = 5.94; % Specific HTF mass flow rate [kg/(m^2*s)]
D = 0.1016; % Diameter of the bed [m]
dp = 0.01407; % Particle diameter [m]
rhoF = 1.08; % Fluid density [kg/m^3]
cpF = 1008; % Fluid specific heat [J/(kg*K)]
% Set up computational domain
Nx = 50; % Number of spatial steps
dx = L / Nx; % Spatial step size
dt = 1; % Time step size in seconds
Nt = 720; % Number of time steps
% Initialize temperature profiles
TS = ones(Nx, 1) * TinS; % Initial solid temperature profile
TF = ones(Nx, 1) * TinF; % Initial fluid temperature profile
TF(1) = Tinfinity
% Simulation loop
for n = 1:Nt
TS_new = TS;
TF_new = TF;
for i = 2:Nx-1
% Fluid temperature equation
TF_new(i) = TF(i) + dt * (-u * (TF(i) – TF(i-1)) / dx + (has/(rhoF * cpF * epsilon)) * (TS(i) – TF(i)));
% Solid temperature equation
d2TSdx2 = (TS(i+1) – 2*TS(i) + TS(i-1)) / dx^2;
TS_new(i) = TS(i) + dt * ((ks/(rhoS * cpS * (1 – epsilon))) * d2TSdx2 …
+ (has/(rhoS * cpS * (1 – epsilon))) * (TF(i) – TS(i)) …
+ (Uw * D * pi / (rhoS * cpS * (1 – epsilon))) * (Tinfinity – TS(i)));
end
% Update temperatures
TS = TS_new;
TF = TF_new;
% Apply boundary conditions
TF(1) = TinF; % Constant inlet temperature for fluid
TS(1) = TS(2); % Adiabatic boundary for solid at inlet
TS(Nx) = TS(Nx-1); %Adiabatic boundary for solid at outlet
end
% Plotting the results
x = linspace(0, L, Nx);
plot(x, TS-273.15, ‘r’, x, TF-273.15, ‘b’);
xlabel(‘Bed Length (m)’);
ylabel(‘Temperature (°C)’);
legend(‘Solid Temperature’, ‘Fluid Temperature’);
title(‘Temperature Distribution Along the Bed Length’);
grid on;Hello, I have to make a numerical model of a packed bed storage full of spheres where I have to predict both fluid temperature and solid temperature across the bed length. Its a transient 1D coupled heat transfer problem where I know only the fluid inlet temperature. I am a newbie at matlab and I tried to develop code with the help of chatgpt for charging phase but it doesn’t work. I also have to derive code for storage and discharging phase. Can you kindly help me with it?
rhoS = 2750; % Solid density [kg/m^3]
cpS = 850; % Solid specific heat capacity [J/(kg*K)]
ks = 1.28; % Effective thermal conductivity of solid [W/(m*K)]
epsilon = 0.36; % Void fraction
has = 47223.11473; % Heat transfer coefficient between solid and fluid [W/(m^2*K)]
Uw = 4.5118; % External heat transfer coefficient [W/(m^2*K)]
Tinfinity = 21 + 273.15; % Ambient temperature [K]
TinF = 83 + 273.15; % Inlet fluid temperature [K]
TinS = 21 + 273.15; % Initial solid temperature [K]
L = .14605; % Height of the packed bed [m]
u = 5.94; % Specific HTF mass flow rate [kg/(m^2*s)]
D = 0.1016; % Diameter of the bed [m]
dp = 0.01407; % Particle diameter [m]
rhoF = 1.08; % Fluid density [kg/m^3]
cpF = 1008; % Fluid specific heat [J/(kg*K)]
% Set up computational domain
Nx = 50; % Number of spatial steps
dx = L / Nx; % Spatial step size
dt = 1; % Time step size in seconds
Nt = 720; % Number of time steps
% Initialize temperature profiles
TS = ones(Nx, 1) * TinS; % Initial solid temperature profile
TF = ones(Nx, 1) * TinF; % Initial fluid temperature profile
TF(1) = Tinfinity
% Simulation loop
for n = 1:Nt
TS_new = TS;
TF_new = TF;
for i = 2:Nx-1
% Fluid temperature equation
TF_new(i) = TF(i) + dt * (-u * (TF(i) – TF(i-1)) / dx + (has/(rhoF * cpF * epsilon)) * (TS(i) – TF(i)));
% Solid temperature equation
d2TSdx2 = (TS(i+1) – 2*TS(i) + TS(i-1)) / dx^2;
TS_new(i) = TS(i) + dt * ((ks/(rhoS * cpS * (1 – epsilon))) * d2TSdx2 …
+ (has/(rhoS * cpS * (1 – epsilon))) * (TF(i) – TS(i)) …
+ (Uw * D * pi / (rhoS * cpS * (1 – epsilon))) * (Tinfinity – TS(i)));
end
% Update temperatures
TS = TS_new;
TF = TF_new;
% Apply boundary conditions
TF(1) = TinF; % Constant inlet temperature for fluid
TS(1) = TS(2); % Adiabatic boundary for solid at inlet
TS(Nx) = TS(Nx-1); %Adiabatic boundary for solid at outlet
end
% Plotting the results
x = linspace(0, L, Nx);
plot(x, TS-273.15, ‘r’, x, TF-273.15, ‘b’);
xlabel(‘Bed Length (m)’);
ylabel(‘Temperature (°C)’);
legend(‘Solid Temperature’, ‘Fluid Temperature’);
title(‘Temperature Distribution Along the Bed Length’);
grid on; Hello, I have to make a numerical model of a packed bed storage full of spheres where I have to predict both fluid temperature and solid temperature across the bed length. Its a transient 1D coupled heat transfer problem where I know only the fluid inlet temperature. I am a newbie at matlab and I tried to develop code with the help of chatgpt for charging phase but it doesn’t work. I also have to derive code for storage and discharging phase. Can you kindly help me with it?
rhoS = 2750; % Solid density [kg/m^3]
cpS = 850; % Solid specific heat capacity [J/(kg*K)]
ks = 1.28; % Effective thermal conductivity of solid [W/(m*K)]
epsilon = 0.36; % Void fraction
has = 47223.11473; % Heat transfer coefficient between solid and fluid [W/(m^2*K)]
Uw = 4.5118; % External heat transfer coefficient [W/(m^2*K)]
Tinfinity = 21 + 273.15; % Ambient temperature [K]
TinF = 83 + 273.15; % Inlet fluid temperature [K]
TinS = 21 + 273.15; % Initial solid temperature [K]
L = .14605; % Height of the packed bed [m]
u = 5.94; % Specific HTF mass flow rate [kg/(m^2*s)]
D = 0.1016; % Diameter of the bed [m]
dp = 0.01407; % Particle diameter [m]
rhoF = 1.08; % Fluid density [kg/m^3]
cpF = 1008; % Fluid specific heat [J/(kg*K)]
% Set up computational domain
Nx = 50; % Number of spatial steps
dx = L / Nx; % Spatial step size
dt = 1; % Time step size in seconds
Nt = 720; % Number of time steps
% Initialize temperature profiles
TS = ones(Nx, 1) * TinS; % Initial solid temperature profile
TF = ones(Nx, 1) * TinF; % Initial fluid temperature profile
TF(1) = Tinfinity
% Simulation loop
for n = 1:Nt
TS_new = TS;
TF_new = TF;
for i = 2:Nx-1
% Fluid temperature equation
TF_new(i) = TF(i) + dt * (-u * (TF(i) – TF(i-1)) / dx + (has/(rhoF * cpF * epsilon)) * (TS(i) – TF(i)));
% Solid temperature equation
d2TSdx2 = (TS(i+1) – 2*TS(i) + TS(i-1)) / dx^2;
TS_new(i) = TS(i) + dt * ((ks/(rhoS * cpS * (1 – epsilon))) * d2TSdx2 …
+ (has/(rhoS * cpS * (1 – epsilon))) * (TF(i) – TS(i)) …
+ (Uw * D * pi / (rhoS * cpS * (1 – epsilon))) * (Tinfinity – TS(i)));
end
% Update temperatures
TS = TS_new;
TF = TF_new;
% Apply boundary conditions
TF(1) = TinF; % Constant inlet temperature for fluid
TS(1) = TS(2); % Adiabatic boundary for solid at inlet
TS(Nx) = TS(Nx-1); %Adiabatic boundary for solid at outlet
end
% Plotting the results
x = linspace(0, L, Nx);
plot(x, TS-273.15, ‘r’, x, TF-273.15, ‘b’);
xlabel(‘Bed Length (m)’);
ylabel(‘Temperature (°C)’);
legend(‘Solid Temperature’, ‘Fluid Temperature’);
title(‘Temperature Distribution Along the Bed Length’);
grid on; model, urgent MATLAB Answers — New Questions
Image Steganography using LSB?
I have coded a LSB algorithm for Image Steganography. During retrieval process i’m getting different msg. Can anyone correct this code please!
Embedding code
c = imread(‘image.bmp’);
message = ‘hellokarthick’
message = strtrim(message);
m = length(message) * 8;
AsciiCode = uint8(message);
binaryString = transpose(dec2bin(AsciiCode,8));
binaryString = binaryString(:);
N = length(binaryString);
b = zeros(N,1); %b is a vector of bits
for k = 1:N
if(binaryString(k) == ‘1’)
b(k) = 1;
else
b(k) = 0;
end
end
s = c;
height = size(c,1);
width = size(c,2);
k = 1;
for i = 1 : height
for j = 1 : width
LSB = mod(double(c(i,j)), 2);
if (k>m || LSB == b(k))
s(i,j) = c(i,j);
else
if(LSB == 1)
s(i,j) = c(i,j) – 1;
else
s(i,j) = c(i,j) + 1;
end
k = k + 1;
end
end
end
imwrite(s, ‘hiddenmsgimage.bmp’);
Retriever coding
s = imread(‘hiddenmsgimage.bmp’);
height = size(s,1);
width = size(s,2);
%For this example the max size is 100 bytes, or 800 bits, (bytes * = bits
m = 800;
k = 1;
for i = 1 : height
for j = 1 : width
if (k <= m)
b(k) = mod(double(s(i,j)),2);
k = k + 1;
end
end
end
binaryVector = b;
binValues = [ 128 64 32 16 8 4 2 1 ];
binaryVector = binaryVector(:);
if mod(length(binaryVector),8) ~= 0
error(‘Length of binary vector must be a multiple of 8.’);
end
binMatrix = reshape(binaryVector,8,100);
display(binMatrix);
textString = char(binValues*binMatrix);
disp(textString);I have coded a LSB algorithm for Image Steganography. During retrieval process i’m getting different msg. Can anyone correct this code please!
Embedding code
c = imread(‘image.bmp’);
message = ‘hellokarthick’
message = strtrim(message);
m = length(message) * 8;
AsciiCode = uint8(message);
binaryString = transpose(dec2bin(AsciiCode,8));
binaryString = binaryString(:);
N = length(binaryString);
b = zeros(N,1); %b is a vector of bits
for k = 1:N
if(binaryString(k) == ‘1’)
b(k) = 1;
else
b(k) = 0;
end
end
s = c;
height = size(c,1);
width = size(c,2);
k = 1;
for i = 1 : height
for j = 1 : width
LSB = mod(double(c(i,j)), 2);
if (k>m || LSB == b(k))
s(i,j) = c(i,j);
else
if(LSB == 1)
s(i,j) = c(i,j) – 1;
else
s(i,j) = c(i,j) + 1;
end
k = k + 1;
end
end
end
imwrite(s, ‘hiddenmsgimage.bmp’);
Retriever coding
s = imread(‘hiddenmsgimage.bmp’);
height = size(s,1);
width = size(s,2);
%For this example the max size is 100 bytes, or 800 bits, (bytes * = bits
m = 800;
k = 1;
for i = 1 : height
for j = 1 : width
if (k <= m)
b(k) = mod(double(s(i,j)),2);
k = k + 1;
end
end
end
binaryVector = b;
binValues = [ 128 64 32 16 8 4 2 1 ];
binaryVector = binaryVector(:);
if mod(length(binaryVector),8) ~= 0
error(‘Length of binary vector must be a multiple of 8.’);
end
binMatrix = reshape(binaryVector,8,100);
display(binMatrix);
textString = char(binValues*binMatrix);
disp(textString); I have coded a LSB algorithm for Image Steganography. During retrieval process i’m getting different msg. Can anyone correct this code please!
Embedding code
c = imread(‘image.bmp’);
message = ‘hellokarthick’
message = strtrim(message);
m = length(message) * 8;
AsciiCode = uint8(message);
binaryString = transpose(dec2bin(AsciiCode,8));
binaryString = binaryString(:);
N = length(binaryString);
b = zeros(N,1); %b is a vector of bits
for k = 1:N
if(binaryString(k) == ‘1’)
b(k) = 1;
else
b(k) = 0;
end
end
s = c;
height = size(c,1);
width = size(c,2);
k = 1;
for i = 1 : height
for j = 1 : width
LSB = mod(double(c(i,j)), 2);
if (k>m || LSB == b(k))
s(i,j) = c(i,j);
else
if(LSB == 1)
s(i,j) = c(i,j) – 1;
else
s(i,j) = c(i,j) + 1;
end
k = k + 1;
end
end
end
imwrite(s, ‘hiddenmsgimage.bmp’);
Retriever coding
s = imread(‘hiddenmsgimage.bmp’);
height = size(s,1);
width = size(s,2);
%For this example the max size is 100 bytes, or 800 bits, (bytes * = bits
m = 800;
k = 1;
for i = 1 : height
for j = 1 : width
if (k <= m)
b(k) = mod(double(s(i,j)),2);
k = k + 1;
end
end
end
binaryVector = b;
binValues = [ 128 64 32 16 8 4 2 1 ];
binaryVector = binaryVector(:);
if mod(length(binaryVector),8) ~= 0
error(‘Length of binary vector must be a multiple of 8.’);
end
binMatrix = reshape(binaryVector,8,100);
display(binMatrix);
textString = char(binValues*binMatrix);
disp(textString); steganography, lsb, watermarking MATLAB Answers — New Questions
call function name in the same function
In a function, I need to run this function somewhere within the function like
function fun
i=1
if i>1
function name
end
end
"function name" is just to call "fun", but I need to create a few copy m files of the above scripts with respective changes in the code so that the function name is actually "copy fun" or "copy 2 fun" etc and I wish "function name" to call "copy fun" or "copy 2 fun" etc.In a function, I need to run this function somewhere within the function like
function fun
i=1
if i>1
function name
end
end
"function name" is just to call "fun", but I need to create a few copy m files of the above scripts with respective changes in the code so that the function name is actually "copy fun" or "copy 2 fun" etc and I wish "function name" to call "copy fun" or "copy 2 fun" etc. In a function, I need to run this function somewhere within the function like
function fun
i=1
if i>1
function name
end
end
"function name" is just to call "fun", but I need to create a few copy m files of the above scripts with respective changes in the code so that the function name is actually "copy fun" or "copy 2 fun" etc and I wish "function name" to call "copy fun" or "copy 2 fun" etc. function MATLAB Answers — New Questions
the app I created in MATLAB App designer is not responding, it worked before but now it has stopped responding, even I can’t close the desktop window
I was working on the app in app designer to record audio,add noise, and then filter the noise with suitable filter, for this I also plotted the time domain and frequency domain spectrum of each signal , i also have difficulting in plotting the filtered signal spectrums, like when I added the code to plot the filtered signal , I started encountering the problem, the app in not running.even I can’t close the window! my matlab version is R2018a.
here is my code
classdef app1 < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
RecordButton matlab.ui.control.Button
durationTextAreaLabel matlab.ui.control.Label
durationTextArea matlab.ui.control.TextArea
playButton matlab.ui.control.Button
UIAxes matlab.ui.control.UIAxes
UIAxes2 matlab.ui.control.UIAxes
wanttoaddnoiseCheckBox matlab.ui.control.CheckBox
ButtonGroup matlab.ui.container.ButtonGroup
noiseaddedButton matlab.ui.control.RadioButton
playnoisysignalButton matlab.ui.control.Button
SNRTextAreaLabel matlab.ui.control.Label
SNRTextArea matlab.ui.control.TextArea
UIAxes3 matlab.ui.control.UIAxes
UIAxes4 matlab.ui.control.UIAxes
filterButton matlab.ui.control.Button
UIAxes5 matlab.ui.control.UIAxes
UIAxes6 matlab.ui.control.UIAxes
showfilteredsignalButton matlab.ui.control.Button
end
properties (Access = private)
% Description
SNR % Description
play % Description
filteredData % Description
Property4 % Description
Property5 % Description
end
methods (Access = private)
function results = func(app)
end
end
methods (Access = private)
% Button pushed function: RecordButton
function RecordButtonPushed(app, event)
audioObject= audiorecorder(44100,16,1);
Duration=str2double(app.durationTextArea.Value{1});
msgbox(‘recording start’);
recordblocking(audioObject,Duration);
msgbox(‘recording stopped’);
assignin(‘base’,’audioObject’,audioObject);
end
% Button pushed function: playButton
function playButtonPushed(app, event)
audioObject=evalin(‘base’,’audioObject’);
audioData=getaudiodata(audioObject);
sound(audioData,audioObject.SampleRate);
audiowrite(‘input_audio.wav’,audioData,44100);
% plotting the audio signal in time domain
t=(0:length(audioData)-1)/44100;
plot(app.UIAxes,t,audioData);
%plotting the amplitude spectrum of audio signal
f_InputData = linspace(-44100/2,44100/2,length(audioData));
INPUTDATA = fft(audioData);
INPUTDATA_f = fftshift(INPUTDATA);
INPUTDATA_f_abs = abs( INPUTDATA_f);
plot(app.UIAxes2,f_InputData,INPUTDATA_f_abs);
end
% Value changed function: wanttoaddnoiseCheckBox
function wanttoaddnoiseCheckBoxValueChanged(app, event)
value = app.wanttoaddnoiseCheckBox.Value;
switch value
case 0
app.noiseaddedButton.Visible = ‘off’;
case 1
app.noiseaddedButton.Visible = ‘on’;
end
end
% Button pushed function: playnoisysignalButton
function playnoisysignalButtonPushed(app, event)
audioObject = evalin(‘base’,’audioObject’);
app.SNR= str2double(app.SNRTextArea.Value{1});
noisyData=awgn(getaudiodata(audioObject),app.SNR,’measured’);
switch app.wanttoaddnoiseCheckBox.Value
case 1
if(app.noiseaddedButton.Value)
app.play = audioplayer(noisyData,44100);
playblocking(app.play);
assignin(‘base’,’noisyData’,noisyData);
%plotting the noisy signal in time domain
audiowrite(‘noisy_input_audio.wav’, noisyData, 44100);
t=(0:length(noisyData)-1)/44100;
plot(app.UIAxes3,t,noisyData);
% plotting amplitude density spectrum of noisy signal
f_InputData = linspace(-44100/2,44100/2,length(noisyData));
INPUTDATA=fft(noisyData);
INPUTDATA_f = fftshift(INPUTDATA);
INPUTDATA_f_abs = abs(INPUTDATA_f);
plot(app.UIAxes4,f_InputData,INPUTDATA_f_abs);
end
case 0
msgbox(‘noise not added’)
end
end
% Button pushed function: filterButton
function filterButtonPushed(app, event)
fc = 4000; % Cut-off frequency in Hz
order = 30; % Filter order
% Design the low-pass filter
[b, a] = butter(order, fc/(44100/2), ‘low’);
% Apply the filter to the noisy audio signal
noisyData = evalin(‘base’,’noisyData’);
v_filtered = filter(b, a,noisyData);
% Play the filtered audio
app.filteredData = audioplayer(v_filtered, 44100);
playblocking(app.filteredData);
assignin(‘base’,’v_filtered’,v_filtered);
v_filtered = evalin(‘base’,’v_filtered’);
end
% Button pushed function: showfilteredsignalButton
function showfilteredsignalButtonPushed(app, event)
v_filtered = evalin(‘base’,’v_filtered’);
audiowrite(‘filtered_audio.wav’,v_filtered, 44100);
t_filt= (0:length(app.filteredData)-1)/44100;
plot(app.UIAxes5,t_filt,v_filtered);
end
end
% App initialization and construction
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure
app.UIFigure = uifigure;
app.UIFigure.Position = [100 100 1523 509];
app.UIFigure.Name = ‘UI Figure’;
% Create RecordButton
app.RecordButton = uibutton(app.UIFigure, ‘push’);
app.RecordButton.ButtonPushedFcn = createCallbackFcn(app, @RecordButtonPushed, true);
app.RecordButton.Position = [39 440 100 22];
app.RecordButton.Text = ‘Record’;
% Create durationTextAreaLabel
app.durationTextAreaLabel = uilabel(app.UIFigure);
app.durationTextAreaLabel.HorizontalAlignment = ‘right’;
app.durationTextAreaLabel.Position = [39 406 49 22];
app.durationTextAreaLabel.Text = ‘duration’;
% Create durationTextArea
app.durationTextArea = uitextarea(app.UIFigure);
app.durationTextArea.HorizontalAlignment = ‘right’;
app.durationTextArea.Position = [103 404 139 26];
app.durationTextArea.Value = {’10’};
% Create playButton
app.playButton = uibutton(app.UIFigure, ‘push’);
app.playButton.ButtonPushedFcn = createCallbackFcn(app, @playButtonPushed, true);
app.playButton.Position = [39 361 100 22];
app.playButton.Text = ‘play’;
% Create UIAxes
app.UIAxes = uiaxes(app.UIFigure);
title(app.UIAxes, ‘Input Audio Signal’)
xlabel(app.UIAxes, ‘time’)
ylabel(app.UIAxes, ‘magnitude’)
app.UIAxes.Position = [251 292 444 197];
% Create UIAxes2
app.UIAxes2 = uiaxes(app.UIFigure);
title(app.UIAxes2, ‘Amplitude Density spectrum of Audio Signal’)
xlabel(app.UIAxes2, ‘frequency’)
ylabel(app.UIAxes2, ‘magnitude’)
app.UIAxes2.Position = [255 70 436 207];
% Create wanttoaddnoiseCheckBox
app.wanttoaddnoiseCheckBox = uicheckbox(app.UIFigure);
app.wanttoaddnoiseCheckBox.ValueChangedFcn = createCallbackFcn(app, @wanttoaddnoiseCheckBoxValueChanged, true);
app.wanttoaddnoiseCheckBox.Text = ‘want to add noise?’;
app.wanttoaddnoiseCheckBox.Position = [75 276 123 22];
% Create ButtonGroup
app.ButtonGroup = uibuttongroup(app.UIFigure);
app.ButtonGroup.BorderType = ‘none’;
app.ButtonGroup.Position = [64 227 123 30];
% Create noiseaddedButton
app.noiseaddedButton = uiradiobutton(app.ButtonGroup);
app.noiseaddedButton.Visible = ‘off’;
app.noiseaddedButton.Text = ‘noise added’;
app.noiseaddedButton.Position = [11 4 87 22];
app.noiseaddedButton.Value = true;
% Create playnoisysignalButton
app.playnoisysignalButton = uibutton(app.UIFigure, ‘push’);
app.playnoisysignalButton.ButtonPushedFcn = createCallbackFcn(app, @playnoisysignalButtonPushed, true);
app.playnoisysignalButton.Position = [89 144 104 22];
app.playnoisysignalButton.Text = ‘play noisy signal’;
% Create SNRTextAreaLabel
app.SNRTextAreaLabel = uilabel(app.UIFigure);
app.SNRTextAreaLabel.HorizontalAlignment = ‘right’;
app.SNRTextAreaLabel.Position = [64 185 31 22];
app.SNRTextAreaLabel.Text = ‘SNR’;
% Create SNRTextArea
app.SNRTextArea = uitextarea(app.UIFigure);
app.SNRTextArea.HorizontalAlignment = ‘right’;
app.SNRTextArea.Position = [110 185 77 24];
app.SNRTextArea.Value = {’12’};
% Create UIAxes3
app.UIAxes3 = uiaxes(app.UIFigure);
title(app.UIAxes3, ‘Noisy signal’)
xlabel(app.UIAxes3, ‘time’)
ylabel(app.UIAxes3, ‘magnitude’)
app.UIAxes3.Position = [726 292 414 197];
% Create UIAxes4
app.UIAxes4 = uiaxes(app.UIFigure);
title(app.UIAxes4, ‘Amplitude Density spectrum of Noisy Signal’)
xlabel(app.UIAxes4, ‘frequecny’)
ylabel(app.UIAxes4, ‘magnitude’)
app.UIAxes4.Position = [726 70 414 207];
% Create filterButton
app.filterButton = uibutton(app.UIFigure, ‘push’);
app.filterButton.ButtonPushedFcn = createCallbackFcn(app, @filterButtonPushed, true);
app.filterButton.Position = [103 70 100 22];
app.filterButton.Text = ‘filter’;
% Create UIAxes5
app.UIAxes5 = uiaxes(app.UIFigure);
title(app.UIAxes5, ‘Title’)
xlabel(app.UIAxes5, ‘X’)
ylabel(app.UIAxes5, ‘Y’)
app.UIAxes5.Position = [1170 292 382 197];
% Create UIAxes6
app.UIAxes6 = uiaxes(app.UIFigure);
title(app.UIAxes6, ‘Title’)
xlabel(app.UIAxes6, ‘X’)
ylabel(app.UIAxes6, ‘Y’)
app.UIAxes6.Position = [1170 70 382 207];
% Create showfilteredsignalButton
app.showfilteredsignalButton = uibutton(app.UIFigure, ‘push’);
app.showfilteredsignalButton.ButtonPushedFcn = createCallbackFcn(app, @showfilteredsignalButtonPushed, true);
app.showfilteredsignalButton.Position = [94 32 118 22];
app.showfilteredsignalButton.Text = ‘show filtered signal’;
end
end
methods (Access = public)
% Construct app
function app = app1
% Create and configure components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
endI was working on the app in app designer to record audio,add noise, and then filter the noise with suitable filter, for this I also plotted the time domain and frequency domain spectrum of each signal , i also have difficulting in plotting the filtered signal spectrums, like when I added the code to plot the filtered signal , I started encountering the problem, the app in not running.even I can’t close the window! my matlab version is R2018a.
here is my code
classdef app1 < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
RecordButton matlab.ui.control.Button
durationTextAreaLabel matlab.ui.control.Label
durationTextArea matlab.ui.control.TextArea
playButton matlab.ui.control.Button
UIAxes matlab.ui.control.UIAxes
UIAxes2 matlab.ui.control.UIAxes
wanttoaddnoiseCheckBox matlab.ui.control.CheckBox
ButtonGroup matlab.ui.container.ButtonGroup
noiseaddedButton matlab.ui.control.RadioButton
playnoisysignalButton matlab.ui.control.Button
SNRTextAreaLabel matlab.ui.control.Label
SNRTextArea matlab.ui.control.TextArea
UIAxes3 matlab.ui.control.UIAxes
UIAxes4 matlab.ui.control.UIAxes
filterButton matlab.ui.control.Button
UIAxes5 matlab.ui.control.UIAxes
UIAxes6 matlab.ui.control.UIAxes
showfilteredsignalButton matlab.ui.control.Button
end
properties (Access = private)
% Description
SNR % Description
play % Description
filteredData % Description
Property4 % Description
Property5 % Description
end
methods (Access = private)
function results = func(app)
end
end
methods (Access = private)
% Button pushed function: RecordButton
function RecordButtonPushed(app, event)
audioObject= audiorecorder(44100,16,1);
Duration=str2double(app.durationTextArea.Value{1});
msgbox(‘recording start’);
recordblocking(audioObject,Duration);
msgbox(‘recording stopped’);
assignin(‘base’,’audioObject’,audioObject);
end
% Button pushed function: playButton
function playButtonPushed(app, event)
audioObject=evalin(‘base’,’audioObject’);
audioData=getaudiodata(audioObject);
sound(audioData,audioObject.SampleRate);
audiowrite(‘input_audio.wav’,audioData,44100);
% plotting the audio signal in time domain
t=(0:length(audioData)-1)/44100;
plot(app.UIAxes,t,audioData);
%plotting the amplitude spectrum of audio signal
f_InputData = linspace(-44100/2,44100/2,length(audioData));
INPUTDATA = fft(audioData);
INPUTDATA_f = fftshift(INPUTDATA);
INPUTDATA_f_abs = abs( INPUTDATA_f);
plot(app.UIAxes2,f_InputData,INPUTDATA_f_abs);
end
% Value changed function: wanttoaddnoiseCheckBox
function wanttoaddnoiseCheckBoxValueChanged(app, event)
value = app.wanttoaddnoiseCheckBox.Value;
switch value
case 0
app.noiseaddedButton.Visible = ‘off’;
case 1
app.noiseaddedButton.Visible = ‘on’;
end
end
% Button pushed function: playnoisysignalButton
function playnoisysignalButtonPushed(app, event)
audioObject = evalin(‘base’,’audioObject’);
app.SNR= str2double(app.SNRTextArea.Value{1});
noisyData=awgn(getaudiodata(audioObject),app.SNR,’measured’);
switch app.wanttoaddnoiseCheckBox.Value
case 1
if(app.noiseaddedButton.Value)
app.play = audioplayer(noisyData,44100);
playblocking(app.play);
assignin(‘base’,’noisyData’,noisyData);
%plotting the noisy signal in time domain
audiowrite(‘noisy_input_audio.wav’, noisyData, 44100);
t=(0:length(noisyData)-1)/44100;
plot(app.UIAxes3,t,noisyData);
% plotting amplitude density spectrum of noisy signal
f_InputData = linspace(-44100/2,44100/2,length(noisyData));
INPUTDATA=fft(noisyData);
INPUTDATA_f = fftshift(INPUTDATA);
INPUTDATA_f_abs = abs(INPUTDATA_f);
plot(app.UIAxes4,f_InputData,INPUTDATA_f_abs);
end
case 0
msgbox(‘noise not added’)
end
end
% Button pushed function: filterButton
function filterButtonPushed(app, event)
fc = 4000; % Cut-off frequency in Hz
order = 30; % Filter order
% Design the low-pass filter
[b, a] = butter(order, fc/(44100/2), ‘low’);
% Apply the filter to the noisy audio signal
noisyData = evalin(‘base’,’noisyData’);
v_filtered = filter(b, a,noisyData);
% Play the filtered audio
app.filteredData = audioplayer(v_filtered, 44100);
playblocking(app.filteredData);
assignin(‘base’,’v_filtered’,v_filtered);
v_filtered = evalin(‘base’,’v_filtered’);
end
% Button pushed function: showfilteredsignalButton
function showfilteredsignalButtonPushed(app, event)
v_filtered = evalin(‘base’,’v_filtered’);
audiowrite(‘filtered_audio.wav’,v_filtered, 44100);
t_filt= (0:length(app.filteredData)-1)/44100;
plot(app.UIAxes5,t_filt,v_filtered);
end
end
% App initialization and construction
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure
app.UIFigure = uifigure;
app.UIFigure.Position = [100 100 1523 509];
app.UIFigure.Name = ‘UI Figure’;
% Create RecordButton
app.RecordButton = uibutton(app.UIFigure, ‘push’);
app.RecordButton.ButtonPushedFcn = createCallbackFcn(app, @RecordButtonPushed, true);
app.RecordButton.Position = [39 440 100 22];
app.RecordButton.Text = ‘Record’;
% Create durationTextAreaLabel
app.durationTextAreaLabel = uilabel(app.UIFigure);
app.durationTextAreaLabel.HorizontalAlignment = ‘right’;
app.durationTextAreaLabel.Position = [39 406 49 22];
app.durationTextAreaLabel.Text = ‘duration’;
% Create durationTextArea
app.durationTextArea = uitextarea(app.UIFigure);
app.durationTextArea.HorizontalAlignment = ‘right’;
app.durationTextArea.Position = [103 404 139 26];
app.durationTextArea.Value = {’10’};
% Create playButton
app.playButton = uibutton(app.UIFigure, ‘push’);
app.playButton.ButtonPushedFcn = createCallbackFcn(app, @playButtonPushed, true);
app.playButton.Position = [39 361 100 22];
app.playButton.Text = ‘play’;
% Create UIAxes
app.UIAxes = uiaxes(app.UIFigure);
title(app.UIAxes, ‘Input Audio Signal’)
xlabel(app.UIAxes, ‘time’)
ylabel(app.UIAxes, ‘magnitude’)
app.UIAxes.Position = [251 292 444 197];
% Create UIAxes2
app.UIAxes2 = uiaxes(app.UIFigure);
title(app.UIAxes2, ‘Amplitude Density spectrum of Audio Signal’)
xlabel(app.UIAxes2, ‘frequency’)
ylabel(app.UIAxes2, ‘magnitude’)
app.UIAxes2.Position = [255 70 436 207];
% Create wanttoaddnoiseCheckBox
app.wanttoaddnoiseCheckBox = uicheckbox(app.UIFigure);
app.wanttoaddnoiseCheckBox.ValueChangedFcn = createCallbackFcn(app, @wanttoaddnoiseCheckBoxValueChanged, true);
app.wanttoaddnoiseCheckBox.Text = ‘want to add noise?’;
app.wanttoaddnoiseCheckBox.Position = [75 276 123 22];
% Create ButtonGroup
app.ButtonGroup = uibuttongroup(app.UIFigure);
app.ButtonGroup.BorderType = ‘none’;
app.ButtonGroup.Position = [64 227 123 30];
% Create noiseaddedButton
app.noiseaddedButton = uiradiobutton(app.ButtonGroup);
app.noiseaddedButton.Visible = ‘off’;
app.noiseaddedButton.Text = ‘noise added’;
app.noiseaddedButton.Position = [11 4 87 22];
app.noiseaddedButton.Value = true;
% Create playnoisysignalButton
app.playnoisysignalButton = uibutton(app.UIFigure, ‘push’);
app.playnoisysignalButton.ButtonPushedFcn = createCallbackFcn(app, @playnoisysignalButtonPushed, true);
app.playnoisysignalButton.Position = [89 144 104 22];
app.playnoisysignalButton.Text = ‘play noisy signal’;
% Create SNRTextAreaLabel
app.SNRTextAreaLabel = uilabel(app.UIFigure);
app.SNRTextAreaLabel.HorizontalAlignment = ‘right’;
app.SNRTextAreaLabel.Position = [64 185 31 22];
app.SNRTextAreaLabel.Text = ‘SNR’;
% Create SNRTextArea
app.SNRTextArea = uitextarea(app.UIFigure);
app.SNRTextArea.HorizontalAlignment = ‘right’;
app.SNRTextArea.Position = [110 185 77 24];
app.SNRTextArea.Value = {’12’};
% Create UIAxes3
app.UIAxes3 = uiaxes(app.UIFigure);
title(app.UIAxes3, ‘Noisy signal’)
xlabel(app.UIAxes3, ‘time’)
ylabel(app.UIAxes3, ‘magnitude’)
app.UIAxes3.Position = [726 292 414 197];
% Create UIAxes4
app.UIAxes4 = uiaxes(app.UIFigure);
title(app.UIAxes4, ‘Amplitude Density spectrum of Noisy Signal’)
xlabel(app.UIAxes4, ‘frequecny’)
ylabel(app.UIAxes4, ‘magnitude’)
app.UIAxes4.Position = [726 70 414 207];
% Create filterButton
app.filterButton = uibutton(app.UIFigure, ‘push’);
app.filterButton.ButtonPushedFcn = createCallbackFcn(app, @filterButtonPushed, true);
app.filterButton.Position = [103 70 100 22];
app.filterButton.Text = ‘filter’;
% Create UIAxes5
app.UIAxes5 = uiaxes(app.UIFigure);
title(app.UIAxes5, ‘Title’)
xlabel(app.UIAxes5, ‘X’)
ylabel(app.UIAxes5, ‘Y’)
app.UIAxes5.Position = [1170 292 382 197];
% Create UIAxes6
app.UIAxes6 = uiaxes(app.UIFigure);
title(app.UIAxes6, ‘Title’)
xlabel(app.UIAxes6, ‘X’)
ylabel(app.UIAxes6, ‘Y’)
app.UIAxes6.Position = [1170 70 382 207];
% Create showfilteredsignalButton
app.showfilteredsignalButton = uibutton(app.UIFigure, ‘push’);
app.showfilteredsignalButton.ButtonPushedFcn = createCallbackFcn(app, @showfilteredsignalButtonPushed, true);
app.showfilteredsignalButton.Position = [94 32 118 22];
app.showfilteredsignalButton.Text = ‘show filtered signal’;
end
end
methods (Access = public)
% Construct app
function app = app1
% Create and configure components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end I was working on the app in app designer to record audio,add noise, and then filter the noise with suitable filter, for this I also plotted the time domain and frequency domain spectrum of each signal , i also have difficulting in plotting the filtered signal spectrums, like when I added the code to plot the filtered signal , I started encountering the problem, the app in not running.even I can’t close the window! my matlab version is R2018a.
here is my code
classdef app1 < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
UIFigure matlab.ui.Figure
RecordButton matlab.ui.control.Button
durationTextAreaLabel matlab.ui.control.Label
durationTextArea matlab.ui.control.TextArea
playButton matlab.ui.control.Button
UIAxes matlab.ui.control.UIAxes
UIAxes2 matlab.ui.control.UIAxes
wanttoaddnoiseCheckBox matlab.ui.control.CheckBox
ButtonGroup matlab.ui.container.ButtonGroup
noiseaddedButton matlab.ui.control.RadioButton
playnoisysignalButton matlab.ui.control.Button
SNRTextAreaLabel matlab.ui.control.Label
SNRTextArea matlab.ui.control.TextArea
UIAxes3 matlab.ui.control.UIAxes
UIAxes4 matlab.ui.control.UIAxes
filterButton matlab.ui.control.Button
UIAxes5 matlab.ui.control.UIAxes
UIAxes6 matlab.ui.control.UIAxes
showfilteredsignalButton matlab.ui.control.Button
end
properties (Access = private)
% Description
SNR % Description
play % Description
filteredData % Description
Property4 % Description
Property5 % Description
end
methods (Access = private)
function results = func(app)
end
end
methods (Access = private)
% Button pushed function: RecordButton
function RecordButtonPushed(app, event)
audioObject= audiorecorder(44100,16,1);
Duration=str2double(app.durationTextArea.Value{1});
msgbox(‘recording start’);
recordblocking(audioObject,Duration);
msgbox(‘recording stopped’);
assignin(‘base’,’audioObject’,audioObject);
end
% Button pushed function: playButton
function playButtonPushed(app, event)
audioObject=evalin(‘base’,’audioObject’);
audioData=getaudiodata(audioObject);
sound(audioData,audioObject.SampleRate);
audiowrite(‘input_audio.wav’,audioData,44100);
% plotting the audio signal in time domain
t=(0:length(audioData)-1)/44100;
plot(app.UIAxes,t,audioData);
%plotting the amplitude spectrum of audio signal
f_InputData = linspace(-44100/2,44100/2,length(audioData));
INPUTDATA = fft(audioData);
INPUTDATA_f = fftshift(INPUTDATA);
INPUTDATA_f_abs = abs( INPUTDATA_f);
plot(app.UIAxes2,f_InputData,INPUTDATA_f_abs);
end
% Value changed function: wanttoaddnoiseCheckBox
function wanttoaddnoiseCheckBoxValueChanged(app, event)
value = app.wanttoaddnoiseCheckBox.Value;
switch value
case 0
app.noiseaddedButton.Visible = ‘off’;
case 1
app.noiseaddedButton.Visible = ‘on’;
end
end
% Button pushed function: playnoisysignalButton
function playnoisysignalButtonPushed(app, event)
audioObject = evalin(‘base’,’audioObject’);
app.SNR= str2double(app.SNRTextArea.Value{1});
noisyData=awgn(getaudiodata(audioObject),app.SNR,’measured’);
switch app.wanttoaddnoiseCheckBox.Value
case 1
if(app.noiseaddedButton.Value)
app.play = audioplayer(noisyData,44100);
playblocking(app.play);
assignin(‘base’,’noisyData’,noisyData);
%plotting the noisy signal in time domain
audiowrite(‘noisy_input_audio.wav’, noisyData, 44100);
t=(0:length(noisyData)-1)/44100;
plot(app.UIAxes3,t,noisyData);
% plotting amplitude density spectrum of noisy signal
f_InputData = linspace(-44100/2,44100/2,length(noisyData));
INPUTDATA=fft(noisyData);
INPUTDATA_f = fftshift(INPUTDATA);
INPUTDATA_f_abs = abs(INPUTDATA_f);
plot(app.UIAxes4,f_InputData,INPUTDATA_f_abs);
end
case 0
msgbox(‘noise not added’)
end
end
% Button pushed function: filterButton
function filterButtonPushed(app, event)
fc = 4000; % Cut-off frequency in Hz
order = 30; % Filter order
% Design the low-pass filter
[b, a] = butter(order, fc/(44100/2), ‘low’);
% Apply the filter to the noisy audio signal
noisyData = evalin(‘base’,’noisyData’);
v_filtered = filter(b, a,noisyData);
% Play the filtered audio
app.filteredData = audioplayer(v_filtered, 44100);
playblocking(app.filteredData);
assignin(‘base’,’v_filtered’,v_filtered);
v_filtered = evalin(‘base’,’v_filtered’);
end
% Button pushed function: showfilteredsignalButton
function showfilteredsignalButtonPushed(app, event)
v_filtered = evalin(‘base’,’v_filtered’);
audiowrite(‘filtered_audio.wav’,v_filtered, 44100);
t_filt= (0:length(app.filteredData)-1)/44100;
plot(app.UIAxes5,t_filt,v_filtered);
end
end
% App initialization and construction
methods (Access = private)
% Create UIFigure and components
function createComponents(app)
% Create UIFigure
app.UIFigure = uifigure;
app.UIFigure.Position = [100 100 1523 509];
app.UIFigure.Name = ‘UI Figure’;
% Create RecordButton
app.RecordButton = uibutton(app.UIFigure, ‘push’);
app.RecordButton.ButtonPushedFcn = createCallbackFcn(app, @RecordButtonPushed, true);
app.RecordButton.Position = [39 440 100 22];
app.RecordButton.Text = ‘Record’;
% Create durationTextAreaLabel
app.durationTextAreaLabel = uilabel(app.UIFigure);
app.durationTextAreaLabel.HorizontalAlignment = ‘right’;
app.durationTextAreaLabel.Position = [39 406 49 22];
app.durationTextAreaLabel.Text = ‘duration’;
% Create durationTextArea
app.durationTextArea = uitextarea(app.UIFigure);
app.durationTextArea.HorizontalAlignment = ‘right’;
app.durationTextArea.Position = [103 404 139 26];
app.durationTextArea.Value = {’10’};
% Create playButton
app.playButton = uibutton(app.UIFigure, ‘push’);
app.playButton.ButtonPushedFcn = createCallbackFcn(app, @playButtonPushed, true);
app.playButton.Position = [39 361 100 22];
app.playButton.Text = ‘play’;
% Create UIAxes
app.UIAxes = uiaxes(app.UIFigure);
title(app.UIAxes, ‘Input Audio Signal’)
xlabel(app.UIAxes, ‘time’)
ylabel(app.UIAxes, ‘magnitude’)
app.UIAxes.Position = [251 292 444 197];
% Create UIAxes2
app.UIAxes2 = uiaxes(app.UIFigure);
title(app.UIAxes2, ‘Amplitude Density spectrum of Audio Signal’)
xlabel(app.UIAxes2, ‘frequency’)
ylabel(app.UIAxes2, ‘magnitude’)
app.UIAxes2.Position = [255 70 436 207];
% Create wanttoaddnoiseCheckBox
app.wanttoaddnoiseCheckBox = uicheckbox(app.UIFigure);
app.wanttoaddnoiseCheckBox.ValueChangedFcn = createCallbackFcn(app, @wanttoaddnoiseCheckBoxValueChanged, true);
app.wanttoaddnoiseCheckBox.Text = ‘want to add noise?’;
app.wanttoaddnoiseCheckBox.Position = [75 276 123 22];
% Create ButtonGroup
app.ButtonGroup = uibuttongroup(app.UIFigure);
app.ButtonGroup.BorderType = ‘none’;
app.ButtonGroup.Position = [64 227 123 30];
% Create noiseaddedButton
app.noiseaddedButton = uiradiobutton(app.ButtonGroup);
app.noiseaddedButton.Visible = ‘off’;
app.noiseaddedButton.Text = ‘noise added’;
app.noiseaddedButton.Position = [11 4 87 22];
app.noiseaddedButton.Value = true;
% Create playnoisysignalButton
app.playnoisysignalButton = uibutton(app.UIFigure, ‘push’);
app.playnoisysignalButton.ButtonPushedFcn = createCallbackFcn(app, @playnoisysignalButtonPushed, true);
app.playnoisysignalButton.Position = [89 144 104 22];
app.playnoisysignalButton.Text = ‘play noisy signal’;
% Create SNRTextAreaLabel
app.SNRTextAreaLabel = uilabel(app.UIFigure);
app.SNRTextAreaLabel.HorizontalAlignment = ‘right’;
app.SNRTextAreaLabel.Position = [64 185 31 22];
app.SNRTextAreaLabel.Text = ‘SNR’;
% Create SNRTextArea
app.SNRTextArea = uitextarea(app.UIFigure);
app.SNRTextArea.HorizontalAlignment = ‘right’;
app.SNRTextArea.Position = [110 185 77 24];
app.SNRTextArea.Value = {’12’};
% Create UIAxes3
app.UIAxes3 = uiaxes(app.UIFigure);
title(app.UIAxes3, ‘Noisy signal’)
xlabel(app.UIAxes3, ‘time’)
ylabel(app.UIAxes3, ‘magnitude’)
app.UIAxes3.Position = [726 292 414 197];
% Create UIAxes4
app.UIAxes4 = uiaxes(app.UIFigure);
title(app.UIAxes4, ‘Amplitude Density spectrum of Noisy Signal’)
xlabel(app.UIAxes4, ‘frequecny’)
ylabel(app.UIAxes4, ‘magnitude’)
app.UIAxes4.Position = [726 70 414 207];
% Create filterButton
app.filterButton = uibutton(app.UIFigure, ‘push’);
app.filterButton.ButtonPushedFcn = createCallbackFcn(app, @filterButtonPushed, true);
app.filterButton.Position = [103 70 100 22];
app.filterButton.Text = ‘filter’;
% Create UIAxes5
app.UIAxes5 = uiaxes(app.UIFigure);
title(app.UIAxes5, ‘Title’)
xlabel(app.UIAxes5, ‘X’)
ylabel(app.UIAxes5, ‘Y’)
app.UIAxes5.Position = [1170 292 382 197];
% Create UIAxes6
app.UIAxes6 = uiaxes(app.UIFigure);
title(app.UIAxes6, ‘Title’)
xlabel(app.UIAxes6, ‘X’)
ylabel(app.UIAxes6, ‘Y’)
app.UIAxes6.Position = [1170 70 382 207];
% Create showfilteredsignalButton
app.showfilteredsignalButton = uibutton(app.UIFigure, ‘push’);
app.showfilteredsignalButton.ButtonPushedFcn = createCallbackFcn(app, @showfilteredsignalButtonPushed, true);
app.showfilteredsignalButton.Position = [94 32 118 22];
app.showfilteredsignalButton.Text = ‘show filtered signal’;
end
end
methods (Access = public)
% Construct app
function app = app1
% Create and configure components
createComponents(app)
% Register the app with App Designer
registerApp(app, app.UIFigure)
if nargout == 0
clear app
end
end
% Code that executes before app deletion
function delete(app)
% Delete UIFigure when app is deleted
delete(app.UIFigure)
end
end
end appdesigner, audio processing, audio filtering, matlab app designer code, matlab gui, matlab app designer, audio signal plotting, callback, app designer callback, app designer not responding MATLAB Answers — New Questions
the matrix only works till days= 16 then when the days=17 or bigger the output is 0 on all the values in the matrix
% solar irradiation on a HORIZONTAL SURFACE
Cn = 0.7; % Clearance index
I0 = 1353; % Solar constant
latitude = -34.005133; % Latitude of the location
days =31; % Number of days in the month
hours = 24; % Number of hours in a day
% Initialize matrices to store results
dec_deg = zeros(days, 1); % Declination angles in degrees
DNI = zeros(days, hours); % Direct Normal Irradiation
DHI = zeros(days, hours); % Diffuse Horizontal Irradiance
GHI = zeros(days, hours); % Global Horizontal Irradiance
for n = 1:days
% Calculate declination angle for the day (in degrees)
dec_deg(n) = 23.45 * sind((360/365) * (n + 284));
% Convert declination angle from degrees to radians
dec_rad = deg2rad(dec_deg(n));
for time = 1:hours
% Calculate hour angle
h = (12 – time) * 15; % Hour angle in degrees
h_rad = deg2rad(h); % Hour angle in radians
% Calculate diffuse factor (Cs)
Cs = 0.095 + 0.04 * sin(deg2rad(360/365) * (n – 100));
% Calculate extraterrestrial solar irradiation (I)
I = I0 * (1 + 0.034 * cos(deg2rad(360 * n / 365.25)));
% Calculate atmospheric optical depth (k)
k = 0.174 + 0.035 * sin(deg2rad((360/365) * (n – 100)));
% Calculate solar altitude angle (alt)
Lat = deg2rad(latitude); % Latitude angle in radians
alt = asin(cos(Lat) * cos(dec_rad) * cos(h_rad) + (sin(Lat) * sin(dec_rad)));
alt_deg = rad2deg(alt); % Daily Solar Altitude Angle
% Calculate air mass (AM)
AM = 1 / sin(deg2rad(alt_deg)); % Air Mass
% Calculate Direct Normal Irradiation (DNI) for the current hour
DNI(n, time) = Cn * I * exp(-k * AM);
% Calculate Diffuse Horizontal Irradiance (DHI) for the current hour
DHI(n, time) = Cs * DNI(n, time);
% Calculate Global Horizontal Irradiance (GHI) for the current hour
GHI(n, time) = (DNI(n, time) + DHI(n, time)) / 1000;
end
end
%% Format changed
format longg
% Display matrices
disp("Direct Normal Irradiation (DNI) for 31 days (24 hours each): ");
disp(DNI);
disp("Diffuse Horizontal Irradiance (DHI) for 31 days (24 hours each): ");
disp(DHI);
disp("Global Horizontal Irradiance (GHI) for 31 days (24 hours each): ");
disp(GHI);
the display is 0 in the matrix for all 31 days but when the days=16 there is an output. if days=17 the output starts to be 0% solar irradiation on a HORIZONTAL SURFACE
Cn = 0.7; % Clearance index
I0 = 1353; % Solar constant
latitude = -34.005133; % Latitude of the location
days =31; % Number of days in the month
hours = 24; % Number of hours in a day
% Initialize matrices to store results
dec_deg = zeros(days, 1); % Declination angles in degrees
DNI = zeros(days, hours); % Direct Normal Irradiation
DHI = zeros(days, hours); % Diffuse Horizontal Irradiance
GHI = zeros(days, hours); % Global Horizontal Irradiance
for n = 1:days
% Calculate declination angle for the day (in degrees)
dec_deg(n) = 23.45 * sind((360/365) * (n + 284));
% Convert declination angle from degrees to radians
dec_rad = deg2rad(dec_deg(n));
for time = 1:hours
% Calculate hour angle
h = (12 – time) * 15; % Hour angle in degrees
h_rad = deg2rad(h); % Hour angle in radians
% Calculate diffuse factor (Cs)
Cs = 0.095 + 0.04 * sin(deg2rad(360/365) * (n – 100));
% Calculate extraterrestrial solar irradiation (I)
I = I0 * (1 + 0.034 * cos(deg2rad(360 * n / 365.25)));
% Calculate atmospheric optical depth (k)
k = 0.174 + 0.035 * sin(deg2rad((360/365) * (n – 100)));
% Calculate solar altitude angle (alt)
Lat = deg2rad(latitude); % Latitude angle in radians
alt = asin(cos(Lat) * cos(dec_rad) * cos(h_rad) + (sin(Lat) * sin(dec_rad)));
alt_deg = rad2deg(alt); % Daily Solar Altitude Angle
% Calculate air mass (AM)
AM = 1 / sin(deg2rad(alt_deg)); % Air Mass
% Calculate Direct Normal Irradiation (DNI) for the current hour
DNI(n, time) = Cn * I * exp(-k * AM);
% Calculate Diffuse Horizontal Irradiance (DHI) for the current hour
DHI(n, time) = Cs * DNI(n, time);
% Calculate Global Horizontal Irradiance (GHI) for the current hour
GHI(n, time) = (DNI(n, time) + DHI(n, time)) / 1000;
end
end
%% Format changed
format longg
% Display matrices
disp("Direct Normal Irradiation (DNI) for 31 days (24 hours each): ");
disp(DNI);
disp("Diffuse Horizontal Irradiance (DHI) for 31 days (24 hours each): ");
disp(DHI);
disp("Global Horizontal Irradiance (GHI) for 31 days (24 hours each): ");
disp(GHI);
the display is 0 in the matrix for all 31 days but when the days=16 there is an output. if days=17 the output starts to be 0 % solar irradiation on a HORIZONTAL SURFACE
Cn = 0.7; % Clearance index
I0 = 1353; % Solar constant
latitude = -34.005133; % Latitude of the location
days =31; % Number of days in the month
hours = 24; % Number of hours in a day
% Initialize matrices to store results
dec_deg = zeros(days, 1); % Declination angles in degrees
DNI = zeros(days, hours); % Direct Normal Irradiation
DHI = zeros(days, hours); % Diffuse Horizontal Irradiance
GHI = zeros(days, hours); % Global Horizontal Irradiance
for n = 1:days
% Calculate declination angle for the day (in degrees)
dec_deg(n) = 23.45 * sind((360/365) * (n + 284));
% Convert declination angle from degrees to radians
dec_rad = deg2rad(dec_deg(n));
for time = 1:hours
% Calculate hour angle
h = (12 – time) * 15; % Hour angle in degrees
h_rad = deg2rad(h); % Hour angle in radians
% Calculate diffuse factor (Cs)
Cs = 0.095 + 0.04 * sin(deg2rad(360/365) * (n – 100));
% Calculate extraterrestrial solar irradiation (I)
I = I0 * (1 + 0.034 * cos(deg2rad(360 * n / 365.25)));
% Calculate atmospheric optical depth (k)
k = 0.174 + 0.035 * sin(deg2rad((360/365) * (n – 100)));
% Calculate solar altitude angle (alt)
Lat = deg2rad(latitude); % Latitude angle in radians
alt = asin(cos(Lat) * cos(dec_rad) * cos(h_rad) + (sin(Lat) * sin(dec_rad)));
alt_deg = rad2deg(alt); % Daily Solar Altitude Angle
% Calculate air mass (AM)
AM = 1 / sin(deg2rad(alt_deg)); % Air Mass
% Calculate Direct Normal Irradiation (DNI) for the current hour
DNI(n, time) = Cn * I * exp(-k * AM);
% Calculate Diffuse Horizontal Irradiance (DHI) for the current hour
DHI(n, time) = Cs * DNI(n, time);
% Calculate Global Horizontal Irradiance (GHI) for the current hour
GHI(n, time) = (DNI(n, time) + DHI(n, time)) / 1000;
end
end
%% Format changed
format longg
% Display matrices
disp("Direct Normal Irradiation (DNI) for 31 days (24 hours each): ");
disp(DNI);
disp("Diffuse Horizontal Irradiance (DHI) for 31 days (24 hours each): ");
disp(DHI);
disp("Global Horizontal Irradiance (GHI) for 31 days (24 hours each): ");
disp(GHI);
the display is 0 in the matrix for all 31 days but when the days=16 there is an output. if days=17 the output starts to be 0 matrices MATLAB Answers — New Questions
pinv operation in matlab
I have a matrix X of size [32X32X10]. I want to do pinv(X). But it suggested to use pagesvd(X). Now the dimension becomes [32X1X10]. However I want the matrix dimension to remain same that is [32X32X10].I have a matrix X of size [32X32X10]. I want to do pinv(X). But it suggested to use pagesvd(X). Now the dimension becomes [32X1X10]. However I want the matrix dimension to remain same that is [32X32X10]. I have a matrix X of size [32X32X10]. I want to do pinv(X). But it suggested to use pagesvd(X). Now the dimension becomes [32X1X10]. However I want the matrix dimension to remain same that is [32X32X10]. matrix, pinv, pagesvd MATLAB Answers — New Questions
Failed to use C caller to run customer code
hello, when i try to use the customer code in simulink through C caller, error happens, know how to resolve it.hello, when i try to use the customer code in simulink through C caller, error happens, know how to resolve it. hello, when i try to use the customer code in simulink through C caller, error happens, know how to resolve it. simulink, c caller MATLAB Answers — New Questions
find a zero of a two-variable function
my main.m is:
clear
clc
close all
%
X0 = [9.609 , 32.288]; %initial value close to zero of function
%
f = Trajectory(X0);
The script Trajectory.m is a messy think that returns a value of f. I want to find values of tht two input variables (X0) is the initial vbalues that give f=0my main.m is:
clear
clc
close all
%
X0 = [9.609 , 32.288]; %initial value close to zero of function
%
f = Trajectory(X0);
The script Trajectory.m is a messy think that returns a value of f. I want to find values of tht two input variables (X0) is the initial vbalues that give f=0 my main.m is:
clear
clc
close all
%
X0 = [9.609 , 32.288]; %initial value close to zero of function
%
f = Trajectory(X0);
The script Trajectory.m is a messy think that returns a value of f. I want to find values of tht two input variables (X0) is the initial vbalues that give f=0 zoro of two-variable function MATLAB Answers — New Questions
problem reading wav file
hi,
I created a folder in drive C on users. I copied the audio file .wav in it. i opened live Editor and did Alt/enter to create a text area and typed ‘Assignment’. I then pressed Ctrl S to save it as ‘Assignment _task’ mlx onto the ‘Assignment’ folder in C. both the audio file and Mxs file appeared on matlab’s ‘my folder’. I then pressed Alt/enter to get into Code area. In Code area, i typed ‘audioread(‘the wav file’) and pressed Ctrl /enter. I came out with error as follows:
Error using audioread>readaudio (line 157)
The file type is not supported
Error in audioread (line 136)
[y, Fs] = readaudio (filename, range, datatype);
my question are 1./ of how can i get the ‘range’ and know the ‘datatype’?2./ why it said ‘audioread>readaudio and error in ‘audioread’ 3./ am i supposed to get x and Fs and rows and column?
Can anyone help me of how to read the audio please?
thank you
D.Ahi,
I created a folder in drive C on users. I copied the audio file .wav in it. i opened live Editor and did Alt/enter to create a text area and typed ‘Assignment’. I then pressed Ctrl S to save it as ‘Assignment _task’ mlx onto the ‘Assignment’ folder in C. both the audio file and Mxs file appeared on matlab’s ‘my folder’. I then pressed Alt/enter to get into Code area. In Code area, i typed ‘audioread(‘the wav file’) and pressed Ctrl /enter. I came out with error as follows:
Error using audioread>readaudio (line 157)
The file type is not supported
Error in audioread (line 136)
[y, Fs] = readaudio (filename, range, datatype);
my question are 1./ of how can i get the ‘range’ and know the ‘datatype’?2./ why it said ‘audioread>readaudio and error in ‘audioread’ 3./ am i supposed to get x and Fs and rows and column?
Can anyone help me of how to read the audio please?
thank you
D.A hi,
I created a folder in drive C on users. I copied the audio file .wav in it. i opened live Editor and did Alt/enter to create a text area and typed ‘Assignment’. I then pressed Ctrl S to save it as ‘Assignment _task’ mlx onto the ‘Assignment’ folder in C. both the audio file and Mxs file appeared on matlab’s ‘my folder’. I then pressed Alt/enter to get into Code area. In Code area, i typed ‘audioread(‘the wav file’) and pressed Ctrl /enter. I came out with error as follows:
Error using audioread>readaudio (line 157)
The file type is not supported
Error in audioread (line 136)
[y, Fs] = readaudio (filename, range, datatype);
my question are 1./ of how can i get the ‘range’ and know the ‘datatype’?2./ why it said ‘audioread>readaudio and error in ‘audioread’ 3./ am i supposed to get x and Fs and rows and column?
Can anyone help me of how to read the audio please?
thank you
D.A audio read MATLAB Answers — New Questions
connection between matlab 2024a and arduino
Hi everyone.I want to turn on an LED using serial communication. The problem is when i give 0 ( for turn off ) and 1 ( for turn on ) in arduino IDE it works, But if these two numbers are taken from MATLAB, the LED will not light up. Can anyone tell me why this happens. Arduino and MATLAB codes are attached. thanks for your help.Hi everyone.I want to turn on an LED using serial communication. The problem is when i give 0 ( for turn off ) and 1 ( for turn on ) in arduino IDE it works, But if these two numbers are taken from MATLAB, the LED will not light up. Can anyone tell me why this happens. Arduino and MATLAB codes are attached. thanks for your help. Hi everyone.I want to turn on an LED using serial communication. The problem is when i give 0 ( for turn off ) and 1 ( for turn on ) in arduino IDE it works, But if these two numbers are taken from MATLAB, the LED will not light up. Can anyone tell me why this happens. Arduino and MATLAB codes are attached. thanks for your help. arduino, matlab MATLAB Answers — New Questions
Invalid argument name classificationmode name must be targetcategories, mask etc.
While using this code from Complex yolo document in R2023a version
doTraining = true;
if doTraining
iteration = 0;
% Create subplots for the learning rate and mini-batch loss.
fig = figure;
[lossPlotter, learningRatePlotter] = configureTrainingProgressPlotter(fig);
% Custom training loop.
for epoch = 1:maxEpochs
reset(mbqTrain);
shuffle(mbqTrain);
while(hasdata(mbqTrain))
iteration = iteration + 1;
[XTrain,YTrain] = next(mbqTrain);
% Evaluate the model gradients and loss using dlfeval and the
% modelGradients function.
[gradients,state,lossInfo] = dlfeval(@modelGradients,net,XTrain,YTrain,anchorBoxes,penaltyThreshold,networkOutputs);
% Apply L2 regularization.
gradients = dlupdate(@(g,w) g + l2Regularization*w, gradients, net.Learnables);
% Determine the current learning rate value.
currentLR = piecewiseLearningRateWithWarmup(iteration,epoch,learningRate,warmupPeriod,maxEpochs);
% Update the network learnable parameters using the SGDM optimizer.
[net,velocity] = sgdmupdate(net,gradients,velocity,currentLR);
% Update the state parameters of dlnetwork.
net.State = state;
% Display progress.
if mod(iteration,10)==1
displayLossInfo(epoch,iteration,currentLR,lossInfo);
end
% Update training plot with new points.
updatePlots(lossPlotter,learningRatePlotter,iteration,currentLR,lossInfo.totalLoss);
end
end
else
net = mdl.net;
anchorBoxes = mdl.anchorBoxes;
end
% Create a table to hold the bounding boxes, scores, and labels returned by
% the detector.
results = table(‘Size’,[0 3], …
‘VariableTypes’,{‘cell’,’cell’,’cell’}, …
‘VariableNames’,{‘Boxes’,’Scores’,’Labels’});
% Run the detector on images in the test set and collect the results.
reset(testData)
while hasdata(testData)
% Read the datastore and get the image.
data = read(testData);
image = data{1,1};
% Run the detector.
executionEnvironment = ‘auto’;
[bboxes,scores,labels] = detectComplexYOLOv4(net,image,anchorBoxes,classNames,executionEnvironment);
% Collect the results.
tbl = table({bboxes},{scores},{labels},’VariableNames’,{‘Boxes’,’Scores’,’Labels’});
results = [results; tbl];
end
% Evaluate the object detector using the average precision metric.
metrics = evaluateDetectionAOS(results, testData)
Got this error
Error using dlarray/crossentropy
Invalid argument name ‘ClassificationMode’. Name must be ‘TargetCategories’, ‘Mask’, ‘Reduction’, ‘NormalizationFactor’, ‘DataFormat’, or ‘WeightsFormat’.
Error in complexYolotrial>@(a,b,c)crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’) (line 400)
objLoss = sum(cellfun(@(a,b,c) crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’),objectnessPredCell,objectnessDeltaTarget,boxMaskTarget(:,2)));
Error in complexYolotrial>objectnessLoss (line 400)
objLoss = sum(cellfun(@(a,b,c) crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’),objectnessPredCell,objectnessDeltaTarget,boxMaskTarget(:,2)));
Error in complexYolotrial>modelGradients (line 339)
objLoss = objectnessLoss(YPredCell(:,1),objectnessTarget,objectMaskTarget);
Error in deep.internal.dlfeval (line 17)
[varargout{1:nargout}] = fun(x{:});
Error in deep.internal.dlfevalWithNestingCheck (line 15)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
Error in dlfeval (line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:}); how to resolve itWhile using this code from Complex yolo document in R2023a version
doTraining = true;
if doTraining
iteration = 0;
% Create subplots for the learning rate and mini-batch loss.
fig = figure;
[lossPlotter, learningRatePlotter] = configureTrainingProgressPlotter(fig);
% Custom training loop.
for epoch = 1:maxEpochs
reset(mbqTrain);
shuffle(mbqTrain);
while(hasdata(mbqTrain))
iteration = iteration + 1;
[XTrain,YTrain] = next(mbqTrain);
% Evaluate the model gradients and loss using dlfeval and the
% modelGradients function.
[gradients,state,lossInfo] = dlfeval(@modelGradients,net,XTrain,YTrain,anchorBoxes,penaltyThreshold,networkOutputs);
% Apply L2 regularization.
gradients = dlupdate(@(g,w) g + l2Regularization*w, gradients, net.Learnables);
% Determine the current learning rate value.
currentLR = piecewiseLearningRateWithWarmup(iteration,epoch,learningRate,warmupPeriod,maxEpochs);
% Update the network learnable parameters using the SGDM optimizer.
[net,velocity] = sgdmupdate(net,gradients,velocity,currentLR);
% Update the state parameters of dlnetwork.
net.State = state;
% Display progress.
if mod(iteration,10)==1
displayLossInfo(epoch,iteration,currentLR,lossInfo);
end
% Update training plot with new points.
updatePlots(lossPlotter,learningRatePlotter,iteration,currentLR,lossInfo.totalLoss);
end
end
else
net = mdl.net;
anchorBoxes = mdl.anchorBoxes;
end
% Create a table to hold the bounding boxes, scores, and labels returned by
% the detector.
results = table(‘Size’,[0 3], …
‘VariableTypes’,{‘cell’,’cell’,’cell’}, …
‘VariableNames’,{‘Boxes’,’Scores’,’Labels’});
% Run the detector on images in the test set and collect the results.
reset(testData)
while hasdata(testData)
% Read the datastore and get the image.
data = read(testData);
image = data{1,1};
% Run the detector.
executionEnvironment = ‘auto’;
[bboxes,scores,labels] = detectComplexYOLOv4(net,image,anchorBoxes,classNames,executionEnvironment);
% Collect the results.
tbl = table({bboxes},{scores},{labels},’VariableNames’,{‘Boxes’,’Scores’,’Labels’});
results = [results; tbl];
end
% Evaluate the object detector using the average precision metric.
metrics = evaluateDetectionAOS(results, testData)
Got this error
Error using dlarray/crossentropy
Invalid argument name ‘ClassificationMode’. Name must be ‘TargetCategories’, ‘Mask’, ‘Reduction’, ‘NormalizationFactor’, ‘DataFormat’, or ‘WeightsFormat’.
Error in complexYolotrial>@(a,b,c)crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’) (line 400)
objLoss = sum(cellfun(@(a,b,c) crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’),objectnessPredCell,objectnessDeltaTarget,boxMaskTarget(:,2)));
Error in complexYolotrial>objectnessLoss (line 400)
objLoss = sum(cellfun(@(a,b,c) crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’),objectnessPredCell,objectnessDeltaTarget,boxMaskTarget(:,2)));
Error in complexYolotrial>modelGradients (line 339)
objLoss = objectnessLoss(YPredCell(:,1),objectnessTarget,objectMaskTarget);
Error in deep.internal.dlfeval (line 17)
[varargout{1:nargout}] = fun(x{:});
Error in deep.internal.dlfevalWithNestingCheck (line 15)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
Error in dlfeval (line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:}); how to resolve it While using this code from Complex yolo document in R2023a version
doTraining = true;
if doTraining
iteration = 0;
% Create subplots for the learning rate and mini-batch loss.
fig = figure;
[lossPlotter, learningRatePlotter] = configureTrainingProgressPlotter(fig);
% Custom training loop.
for epoch = 1:maxEpochs
reset(mbqTrain);
shuffle(mbqTrain);
while(hasdata(mbqTrain))
iteration = iteration + 1;
[XTrain,YTrain] = next(mbqTrain);
% Evaluate the model gradients and loss using dlfeval and the
% modelGradients function.
[gradients,state,lossInfo] = dlfeval(@modelGradients,net,XTrain,YTrain,anchorBoxes,penaltyThreshold,networkOutputs);
% Apply L2 regularization.
gradients = dlupdate(@(g,w) g + l2Regularization*w, gradients, net.Learnables);
% Determine the current learning rate value.
currentLR = piecewiseLearningRateWithWarmup(iteration,epoch,learningRate,warmupPeriod,maxEpochs);
% Update the network learnable parameters using the SGDM optimizer.
[net,velocity] = sgdmupdate(net,gradients,velocity,currentLR);
% Update the state parameters of dlnetwork.
net.State = state;
% Display progress.
if mod(iteration,10)==1
displayLossInfo(epoch,iteration,currentLR,lossInfo);
end
% Update training plot with new points.
updatePlots(lossPlotter,learningRatePlotter,iteration,currentLR,lossInfo.totalLoss);
end
end
else
net = mdl.net;
anchorBoxes = mdl.anchorBoxes;
end
% Create a table to hold the bounding boxes, scores, and labels returned by
% the detector.
results = table(‘Size’,[0 3], …
‘VariableTypes’,{‘cell’,’cell’,’cell’}, …
‘VariableNames’,{‘Boxes’,’Scores’,’Labels’});
% Run the detector on images in the test set and collect the results.
reset(testData)
while hasdata(testData)
% Read the datastore and get the image.
data = read(testData);
image = data{1,1};
% Run the detector.
executionEnvironment = ‘auto’;
[bboxes,scores,labels] = detectComplexYOLOv4(net,image,anchorBoxes,classNames,executionEnvironment);
% Collect the results.
tbl = table({bboxes},{scores},{labels},’VariableNames’,{‘Boxes’,’Scores’,’Labels’});
results = [results; tbl];
end
% Evaluate the object detector using the average precision metric.
metrics = evaluateDetectionAOS(results, testData)
Got this error
Error using dlarray/crossentropy
Invalid argument name ‘ClassificationMode’. Name must be ‘TargetCategories’, ‘Mask’, ‘Reduction’, ‘NormalizationFactor’, ‘DataFormat’, or ‘WeightsFormat’.
Error in complexYolotrial>@(a,b,c)crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’) (line 400)
objLoss = sum(cellfun(@(a,b,c) crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’),objectnessPredCell,objectnessDeltaTarget,boxMaskTarget(:,2)));
Error in complexYolotrial>objectnessLoss (line 400)
objLoss = sum(cellfun(@(a,b,c) crossentropy(a.*c,b.*c,’ClassificationMode’,’multilabel’),objectnessPredCell,objectnessDeltaTarget,boxMaskTarget(:,2)));
Error in complexYolotrial>modelGradients (line 339)
objLoss = objectnessLoss(YPredCell(:,1),objectnessTarget,objectMaskTarget);
Error in deep.internal.dlfeval (line 17)
[varargout{1:nargout}] = fun(x{:});
Error in deep.internal.dlfevalWithNestingCheck (line 15)
[varargout{1:nargout}] = deep.internal.dlfeval(fun,varargin{:});
Error in dlfeval (line 31)
[varargout{1:nargout}] = deep.internal.dlfevalWithNestingCheck(fun,varargin{:}); how to resolve it deep learning MATLAB Answers — New Questions
3d matrix initialization and find the specific values after the for loops
Hello my Vf is 42444 *1*1000 matrix. I used this code for finding values for the location of 312 and incrementing of 324 from the 42444 values. But why the final matrix A is 131 * 3*1000. I am expecting 131*1*1000.
Could you help me on that?
Vf= is a 3d matix of 42444 * 1 * 1000;
m = size(Vf, 1)= 42444;
n = size(Vf, 2)= 1;
p = size(Vf, 3)=1000;
A=[m,n,p];
% Loop through the data and fill A
for j = 1:p
index = 1;
for i = 312:324:m
% Assign the value from Vf to the corresponding location in A
A(index, :, j) = Vf(i, :, j);
index = index + 1;
end
endHello my Vf is 42444 *1*1000 matrix. I used this code for finding values for the location of 312 and incrementing of 324 from the 42444 values. But why the final matrix A is 131 * 3*1000. I am expecting 131*1*1000.
Could you help me on that?
Vf= is a 3d matix of 42444 * 1 * 1000;
m = size(Vf, 1)= 42444;
n = size(Vf, 2)= 1;
p = size(Vf, 3)=1000;
A=[m,n,p];
% Loop through the data and fill A
for j = 1:p
index = 1;
for i = 312:324:m
% Assign the value from Vf to the corresponding location in A
A(index, :, j) = Vf(i, :, j);
index = index + 1;
end
end Hello my Vf is 42444 *1*1000 matrix. I used this code for finding values for the location of 312 and incrementing of 324 from the 42444 values. But why the final matrix A is 131 * 3*1000. I am expecting 131*1*1000.
Could you help me on that?
Vf= is a 3d matix of 42444 * 1 * 1000;
m = size(Vf, 1)= 42444;
n = size(Vf, 2)= 1;
p = size(Vf, 3)=1000;
A=[m,n,p];
% Loop through the data and fill A
for j = 1:p
index = 1;
for i = 312:324:m
% Assign the value from Vf to the corresponding location in A
A(index, :, j) = Vf(i, :, j);
index = index + 1;
end
end matlab, 3d matix MATLAB Answers — New Questions
Custom Display for symbolic Object
Hello,
I do alot of work with symbolic variables and latex, and I would like to have some custom output for when a semi colon is not put at the end of a line, I would like it to output the formated version of the symbolic variable so that I can use the copy as LaTeX. An example of how I would like it displayed is below, when I run the line sigma_i = 10*u.MPa I would like it to be displayed as if I had run myFunc.
u =symunit;
sigma_i =10*u.MPa
myFunc(sigma_i)
function myFunc(inputValue)
varName = inputname(1);
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == inputValue, 3)); % Adjust the precision as needed
end
I have tried creating class MySym which inherits from sym but whenever I do any operations the output ends up being a sym
classdef MySym < sym
methods
% Constructor method
function obj = MySym(val)
% Convert input to sym and store it in the object
obj = obj@sym(val); % Call superclass constructor
end
% Custom display method
function display(obj)
varName = inputname(1);
if isempty(varName)
varName = ‘ans’;
end
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == obj, 3)); % Display with 3 digits precision
end
end
endHello,
I do alot of work with symbolic variables and latex, and I would like to have some custom output for when a semi colon is not put at the end of a line, I would like it to output the formated version of the symbolic variable so that I can use the copy as LaTeX. An example of how I would like it displayed is below, when I run the line sigma_i = 10*u.MPa I would like it to be displayed as if I had run myFunc.
u =symunit;
sigma_i =10*u.MPa
myFunc(sigma_i)
function myFunc(inputValue)
varName = inputname(1);
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == inputValue, 3)); % Adjust the precision as needed
end
I have tried creating class MySym which inherits from sym but whenever I do any operations the output ends up being a sym
classdef MySym < sym
methods
% Constructor method
function obj = MySym(val)
% Convert input to sym and store it in the object
obj = obj@sym(val); % Call superclass constructor
end
% Custom display method
function display(obj)
varName = inputname(1);
if isempty(varName)
varName = ‘ans’;
end
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == obj, 3)); % Display with 3 digits precision
end
end
end Hello,
I do alot of work with symbolic variables and latex, and I would like to have some custom output for when a semi colon is not put at the end of a line, I would like it to output the formated version of the symbolic variable so that I can use the copy as LaTeX. An example of how I would like it displayed is below, when I run the line sigma_i = 10*u.MPa I would like it to be displayed as if I had run myFunc.
u =symunit;
sigma_i =10*u.MPa
myFunc(sigma_i)
function myFunc(inputValue)
varName = inputname(1);
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == inputValue, 3)); % Adjust the precision as needed
end
I have tried creating class MySym which inherits from sym but whenever I do any operations the output ends up being a sym
classdef MySym < sym
methods
% Constructor method
function obj = MySym(val)
% Convert input to sym and store it in the object
obj = obj@sym(val); % Call superclass constructor
end
% Custom display method
function display(obj)
varName = inputname(1);
if isempty(varName)
varName = ‘ans’;
end
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == obj, 3)); % Display with 3 digits precision
end
end
end symbolic variables, custom displaying MATLAB Answers — New Questions
Axis does not plot in app designer
I am making an application in app designer where I use two graphs to show the PWM of a digital controller, the UIAxes of the controller response works fine, but the PWM does not show the graph even when the axes are updated normally.
usada = app.PlacaDropDown.Value;
pcom = app.PuertoCOMEditField.Value;
elcom = strcat(‘COM’, pcom);
app.a = arduino(elcom, usada);
app.parar = false;
app.file_path = uiputfile(‘*.csv’, ‘Guardar como’);
i = 1;
H1 = 0;
H2 = 0;
selectedTab = app.TabGroup.SelectedTab;
titulo = selectedTab.Title;
switch titulo
case ‘P’
K = app.K_P.Value;
t = app.T_P.Value;
q0 = K;
q1 = 0.0;
q2 = 0.0;
case ‘PI’
K = app.K_PI.Value;
Ti = app.Ti_PI.Value;
t = app.T_PI.Value;
q0 = K * ( 1 + t/2*Ti );
q1 = -K * ( 1 – t/2*Ti );
q2 = 0.0;
case ‘PID’
K = app.K_PID.Value;
Ti = app.Ti_PID.Value;
Td = app.Td_PID.Value;
t = app.T_PID.Value;
q0 = K * (1 + t/2*Ti + Td/t );
q1 = -K * (1 – t/2*Ti + 2*Td/t );
q2 = K*Td/t;
end
while ~app.parar
muestra(i) = i;
lectura1(i) = readVoltage(app.a,’A1′)* 25;
lectura2(i) = readVoltage(app.a,’A2′)* 25;
if lectura1 >= 40
writeDigitalPin(app.a, ‘D7’, 1);
else
writeDigitalPin(app.a, ‘D7’, 0);
end
if lectura2 >= 40
writeDigitalPin(app.a,’D8′,1);
else
writeDigitalPin(app.a, ‘D8’, 0);
end
if app.Q1CheckBox.Value
%Actualizacion del vector de error (etapa 1).
app.e1(1) = app.e1(2);
app.e1(2) = app.e1(3);
app.e1(3) = app.tempRef.Value – lectura1(i);
%Actualizacion del vector de control (etapa 1).
app.u1(1) = app.u1(2);
app.u1(2) = ControlPID(app.u1, app.e1, q0, q1, q2);
H1 = app.u1(2) / 100; %Se mapea el PWM obtenico para enviarlo al arduino.
writePWMDutyCycle(app.a, ‘D11’, H1);
end
if app.Q2CheckBox.Value
%Actualizacion del vector de error (etapa 2).
app.e2(1) = app.e2(2);
app.e2(2) = app.e2(3);
app.e2(3) = app.tempRef.Value – lectura2(i);
%Actualizacion del vector de control (etapa 2).
app.u2(1) = app.u2(2);
app.u2(2) = ControlPID(app.u2, app.e2, q0, q1, q2);
H2 = app.u2(2) / 100; %Se mapea el PWM obtenico para enviarlo al arduino.
writePWMDutyCycle(app.a, ‘D10’, H2);
end
format bank;
app.matriz1(1, 1) = muestra(i);
app.matriz1(1, 2) = round(lectura1(i), 2);
app.matriz1(1, 3) = round(lectura2(i), 2);
app.matriz1(1, 4) = round(H1 * 100, 2);
app.matriz1(1, 5) = round(H2 * 100, 2);
writematrix(app.matriz1, app.file_path, ‘WriteMode’, ‘append’);
plot(app.grafica_pwm, muestra(i), H2 * 100, muestra(i), H1 * 100);
legend(app.grafica_pwm, ‘H2’, ‘H1’);
plot(app.grafica_temp, muestra, lectura2, muestra, lectura1);
legend(app.grafica_temp, ‘Lectura2’, ‘Lectura1’);
drawnow;
i = i + 1;
%set(app.inicioButton,’BackgroundColor’,[0 0 0],’FontColor’,[0.96 0.96 0.96],’Text’,’Sensando…’);
pause(t);
end
function [act] = ControlPID(u, e, q0, q1, q2)
act = u(1) + q0*e(3) + q1*e(2) + q2*e(1);
if act >= 100
act = 100;
elseif act <= 0
act = 0;
end
end
I am grateful for any commentsI am making an application in app designer where I use two graphs to show the PWM of a digital controller, the UIAxes of the controller response works fine, but the PWM does not show the graph even when the axes are updated normally.
usada = app.PlacaDropDown.Value;
pcom = app.PuertoCOMEditField.Value;
elcom = strcat(‘COM’, pcom);
app.a = arduino(elcom, usada);
app.parar = false;
app.file_path = uiputfile(‘*.csv’, ‘Guardar como’);
i = 1;
H1 = 0;
H2 = 0;
selectedTab = app.TabGroup.SelectedTab;
titulo = selectedTab.Title;
switch titulo
case ‘P’
K = app.K_P.Value;
t = app.T_P.Value;
q0 = K;
q1 = 0.0;
q2 = 0.0;
case ‘PI’
K = app.K_PI.Value;
Ti = app.Ti_PI.Value;
t = app.T_PI.Value;
q0 = K * ( 1 + t/2*Ti );
q1 = -K * ( 1 – t/2*Ti );
q2 = 0.0;
case ‘PID’
K = app.K_PID.Value;
Ti = app.Ti_PID.Value;
Td = app.Td_PID.Value;
t = app.T_PID.Value;
q0 = K * (1 + t/2*Ti + Td/t );
q1 = -K * (1 – t/2*Ti + 2*Td/t );
q2 = K*Td/t;
end
while ~app.parar
muestra(i) = i;
lectura1(i) = readVoltage(app.a,’A1′)* 25;
lectura2(i) = readVoltage(app.a,’A2′)* 25;
if lectura1 >= 40
writeDigitalPin(app.a, ‘D7’, 1);
else
writeDigitalPin(app.a, ‘D7’, 0);
end
if lectura2 >= 40
writeDigitalPin(app.a,’D8′,1);
else
writeDigitalPin(app.a, ‘D8’, 0);
end
if app.Q1CheckBox.Value
%Actualizacion del vector de error (etapa 1).
app.e1(1) = app.e1(2);
app.e1(2) = app.e1(3);
app.e1(3) = app.tempRef.Value – lectura1(i);
%Actualizacion del vector de control (etapa 1).
app.u1(1) = app.u1(2);
app.u1(2) = ControlPID(app.u1, app.e1, q0, q1, q2);
H1 = app.u1(2) / 100; %Se mapea el PWM obtenico para enviarlo al arduino.
writePWMDutyCycle(app.a, ‘D11’, H1);
end
if app.Q2CheckBox.Value
%Actualizacion del vector de error (etapa 2).
app.e2(1) = app.e2(2);
app.e2(2) = app.e2(3);
app.e2(3) = app.tempRef.Value – lectura2(i);
%Actualizacion del vector de control (etapa 2).
app.u2(1) = app.u2(2);
app.u2(2) = ControlPID(app.u2, app.e2, q0, q1, q2);
H2 = app.u2(2) / 100; %Se mapea el PWM obtenico para enviarlo al arduino.
writePWMDutyCycle(app.a, ‘D10’, H2);
end
format bank;
app.matriz1(1, 1) = muestra(i);
app.matriz1(1, 2) = round(lectura1(i), 2);
app.matriz1(1, 3) = round(lectura2(i), 2);
app.matriz1(1, 4) = round(H1 * 100, 2);
app.matriz1(1, 5) = round(H2 * 100, 2);
writematrix(app.matriz1, app.file_path, ‘WriteMode’, ‘append’);
plot(app.grafica_pwm, muestra(i), H2 * 100, muestra(i), H1 * 100);
legend(app.grafica_pwm, ‘H2’, ‘H1’);
plot(app.grafica_temp, muestra, lectura2, muestra, lectura1);
legend(app.grafica_temp, ‘Lectura2’, ‘Lectura1’);
drawnow;
i = i + 1;
%set(app.inicioButton,’BackgroundColor’,[0 0 0],’FontColor’,[0.96 0.96 0.96],’Text’,’Sensando…’);
pause(t);
end
function [act] = ControlPID(u, e, q0, q1, q2)
act = u(1) + q0*e(3) + q1*e(2) + q2*e(1);
if act >= 100
act = 100;
elseif act <= 0
act = 0;
end
end
I am grateful for any comments I am making an application in app designer where I use two graphs to show the PWM of a digital controller, the UIAxes of the controller response works fine, but the PWM does not show the graph even when the axes are updated normally.
usada = app.PlacaDropDown.Value;
pcom = app.PuertoCOMEditField.Value;
elcom = strcat(‘COM’, pcom);
app.a = arduino(elcom, usada);
app.parar = false;
app.file_path = uiputfile(‘*.csv’, ‘Guardar como’);
i = 1;
H1 = 0;
H2 = 0;
selectedTab = app.TabGroup.SelectedTab;
titulo = selectedTab.Title;
switch titulo
case ‘P’
K = app.K_P.Value;
t = app.T_P.Value;
q0 = K;
q1 = 0.0;
q2 = 0.0;
case ‘PI’
K = app.K_PI.Value;
Ti = app.Ti_PI.Value;
t = app.T_PI.Value;
q0 = K * ( 1 + t/2*Ti );
q1 = -K * ( 1 – t/2*Ti );
q2 = 0.0;
case ‘PID’
K = app.K_PID.Value;
Ti = app.Ti_PID.Value;
Td = app.Td_PID.Value;
t = app.T_PID.Value;
q0 = K * (1 + t/2*Ti + Td/t );
q1 = -K * (1 – t/2*Ti + 2*Td/t );
q2 = K*Td/t;
end
while ~app.parar
muestra(i) = i;
lectura1(i) = readVoltage(app.a,’A1′)* 25;
lectura2(i) = readVoltage(app.a,’A2′)* 25;
if lectura1 >= 40
writeDigitalPin(app.a, ‘D7’, 1);
else
writeDigitalPin(app.a, ‘D7’, 0);
end
if lectura2 >= 40
writeDigitalPin(app.a,’D8′,1);
else
writeDigitalPin(app.a, ‘D8’, 0);
end
if app.Q1CheckBox.Value
%Actualizacion del vector de error (etapa 1).
app.e1(1) = app.e1(2);
app.e1(2) = app.e1(3);
app.e1(3) = app.tempRef.Value – lectura1(i);
%Actualizacion del vector de control (etapa 1).
app.u1(1) = app.u1(2);
app.u1(2) = ControlPID(app.u1, app.e1, q0, q1, q2);
H1 = app.u1(2) / 100; %Se mapea el PWM obtenico para enviarlo al arduino.
writePWMDutyCycle(app.a, ‘D11’, H1);
end
if app.Q2CheckBox.Value
%Actualizacion del vector de error (etapa 2).
app.e2(1) = app.e2(2);
app.e2(2) = app.e2(3);
app.e2(3) = app.tempRef.Value – lectura2(i);
%Actualizacion del vector de control (etapa 2).
app.u2(1) = app.u2(2);
app.u2(2) = ControlPID(app.u2, app.e2, q0, q1, q2);
H2 = app.u2(2) / 100; %Se mapea el PWM obtenico para enviarlo al arduino.
writePWMDutyCycle(app.a, ‘D10’, H2);
end
format bank;
app.matriz1(1, 1) = muestra(i);
app.matriz1(1, 2) = round(lectura1(i), 2);
app.matriz1(1, 3) = round(lectura2(i), 2);
app.matriz1(1, 4) = round(H1 * 100, 2);
app.matriz1(1, 5) = round(H2 * 100, 2);
writematrix(app.matriz1, app.file_path, ‘WriteMode’, ‘append’);
plot(app.grafica_pwm, muestra(i), H2 * 100, muestra(i), H1 * 100);
legend(app.grafica_pwm, ‘H2’, ‘H1’);
plot(app.grafica_temp, muestra, lectura2, muestra, lectura1);
legend(app.grafica_temp, ‘Lectura2’, ‘Lectura1’);
drawnow;
i = i + 1;
%set(app.inicioButton,’BackgroundColor’,[0 0 0],’FontColor’,[0.96 0.96 0.96],’Text’,’Sensando…’);
pause(t);
end
function [act] = ControlPID(u, e, q0, q1, q2)
act = u(1) + q0*e(3) + q1*e(2) + q2*e(1);
if act >= 100
act = 100;
elseif act <= 0
act = 0;
end
end
I am grateful for any comments appdesigner, axes MATLAB Answers — New Questions
Random Number from a given vector of numbers
Given a vector of certain allowed numbers,
how to generate another vector whose elements randomly take values from that vector of numbers?Given a vector of certain allowed numbers,
how to generate another vector whose elements randomly take values from that vector of numbers? Given a vector of certain allowed numbers,
how to generate another vector whose elements randomly take values from that vector of numbers? random MATLAB Answers — New Questions
Using signal values in a block that accepts variables in Simscape Multibody
Hi there,
I want to create a frame at the centroid of a bunch of frame origins. I tracked these frames through the Transform Sensor block, and calculated the coordinates of the centroid. Now, I can’t seem to figure out how to use these x,y,z coordinates in the rigid transform block (B frame will be connected to the fixed reference) so that F frame is translated in space by x,y,z amounts in the respective directions.
Can’t I use these signal inputs in the block (like [x_coord y_coord z_coord] in the place of [0 0 0])?
Any help is highly appreciated. Thank you.Hi there,
I want to create a frame at the centroid of a bunch of frame origins. I tracked these frames through the Transform Sensor block, and calculated the coordinates of the centroid. Now, I can’t seem to figure out how to use these x,y,z coordinates in the rigid transform block (B frame will be connected to the fixed reference) so that F frame is translated in space by x,y,z amounts in the respective directions.
Can’t I use these signal inputs in the block (like [x_coord y_coord z_coord] in the place of [0 0 0])?
Any help is highly appreciated. Thank you. Hi there,
I want to create a frame at the centroid of a bunch of frame origins. I tracked these frames through the Transform Sensor block, and calculated the coordinates of the centroid. Now, I can’t seem to figure out how to use these x,y,z coordinates in the rigid transform block (B frame will be connected to the fixed reference) so that F frame is translated in space by x,y,z amounts in the respective directions.
Can’t I use these signal inputs in the block (like [x_coord y_coord z_coord] in the place of [0 0 0])?
Any help is highly appreciated. Thank you. simscape, signals, variables, rigid transform, coordinates MATLAB Answers — New Questions
Extracting values from optimization variable and setting constraints
I have a basket of 20 products with baseline quantities E.g., 40 Tomatoes, 15 Onions, 35 Apples etc. Standard linear optimization with the objective being maximizing the value of the basket subject to constraints on the total weight of the basket, total number of items etc.
The optimization variable QTY is used by the optimizer to adjust the baseline quantity for each product. QTY can take integer values of -15 to +15, i.e., it can increase or reduce baseline amounts of each product by 5 units.
For reasons outside the scope of this question, I need to limit the total number of adjustments it makes across all products, i.e., the sum of the absolute value of QTY <= 30. So it can’t reduce Tomatoes and Onions by 10 each but increase Apples by 15.
How do I place this constraint?
The ABS function can’t access the values in QTY. Adding the constraint on the squared value of QTY gives me a "nonlinear problem" error. Assigning values in QTY to another variable doesn’t work since it just aliases. Various other attempts have yielded the same "nonlinear" error. I’ve been able to make it work in the past by setting 2 optimization variables – QTYUP and QTYDOWN but that becomes clunky.
Current thought is to find a way to extract the values in QTY into a temporary variable, calculate the sum of absolute values, and go. But I haven’t found a straightforward way to this.
Thanks.I have a basket of 20 products with baseline quantities E.g., 40 Tomatoes, 15 Onions, 35 Apples etc. Standard linear optimization with the objective being maximizing the value of the basket subject to constraints on the total weight of the basket, total number of items etc.
The optimization variable QTY is used by the optimizer to adjust the baseline quantity for each product. QTY can take integer values of -15 to +15, i.e., it can increase or reduce baseline amounts of each product by 5 units.
For reasons outside the scope of this question, I need to limit the total number of adjustments it makes across all products, i.e., the sum of the absolute value of QTY <= 30. So it can’t reduce Tomatoes and Onions by 10 each but increase Apples by 15.
How do I place this constraint?
The ABS function can’t access the values in QTY. Adding the constraint on the squared value of QTY gives me a "nonlinear problem" error. Assigning values in QTY to another variable doesn’t work since it just aliases. Various other attempts have yielded the same "nonlinear" error. I’ve been able to make it work in the past by setting 2 optimization variables – QTYUP and QTYDOWN but that becomes clunky.
Current thought is to find a way to extract the values in QTY into a temporary variable, calculate the sum of absolute values, and go. But I haven’t found a straightforward way to this.
Thanks. I have a basket of 20 products with baseline quantities E.g., 40 Tomatoes, 15 Onions, 35 Apples etc. Standard linear optimization with the objective being maximizing the value of the basket subject to constraints on the total weight of the basket, total number of items etc.
The optimization variable QTY is used by the optimizer to adjust the baseline quantity for each product. QTY can take integer values of -15 to +15, i.e., it can increase or reduce baseline amounts of each product by 5 units.
For reasons outside the scope of this question, I need to limit the total number of adjustments it makes across all products, i.e., the sum of the absolute value of QTY <= 30. So it can’t reduce Tomatoes and Onions by 10 each but increase Apples by 15.
How do I place this constraint?
The ABS function can’t access the values in QTY. Adding the constraint on the squared value of QTY gives me a "nonlinear problem" error. Assigning values in QTY to another variable doesn’t work since it just aliases. Various other attempts have yielded the same "nonlinear" error. I’ve been able to make it work in the past by setting 2 optimization variables – QTYUP and QTYDOWN but that becomes clunky.
Current thought is to find a way to extract the values in QTY into a temporary variable, calculate the sum of absolute values, and go. But I haven’t found a straightforward way to this.
Thanks. optimization, constraints MATLAB Answers — New Questions
command not found: pip
Python is installed and loaded in Matlab but pip is not found
how can I fix this?
>> pyenv
ans =
PythonEnvironment with properties:
Version: "3.9"
Executable: "/Library/Developer/CommandLineTools/usr/bin/python3"
Library: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/libpython3.9.dylib"
Home: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9"
Status: Loaded
ExecutionMode: InProcess
ProcessID: "17092"
ProcessName: "MATLAB"
>> !pip install tensorflow
zsh:1: command not found: pipPython is installed and loaded in Matlab but pip is not found
how can I fix this?
>> pyenv
ans =
PythonEnvironment with properties:
Version: "3.9"
Executable: "/Library/Developer/CommandLineTools/usr/bin/python3"
Library: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/libpython3.9.dylib"
Home: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9"
Status: Loaded
ExecutionMode: InProcess
ProcessID: "17092"
ProcessName: "MATLAB"
>> !pip install tensorflow
zsh:1: command not found: pip Python is installed and loaded in Matlab but pip is not found
how can I fix this?
>> pyenv
ans =
PythonEnvironment with properties:
Version: "3.9"
Executable: "/Library/Developer/CommandLineTools/usr/bin/python3"
Library: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/libpython3.9.dylib"
Home: "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9"
Status: Loaded
ExecutionMode: InProcess
ProcessID: "17092"
ProcessName: "MATLAB"
>> !pip install tensorflow
zsh:1: command not found: pip python MATLAB Answers — New Questions
Designing Coffee vending Machine using Simulink MATLAB
I am trying to build a coffee vending machine in the simulink for MATLAB but I can’t find any resoruces related to the topic can anyone help me.I am trying to build a coffee vending machine in the simulink for MATLAB but I can’t find any resoruces related to the topic can anyone help me. I am trying to build a coffee vending machine in the simulink for MATLAB but I can’t find any resoruces related to the topic can anyone help me. simulink, matlab MATLAB Answers — New Questions