Category: News
Setting up an optimization in matlab
Hi everyone.
I have an optimization problem that seeks to aid the selection of suitable conductors in a network planning exercise. I have set up two functions – one of the functions sets up the objective function which is to calculate the total cost based on the type of conductor and the cost associated with the type of conductor. The total cost is thus calculated based on the code below.
function TotCost = minTotCost(RepCondpath,fdrpath1,sheetname)
%fdrpath1: describes the path to the an excel file with the conductors on
%the network while RepCondpath described the path to the costs associated
%with each type of conductor.
[TR,TAmp, C_index]=rep_repository_cr_opt(RepCondpath);
[R,Amp]=getInitialCon_par(fdrpath1,sheetname);
% examine the Resistance of the conductor
% check the TR to find out the value of the
C_weights=C_index;
cost =zeros(length(R),1);
for i =1:length (R)
disp(i);
j= TR == R(i);
cost(i) = C_weights(j);
end
TotCost= sum(cost);
The second thing is to describe the constraints function. In this case, the two constraints are voltage levels (NPI) and conductor loading (CPI). These two are calculated based on the a powerflow function- which calculate the network’s NPI and CPI using the following constraint function.
function[NPI,CPI]=ConstraintFnc(fdrpath1,sheetname)
fname1 = fdrpath1;sheet = sheetname;
fdrcon=get_fdrcon(fdrpath1,sheetname);
[VA,VB,VC,~,IA,IB,IC]= start_f7(1,1,1,1,sheetname,fdrpath1); % This is the powerflow function
ResRange1 = "G6:G12"; AmpRange="AG6:AG12";
R=xlsread(fname1,sheet,ResRange1);
Amp=xlsread(fname1,sheet,AmpRange);
[CPI,NPI]= BNPerf_opt(VA, VB, VC, IA, IB, IC); % This is the function that calculates the CPI and NPI
The objective is to find conductors in TR whose combination has the least total cost. How do I bring these two functions together to run on Matlab.Hi everyone.
I have an optimization problem that seeks to aid the selection of suitable conductors in a network planning exercise. I have set up two functions – one of the functions sets up the objective function which is to calculate the total cost based on the type of conductor and the cost associated with the type of conductor. The total cost is thus calculated based on the code below.
function TotCost = minTotCost(RepCondpath,fdrpath1,sheetname)
%fdrpath1: describes the path to the an excel file with the conductors on
%the network while RepCondpath described the path to the costs associated
%with each type of conductor.
[TR,TAmp, C_index]=rep_repository_cr_opt(RepCondpath);
[R,Amp]=getInitialCon_par(fdrpath1,sheetname);
% examine the Resistance of the conductor
% check the TR to find out the value of the
C_weights=C_index;
cost =zeros(length(R),1);
for i =1:length (R)
disp(i);
j= TR == R(i);
cost(i) = C_weights(j);
end
TotCost= sum(cost);
The second thing is to describe the constraints function. In this case, the two constraints are voltage levels (NPI) and conductor loading (CPI). These two are calculated based on the a powerflow function- which calculate the network’s NPI and CPI using the following constraint function.
function[NPI,CPI]=ConstraintFnc(fdrpath1,sheetname)
fname1 = fdrpath1;sheet = sheetname;
fdrcon=get_fdrcon(fdrpath1,sheetname);
[VA,VB,VC,~,IA,IB,IC]= start_f7(1,1,1,1,sheetname,fdrpath1); % This is the powerflow function
ResRange1 = "G6:G12"; AmpRange="AG6:AG12";
R=xlsread(fname1,sheet,ResRange1);
Amp=xlsread(fname1,sheet,AmpRange);
[CPI,NPI]= BNPerf_opt(VA, VB, VC, IA, IB, IC); % This is the function that calculates the CPI and NPI
The objective is to find conductors in TR whose combination has the least total cost. How do I bring these two functions together to run on Matlab. Hi everyone.
I have an optimization problem that seeks to aid the selection of suitable conductors in a network planning exercise. I have set up two functions – one of the functions sets up the objective function which is to calculate the total cost based on the type of conductor and the cost associated with the type of conductor. The total cost is thus calculated based on the code below.
function TotCost = minTotCost(RepCondpath,fdrpath1,sheetname)
%fdrpath1: describes the path to the an excel file with the conductors on
%the network while RepCondpath described the path to the costs associated
%with each type of conductor.
[TR,TAmp, C_index]=rep_repository_cr_opt(RepCondpath);
[R,Amp]=getInitialCon_par(fdrpath1,sheetname);
% examine the Resistance of the conductor
% check the TR to find out the value of the
C_weights=C_index;
cost =zeros(length(R),1);
for i =1:length (R)
disp(i);
j= TR == R(i);
cost(i) = C_weights(j);
end
TotCost= sum(cost);
The second thing is to describe the constraints function. In this case, the two constraints are voltage levels (NPI) and conductor loading (CPI). These two are calculated based on the a powerflow function- which calculate the network’s NPI and CPI using the following constraint function.
function[NPI,CPI]=ConstraintFnc(fdrpath1,sheetname)
fname1 = fdrpath1;sheet = sheetname;
fdrcon=get_fdrcon(fdrpath1,sheetname);
[VA,VB,VC,~,IA,IB,IC]= start_f7(1,1,1,1,sheetname,fdrpath1); % This is the powerflow function
ResRange1 = "G6:G12"; AmpRange="AG6:AG12";
R=xlsread(fname1,sheet,ResRange1);
Amp=xlsread(fname1,sheet,AmpRange);
[CPI,NPI]= BNPerf_opt(VA, VB, VC, IA, IB, IC); % This is the function that calculates the CPI and NPI
The objective is to find conductors in TR whose combination has the least total cost. How do I bring these two functions together to run on Matlab. ga, optimization, conductor selection MATLAB Answers — New Questions
How do I feed ODE45 a cell array ?
I am trying to solve an ODE which consists of function handles. In order to formulate the equation of state vector derivative of the System of 1st order ODEs, I collect these function handles in a cell array. It is not possible to store them in a normal array as far as I know. How do I feed the cell Array, which contains all the function handles to the ODE45 solver or do it differently?
Scheme of the problem:
%create cell and state array
state = @(x,y,z) [x;y;z];
Cell_array = cell(3);
%column selector
select_column = @(M, col_index) M(:,col_index);
%Define Matrix Functions, here 2 examples of Matrices
Matrix_1 = @(state) [1,1,state(1); 1,1,sin(state(2));1,1,state(3)];
Matrix_2 = @(state) [state(1),0,0; 0,state(2),0; 0,0, state(2)];
%select the columns
M1_c1 = @(state) select_column(Matrix_1(state),1);
M1_c2 = @(state) select_column(Matrix_1(state),2);
M1_c3 = @(state) select_column(Matrix_1(state),3);
%differential equations
state_dot_1 = @(state) Matrix_2(state) * M1_c1(state);
state_dot_2 = @(state) Matrix_2(state) * M1_c2(state);
state_dot_3 = @(state) Matrix_2(state) * M1_c3(state);
%fill cell array with differential equations
Cell_array{1} = state_dot_1;
Cell_array{2} = state_dot_2;
Cell_array{3} = state_dot_3;
I would now like to feed that cell_array to an ODE solver. This doesn’t work. But using a normal array doesn’t work either for these function handles. Does anyone know a work around ? I’m new to matlab and programming in general.I am trying to solve an ODE which consists of function handles. In order to formulate the equation of state vector derivative of the System of 1st order ODEs, I collect these function handles in a cell array. It is not possible to store them in a normal array as far as I know. How do I feed the cell Array, which contains all the function handles to the ODE45 solver or do it differently?
Scheme of the problem:
%create cell and state array
state = @(x,y,z) [x;y;z];
Cell_array = cell(3);
%column selector
select_column = @(M, col_index) M(:,col_index);
%Define Matrix Functions, here 2 examples of Matrices
Matrix_1 = @(state) [1,1,state(1); 1,1,sin(state(2));1,1,state(3)];
Matrix_2 = @(state) [state(1),0,0; 0,state(2),0; 0,0, state(2)];
%select the columns
M1_c1 = @(state) select_column(Matrix_1(state),1);
M1_c2 = @(state) select_column(Matrix_1(state),2);
M1_c3 = @(state) select_column(Matrix_1(state),3);
%differential equations
state_dot_1 = @(state) Matrix_2(state) * M1_c1(state);
state_dot_2 = @(state) Matrix_2(state) * M1_c2(state);
state_dot_3 = @(state) Matrix_2(state) * M1_c3(state);
%fill cell array with differential equations
Cell_array{1} = state_dot_1;
Cell_array{2} = state_dot_2;
Cell_array{3} = state_dot_3;
I would now like to feed that cell_array to an ODE solver. This doesn’t work. But using a normal array doesn’t work either for these function handles. Does anyone know a work around ? I’m new to matlab and programming in general. I am trying to solve an ODE which consists of function handles. In order to formulate the equation of state vector derivative of the System of 1st order ODEs, I collect these function handles in a cell array. It is not possible to store them in a normal array as far as I know. How do I feed the cell Array, which contains all the function handles to the ODE45 solver or do it differently?
Scheme of the problem:
%create cell and state array
state = @(x,y,z) [x;y;z];
Cell_array = cell(3);
%column selector
select_column = @(M, col_index) M(:,col_index);
%Define Matrix Functions, here 2 examples of Matrices
Matrix_1 = @(state) [1,1,state(1); 1,1,sin(state(2));1,1,state(3)];
Matrix_2 = @(state) [state(1),0,0; 0,state(2),0; 0,0, state(2)];
%select the columns
M1_c1 = @(state) select_column(Matrix_1(state),1);
M1_c2 = @(state) select_column(Matrix_1(state),2);
M1_c3 = @(state) select_column(Matrix_1(state),3);
%differential equations
state_dot_1 = @(state) Matrix_2(state) * M1_c1(state);
state_dot_2 = @(state) Matrix_2(state) * M1_c2(state);
state_dot_3 = @(state) Matrix_2(state) * M1_c3(state);
%fill cell array with differential equations
Cell_array{1} = state_dot_1;
Cell_array{2} = state_dot_2;
Cell_array{3} = state_dot_3;
I would now like to feed that cell_array to an ODE solver. This doesn’t work. But using a normal array doesn’t work either for these function handles. Does anyone know a work around ? I’m new to matlab and programming in general. function handles, ode45, cell array MATLAB Answers — New Questions
How to resolve this error: Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right side is 1000-by-1000
Howe to resolve this error:
Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right
side is 1000-by-1000.
Error in servssnr (line 43)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
This is my full code:
PRF = 500e3; % Pulse Repetition Frequency (Hz)
sampling_freq = 60e6; % Sampling Frequency (Hz)
carrier_freq = 2.4e9;
rng(‘default’) % Set random number seed for repeatability
M = 4;
EbNo = 0:13;
[ber,ser] = berawgn(EbNo,’pam’,M);
n = 1000; % Number of symbols to process
k = log2(M); % Number of bits per symbol
snr = EbNo+3+10*log10(k); % In dB
ynoisy = zeros(n,length(snr));
z = zeros(n,length(snr));
errVec = zeros(3,length(EbNo));
grid on;
errcalc = comm.ErrorRate;
%x1 = randi([0 M-1],n,1); % Create message signal
% Generate Gold code
code1 = comm.GoldSequence(‘FirstPolynomial’,’x^6+x^5+1′, ‘FirstInitialConditions’,[ 0 0 0 0 0 1], ‘SecondPolynomial’,’x^6+x^5+x^4+x+1′, ‘SecondInitialConditions’,[0 0 0 0 0 1], ‘Index’,1, ‘SamplesPerFrame’,1000);
gold_code = code1();
% Generate Kasami code
kasamiseq = comm.KasamiSequence(‘Polynomial’,[6 5 4 1 0], ‘InitialConditions’,[ 0 0 0 0 0 1],’SamplesPerFrame’,1000);
kasami_code = kasamiseq()
y1 = pammod(gold_code,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y1),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(gold_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’r’);
hold on;
% Modulate kasami code with barker code
x5 = cos(2*pi*carrier_freq*(0:numel(gold_code)-1)/sampling_freq) .* (gold_code .* kasami_code.’);
y = pammod(x5,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(x5,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’b’);
hold on;
y2 = pammod(kasami_code,M);
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y2),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(kasami_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’g’);
legend(‘Gold code’,’Gold-Kasami’, ‘Kasami’);
title(‘Comparison of SER ‘);
xlabel(‘E_b/N_0 (dB)’);
ylabel(‘Symbol Error Rate’);
grid on;
hold off;Howe to resolve this error:
Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right
side is 1000-by-1000.
Error in servssnr (line 43)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
This is my full code:
PRF = 500e3; % Pulse Repetition Frequency (Hz)
sampling_freq = 60e6; % Sampling Frequency (Hz)
carrier_freq = 2.4e9;
rng(‘default’) % Set random number seed for repeatability
M = 4;
EbNo = 0:13;
[ber,ser] = berawgn(EbNo,’pam’,M);
n = 1000; % Number of symbols to process
k = log2(M); % Number of bits per symbol
snr = EbNo+3+10*log10(k); % In dB
ynoisy = zeros(n,length(snr));
z = zeros(n,length(snr));
errVec = zeros(3,length(EbNo));
grid on;
errcalc = comm.ErrorRate;
%x1 = randi([0 M-1],n,1); % Create message signal
% Generate Gold code
code1 = comm.GoldSequence(‘FirstPolynomial’,’x^6+x^5+1′, ‘FirstInitialConditions’,[ 0 0 0 0 0 1], ‘SecondPolynomial’,’x^6+x^5+x^4+x+1′, ‘SecondInitialConditions’,[0 0 0 0 0 1], ‘Index’,1, ‘SamplesPerFrame’,1000);
gold_code = code1();
% Generate Kasami code
kasamiseq = comm.KasamiSequence(‘Polynomial’,[6 5 4 1 0], ‘InitialConditions’,[ 0 0 0 0 0 1],’SamplesPerFrame’,1000);
kasami_code = kasamiseq()
y1 = pammod(gold_code,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y1),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(gold_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’r’);
hold on;
% Modulate kasami code with barker code
x5 = cos(2*pi*carrier_freq*(0:numel(gold_code)-1)/sampling_freq) .* (gold_code .* kasami_code.’);
y = pammod(x5,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(x5,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’b’);
hold on;
y2 = pammod(kasami_code,M);
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y2),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(kasami_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’g’);
legend(‘Gold code’,’Gold-Kasami’, ‘Kasami’);
title(‘Comparison of SER ‘);
xlabel(‘E_b/N_0 (dB)’);
ylabel(‘Symbol Error Rate’);
grid on;
hold off; Howe to resolve this error:
Unable to perform assignment because the size of the left side is 1000-by-1 and the size of the right
side is 1000-by-1000.
Error in servssnr (line 43)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
This is my full code:
PRF = 500e3; % Pulse Repetition Frequency (Hz)
sampling_freq = 60e6; % Sampling Frequency (Hz)
carrier_freq = 2.4e9;
rng(‘default’) % Set random number seed for repeatability
M = 4;
EbNo = 0:13;
[ber,ser] = berawgn(EbNo,’pam’,M);
n = 1000; % Number of symbols to process
k = log2(M); % Number of bits per symbol
snr = EbNo+3+10*log10(k); % In dB
ynoisy = zeros(n,length(snr));
z = zeros(n,length(snr));
errVec = zeros(3,length(EbNo));
grid on;
errcalc = comm.ErrorRate;
%x1 = randi([0 M-1],n,1); % Create message signal
% Generate Gold code
code1 = comm.GoldSequence(‘FirstPolynomial’,’x^6+x^5+1′, ‘FirstInitialConditions’,[ 0 0 0 0 0 1], ‘SecondPolynomial’,’x^6+x^5+x^4+x+1′, ‘SecondInitialConditions’,[0 0 0 0 0 1], ‘Index’,1, ‘SamplesPerFrame’,1000);
gold_code = code1();
% Generate Kasami code
kasamiseq = comm.KasamiSequence(‘Polynomial’,[6 5 4 1 0], ‘InitialConditions’,[ 0 0 0 0 0 1],’SamplesPerFrame’,1000);
kasami_code = kasamiseq()
y1 = pammod(gold_code,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y1),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(gold_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’r’);
hold on;
% Modulate kasami code with barker code
x5 = cos(2*pi*carrier_freq*(0:numel(gold_code)-1)/sampling_freq) .* (gold_code .* kasami_code.’);
y = pammod(x5,M); % Modulate
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(x5,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’b’);
hold on;
y2 = pammod(kasami_code,M);
for ii = 1:length(snr)
reset(errcalc)
ynoisy(:,ii) = awgn(real(y2),snr(ii),’measured’); % Add AWGN
z(:,ii) = pamdemod(complex(ynoisy(:,ii)),M); % Demodulate
errVec(:,ii) = errcalc(kasami_code,z(:,ii)); % Compute SER from simulation
end
semilogy(EbNo,errVec(1,:),’g’);
legend(‘Gold code’,’Gold-Kasami’, ‘Kasami’);
title(‘Comparison of SER ‘);
xlabel(‘E_b/N_0 (dB)’);
ylabel(‘Symbol Error Rate’);
grid on;
hold off; matlab, digital signal processing, radar, error, dimensions, binary MATLAB Answers — New Questions
How would I properly go about creating this function?
I am doing a project to practice matlab and thought it would be best to be put into a function. This is my function and the rest of my code, I have variables t_values, height_values, and width_values that need to be used outside of the function, but I do not know how to use them from inside the function. These equations are going to be different for the different beams which is why I decided to create a general function. Thanks!
l = 70*12; %length
maxHeight = 12; %maximum height of beam
maxWidth = 10; %maximum width of beam
minHeight = 3; %minimum height of beam
minWidth = 3; %minimum width of beam
maxDef = 10; %maximum beam deformation
w = 3; %distributed load
p = 500; %point force
a = l/3; %distance to point force
E_alum = 9.9*10^6; %aluminum stiffness
E_steel = 28*10^6; %steel stiffness
E_ti = 16*10^6; %titanium stiffness
den_alum = .098; %aluminum density
den_steel = .286; %steel density
den_ti = .16; %titanium density
E = [E_alum, E_steel, E_ti];
density = [den_alum, den_steel, den_ti];
%For combined load
I_min = (w*(l^4)./(E.*30.*maxDef))…
– ((p*(a^2)*((3*l)-a))./(E.*6.*maxDef));
disp(‘I-Beam’);
A_horizI = width_values.*t_values; %Area of flanges
A_vertI = t_values.*(height_values-(2.*t_values)); %Area of web
I_horizI = width_values.*t_values.^3; %Moment of flanges
I_vertI = (t_values.*(height_values-(2.*t_values)).^3)./12; %Moment of web
I_I_beam = I_vertI + 2.*(I_horizI + A_horizI.*((height_values./2)-(t_values./2)).^2); %I for I beam
weightIbeam = @(t, h, w, l, density) (2*w.*t + t.*(h-2.*t))*l*density; %Weight equation for I beam
beamoptimize(I_min, l, density,I_I_beam,weightIbeam);
function beamoptimize( I_min, l, density, I1, weightFunc)
t = 0.1:0.05:1;
height = minHeight:0.05:maxHeight;
width = minWidth:0.05:maxWidth;
V = {t, height, width};
C = cell(1, numel(V));
[C{:}] = ndgrid(V{:});
C = cellfun(@(X) reshape(X, [], 1), C, ‘UniformOutput’, false);
C = horzcat(C{:});
t_values = C(:, 1);
height_values = C(:, 2);
width_values = C(:, 3);
for i = 1:length(I_min)
I = I1;
valid_I = I(I >= I_min(i));
valid_t = t_values(I >= I_min(i));
valid_height = height_values(I >= I_min(i));
valid_width = width_values(I >= I_min(i));
% Calculate weight using the provided weight function
weight = weightFunc(valid_t, valid_height, valid_width, l, density(i));
[min_weight, min_index] = min(weight);
optimal_I = valid_I(min_index);
optimal_t = valid_t(min_index);
optimal_height = valid_height(min_index);
optimal_width = valid_width(min_index);
disp([‘For I_min = ‘, num2str(I_min(i))]);
disp([‘Minimum weight: ‘, num2str(min_weight)]);
disp([‘Optimal valid_I: ‘, num2str(optimal_I)]);
disp([‘Minimum thickness: ‘, num2str(optimal_t)]);
disp([‘Optimal height: ‘, num2str(optimal_height)]);
disp([‘Optimal width: ‘, num2str(optimal_width)]);
disp(‘—————————————‘);
end
endI am doing a project to practice matlab and thought it would be best to be put into a function. This is my function and the rest of my code, I have variables t_values, height_values, and width_values that need to be used outside of the function, but I do not know how to use them from inside the function. These equations are going to be different for the different beams which is why I decided to create a general function. Thanks!
l = 70*12; %length
maxHeight = 12; %maximum height of beam
maxWidth = 10; %maximum width of beam
minHeight = 3; %minimum height of beam
minWidth = 3; %minimum width of beam
maxDef = 10; %maximum beam deformation
w = 3; %distributed load
p = 500; %point force
a = l/3; %distance to point force
E_alum = 9.9*10^6; %aluminum stiffness
E_steel = 28*10^6; %steel stiffness
E_ti = 16*10^6; %titanium stiffness
den_alum = .098; %aluminum density
den_steel = .286; %steel density
den_ti = .16; %titanium density
E = [E_alum, E_steel, E_ti];
density = [den_alum, den_steel, den_ti];
%For combined load
I_min = (w*(l^4)./(E.*30.*maxDef))…
– ((p*(a^2)*((3*l)-a))./(E.*6.*maxDef));
disp(‘I-Beam’);
A_horizI = width_values.*t_values; %Area of flanges
A_vertI = t_values.*(height_values-(2.*t_values)); %Area of web
I_horizI = width_values.*t_values.^3; %Moment of flanges
I_vertI = (t_values.*(height_values-(2.*t_values)).^3)./12; %Moment of web
I_I_beam = I_vertI + 2.*(I_horizI + A_horizI.*((height_values./2)-(t_values./2)).^2); %I for I beam
weightIbeam = @(t, h, w, l, density) (2*w.*t + t.*(h-2.*t))*l*density; %Weight equation for I beam
beamoptimize(I_min, l, density,I_I_beam,weightIbeam);
function beamoptimize( I_min, l, density, I1, weightFunc)
t = 0.1:0.05:1;
height = minHeight:0.05:maxHeight;
width = minWidth:0.05:maxWidth;
V = {t, height, width};
C = cell(1, numel(V));
[C{:}] = ndgrid(V{:});
C = cellfun(@(X) reshape(X, [], 1), C, ‘UniformOutput’, false);
C = horzcat(C{:});
t_values = C(:, 1);
height_values = C(:, 2);
width_values = C(:, 3);
for i = 1:length(I_min)
I = I1;
valid_I = I(I >= I_min(i));
valid_t = t_values(I >= I_min(i));
valid_height = height_values(I >= I_min(i));
valid_width = width_values(I >= I_min(i));
% Calculate weight using the provided weight function
weight = weightFunc(valid_t, valid_height, valid_width, l, density(i));
[min_weight, min_index] = min(weight);
optimal_I = valid_I(min_index);
optimal_t = valid_t(min_index);
optimal_height = valid_height(min_index);
optimal_width = valid_width(min_index);
disp([‘For I_min = ‘, num2str(I_min(i))]);
disp([‘Minimum weight: ‘, num2str(min_weight)]);
disp([‘Optimal valid_I: ‘, num2str(optimal_I)]);
disp([‘Minimum thickness: ‘, num2str(optimal_t)]);
disp([‘Optimal height: ‘, num2str(optimal_height)]);
disp([‘Optimal width: ‘, num2str(optimal_width)]);
disp(‘—————————————‘);
end
end I am doing a project to practice matlab and thought it would be best to be put into a function. This is my function and the rest of my code, I have variables t_values, height_values, and width_values that need to be used outside of the function, but I do not know how to use them from inside the function. These equations are going to be different for the different beams which is why I decided to create a general function. Thanks!
l = 70*12; %length
maxHeight = 12; %maximum height of beam
maxWidth = 10; %maximum width of beam
minHeight = 3; %minimum height of beam
minWidth = 3; %minimum width of beam
maxDef = 10; %maximum beam deformation
w = 3; %distributed load
p = 500; %point force
a = l/3; %distance to point force
E_alum = 9.9*10^6; %aluminum stiffness
E_steel = 28*10^6; %steel stiffness
E_ti = 16*10^6; %titanium stiffness
den_alum = .098; %aluminum density
den_steel = .286; %steel density
den_ti = .16; %titanium density
E = [E_alum, E_steel, E_ti];
density = [den_alum, den_steel, den_ti];
%For combined load
I_min = (w*(l^4)./(E.*30.*maxDef))…
– ((p*(a^2)*((3*l)-a))./(E.*6.*maxDef));
disp(‘I-Beam’);
A_horizI = width_values.*t_values; %Area of flanges
A_vertI = t_values.*(height_values-(2.*t_values)); %Area of web
I_horizI = width_values.*t_values.^3; %Moment of flanges
I_vertI = (t_values.*(height_values-(2.*t_values)).^3)./12; %Moment of web
I_I_beam = I_vertI + 2.*(I_horizI + A_horizI.*((height_values./2)-(t_values./2)).^2); %I for I beam
weightIbeam = @(t, h, w, l, density) (2*w.*t + t.*(h-2.*t))*l*density; %Weight equation for I beam
beamoptimize(I_min, l, density,I_I_beam,weightIbeam);
function beamoptimize( I_min, l, density, I1, weightFunc)
t = 0.1:0.05:1;
height = minHeight:0.05:maxHeight;
width = minWidth:0.05:maxWidth;
V = {t, height, width};
C = cell(1, numel(V));
[C{:}] = ndgrid(V{:});
C = cellfun(@(X) reshape(X, [], 1), C, ‘UniformOutput’, false);
C = horzcat(C{:});
t_values = C(:, 1);
height_values = C(:, 2);
width_values = C(:, 3);
for i = 1:length(I_min)
I = I1;
valid_I = I(I >= I_min(i));
valid_t = t_values(I >= I_min(i));
valid_height = height_values(I >= I_min(i));
valid_width = width_values(I >= I_min(i));
% Calculate weight using the provided weight function
weight = weightFunc(valid_t, valid_height, valid_width, l, density(i));
[min_weight, min_index] = min(weight);
optimal_I = valid_I(min_index);
optimal_t = valid_t(min_index);
optimal_height = valid_height(min_index);
optimal_width = valid_width(min_index);
disp([‘For I_min = ‘, num2str(I_min(i))]);
disp([‘Minimum weight: ‘, num2str(min_weight)]);
disp([‘Optimal valid_I: ‘, num2str(optimal_I)]);
disp([‘Minimum thickness: ‘, num2str(optimal_t)]);
disp([‘Optimal height: ‘, num2str(optimal_height)]);
disp([‘Optimal width: ‘, num2str(optimal_width)]);
disp(‘—————————————‘);
end
end help, functions, matlab MATLAB Answers — New Questions
PDEPE solver failure (spatial discretization) ; partial differential/derivative temperature modelling
Attempting to model temperature profile of an adsorption column based on concentration profile since this determines the heat of adsorption.
This is the function:
function[c,f,s] = pdefunEB(x,t,u,dudx)
global qmax_phenol K_L_phenol kf De u_s Rep Dp epsilon rho_liq cp_AC cp_feed H_ads h alpha
C = u(1) ;
q = u(2) ;
Tf = u(3) ;
dCdx = dudx(1) ;
dqdx = dudx(2) ;
dTdx = dudx(3) ;
Ts = 298.15 ; % adsorbent temp Kelvin
qstar = ((qmax_phenol)*(K_L_phenol)*C)/(1+(K_L_phenol)*C) ;
dqdt = kf*(qstar-q) ;
c = ones(3,1) ;
f = [De*dCdx;
0;
0];
s = [-u_s*dCdx-(1-epsilon)/epsilon*rho_liq*dqdt;
dqdt;
-u_s*dTdx+(((h*alpha*(Tf-Ts)-(H_ads/cp_AC))+(H_ads/cp_feed))*(dqdt*((1-epsilon)/epsilon)))] ;
end
%% initial condition
function u0 = icfunEB(x)
u0 = [0;
0;
298.15] ;
end
%% boundary condition
function [p1,q1,pr,qr] = bcfunEB(x1,u1,xr,ur,t)
global C_phenol
C0 = C_phenol ;
p1 = [u1(1)-C0;0;-298.15] ;
q1 = [0;1;0] ;
pr = [0;0;0] ;
qr = [1;1;1] ;
end
this is where the error appears (Error using pdepe Spatial discretization has failed. Discretization supports only parabolic and elliptic equations, with flux term involving spatial derivative)
mEB = 0 ;
sol1 = pdepe(mEB,@pdefunEB,@icfunEB,@bcfunEB,x,t) ;
CEB = sol1(:,:,1) ;
qEB = sol1(:,:,2) ;
TEB = sol1(:,:,3) ;
figure(2)
T0 = 298.15 ;
Cp1 = C1(:,end)./C01 ;
plot(t,TEB,’b-‘,’LineWidth’,2)
grid on
title(‘Column Temperature’)
xlabel(‘time in minutes’)
ylabel(‘temp in kelvin’)
Heres a picture of my mathematical working before input into matlab:Attempting to model temperature profile of an adsorption column based on concentration profile since this determines the heat of adsorption.
This is the function:
function[c,f,s] = pdefunEB(x,t,u,dudx)
global qmax_phenol K_L_phenol kf De u_s Rep Dp epsilon rho_liq cp_AC cp_feed H_ads h alpha
C = u(1) ;
q = u(2) ;
Tf = u(3) ;
dCdx = dudx(1) ;
dqdx = dudx(2) ;
dTdx = dudx(3) ;
Ts = 298.15 ; % adsorbent temp Kelvin
qstar = ((qmax_phenol)*(K_L_phenol)*C)/(1+(K_L_phenol)*C) ;
dqdt = kf*(qstar-q) ;
c = ones(3,1) ;
f = [De*dCdx;
0;
0];
s = [-u_s*dCdx-(1-epsilon)/epsilon*rho_liq*dqdt;
dqdt;
-u_s*dTdx+(((h*alpha*(Tf-Ts)-(H_ads/cp_AC))+(H_ads/cp_feed))*(dqdt*((1-epsilon)/epsilon)))] ;
end
%% initial condition
function u0 = icfunEB(x)
u0 = [0;
0;
298.15] ;
end
%% boundary condition
function [p1,q1,pr,qr] = bcfunEB(x1,u1,xr,ur,t)
global C_phenol
C0 = C_phenol ;
p1 = [u1(1)-C0;0;-298.15] ;
q1 = [0;1;0] ;
pr = [0;0;0] ;
qr = [1;1;1] ;
end
this is where the error appears (Error using pdepe Spatial discretization has failed. Discretization supports only parabolic and elliptic equations, with flux term involving spatial derivative)
mEB = 0 ;
sol1 = pdepe(mEB,@pdefunEB,@icfunEB,@bcfunEB,x,t) ;
CEB = sol1(:,:,1) ;
qEB = sol1(:,:,2) ;
TEB = sol1(:,:,3) ;
figure(2)
T0 = 298.15 ;
Cp1 = C1(:,end)./C01 ;
plot(t,TEB,’b-‘,’LineWidth’,2)
grid on
title(‘Column Temperature’)
xlabel(‘time in minutes’)
ylabel(‘temp in kelvin’)
Heres a picture of my mathematical working before input into matlab: Attempting to model temperature profile of an adsorption column based on concentration profile since this determines the heat of adsorption.
This is the function:
function[c,f,s] = pdefunEB(x,t,u,dudx)
global qmax_phenol K_L_phenol kf De u_s Rep Dp epsilon rho_liq cp_AC cp_feed H_ads h alpha
C = u(1) ;
q = u(2) ;
Tf = u(3) ;
dCdx = dudx(1) ;
dqdx = dudx(2) ;
dTdx = dudx(3) ;
Ts = 298.15 ; % adsorbent temp Kelvin
qstar = ((qmax_phenol)*(K_L_phenol)*C)/(1+(K_L_phenol)*C) ;
dqdt = kf*(qstar-q) ;
c = ones(3,1) ;
f = [De*dCdx;
0;
0];
s = [-u_s*dCdx-(1-epsilon)/epsilon*rho_liq*dqdt;
dqdt;
-u_s*dTdx+(((h*alpha*(Tf-Ts)-(H_ads/cp_AC))+(H_ads/cp_feed))*(dqdt*((1-epsilon)/epsilon)))] ;
end
%% initial condition
function u0 = icfunEB(x)
u0 = [0;
0;
298.15] ;
end
%% boundary condition
function [p1,q1,pr,qr] = bcfunEB(x1,u1,xr,ur,t)
global C_phenol
C0 = C_phenol ;
p1 = [u1(1)-C0;0;-298.15] ;
q1 = [0;1;0] ;
pr = [0;0;0] ;
qr = [1;1;1] ;
end
this is where the error appears (Error using pdepe Spatial discretization has failed. Discretization supports only parabolic and elliptic equations, with flux term involving spatial derivative)
mEB = 0 ;
sol1 = pdepe(mEB,@pdefunEB,@icfunEB,@bcfunEB,x,t) ;
CEB = sol1(:,:,1) ;
qEB = sol1(:,:,2) ;
TEB = sol1(:,:,3) ;
figure(2)
T0 = 298.15 ;
Cp1 = C1(:,end)./C01 ;
plot(t,TEB,’b-‘,’LineWidth’,2)
grid on
title(‘Column Temperature’)
xlabel(‘time in minutes’)
ylabel(‘temp in kelvin’)
Heres a picture of my mathematical working before input into matlab: pdepe, partials, partialdifferentials, partialderivatives, adsorption, chemical engineering, spatial discretisation MATLAB Answers — New Questions
Why is the conditional statement not working as per the condition given?
horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
for i=1:numberOfParticlesInDomain
p=1;
for j=1:numberOfParticlesInDomain
if i~=j %Condition for checking undesired presence of a particle in its own neighbourhood
d=abs(CORD(i)-CORD(j)); %Distance between the two particles is stored in’d’ for comparison with the horizon value
if d<=horizon
neighbourhoodArray(i,p)=j;
p=p+1; %’p’ is incremented at every step to store only the particles within the horizon distance of a particular particle.
end
end
end
end
disp(neighbourhoodArray);
This code is part of a project on material failure modelling. I need to store all the particles (labelled as ‘j’ in the for loop) within a certain distance (lablled as ‘horizon’) from a particular particle (labelled as ‘i’ in the for loop). With the given data of horizon=0.3, spacing (between particles)=0.1, and length=1, number of particles in the domain will come out to be 10. The x-component of 1st particle is ‘0’ and that of the last one is ‘0.9’, as in the ‘xComponent’ array.
Now, with the given data, for the first particle (with CORD(1)=0), the neighbourhood particles should be those at CORD(2)=0.1 (Particle-2), CORD(3)=0.2 (Particle-3), CORD(3)=0.3 (Particle-4). But, in the neighbourhoodArray array, for the 1st particle, only Particle-2 and Particle-3 are being shown to be in the neighbourhood of Particle-1, which is incorrect.
I ran the code statement-by-statement using ‘Step’ and found that the compiler is not executing the statement under "if d<=horizon" when ‘d’ and ‘horizon’ have the same value (=0.3). I really don’t understand what the problem is with the conditional statement, as I think the logic that I have used is correct.horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
for i=1:numberOfParticlesInDomain
p=1;
for j=1:numberOfParticlesInDomain
if i~=j %Condition for checking undesired presence of a particle in its own neighbourhood
d=abs(CORD(i)-CORD(j)); %Distance between the two particles is stored in’d’ for comparison with the horizon value
if d<=horizon
neighbourhoodArray(i,p)=j;
p=p+1; %’p’ is incremented at every step to store only the particles within the horizon distance of a particular particle.
end
end
end
end
disp(neighbourhoodArray);
This code is part of a project on material failure modelling. I need to store all the particles (labelled as ‘j’ in the for loop) within a certain distance (lablled as ‘horizon’) from a particular particle (labelled as ‘i’ in the for loop). With the given data of horizon=0.3, spacing (between particles)=0.1, and length=1, number of particles in the domain will come out to be 10. The x-component of 1st particle is ‘0’ and that of the last one is ‘0.9’, as in the ‘xComponent’ array.
Now, with the given data, for the first particle (with CORD(1)=0), the neighbourhood particles should be those at CORD(2)=0.1 (Particle-2), CORD(3)=0.2 (Particle-3), CORD(3)=0.3 (Particle-4). But, in the neighbourhoodArray array, for the 1st particle, only Particle-2 and Particle-3 are being shown to be in the neighbourhood of Particle-1, which is incorrect.
I ran the code statement-by-statement using ‘Step’ and found that the compiler is not executing the statement under "if d<=horizon" when ‘d’ and ‘horizon’ have the same value (=0.3). I really don’t understand what the problem is with the conditional statement, as I think the logic that I have used is correct. horizon=0.3;
spacing=0.1;
length=1;
numberOfParticlesAlongX=floor(length/spacing);
numberOfParticlesInDomain=numberOfParticlesAlongX; %Number of particles in X-direction attributed to domain
xComponent(1:numberOfParticlesAlongX)=((1:numberOfParticlesAlongX)-1)*spacing; %Co-ordinate of each particle stored in xComponent
CORD=xComponent;
for i=1:numberOfParticlesInDomain
p=1;
for j=1:numberOfParticlesInDomain
if i~=j %Condition for checking undesired presence of a particle in its own neighbourhood
d=abs(CORD(i)-CORD(j)); %Distance between the two particles is stored in’d’ for comparison with the horizon value
if d<=horizon
neighbourhoodArray(i,p)=j;
p=p+1; %’p’ is incremented at every step to store only the particles within the horizon distance of a particular particle.
end
end
end
end
disp(neighbourhoodArray);
This code is part of a project on material failure modelling. I need to store all the particles (labelled as ‘j’ in the for loop) within a certain distance (lablled as ‘horizon’) from a particular particle (labelled as ‘i’ in the for loop). With the given data of horizon=0.3, spacing (between particles)=0.1, and length=1, number of particles in the domain will come out to be 10. The x-component of 1st particle is ‘0’ and that of the last one is ‘0.9’, as in the ‘xComponent’ array.
Now, with the given data, for the first particle (with CORD(1)=0), the neighbourhood particles should be those at CORD(2)=0.1 (Particle-2), CORD(3)=0.2 (Particle-3), CORD(3)=0.3 (Particle-4). But, in the neighbourhoodArray array, for the 1st particle, only Particle-2 and Particle-3 are being shown to be in the neighbourhood of Particle-1, which is incorrect.
I ran the code statement-by-statement using ‘Step’ and found that the compiler is not executing the statement under "if d<=horizon" when ‘d’ and ‘horizon’ have the same value (=0.3). I really don’t understand what the problem is with the conditional statement, as I think the logic that I have used is correct. matlab, conditional statement, array MATLAB Answers — New Questions
How to put conditions to find peaks in NDVI time series?
I am using following matlab code
findpeaks(data,days’MinPeakProminence’,60)
xlabel(‘days’)
ylabel(‘NDVI’)
title(‘Find Prominent Peaks’) here the data is NDVI time series attached here.I am using following matlab code
findpeaks(data,days’MinPeakProminence’,60)
xlabel(‘days’)
ylabel(‘NDVI’)
title(‘Find Prominent Peaks’) here the data is NDVI time series attached here. I am using following matlab code
findpeaks(data,days’MinPeakProminence’,60)
xlabel(‘days’)
ylabel(‘NDVI’)
title(‘Find Prominent Peaks’) here the data is NDVI time series attached here. how to put conditions for finding peaks? MATLAB Answers — New Questions
backtestStrategy: rebalance function keeps track of past & current open position
Hi All,
backtestStrategy provides a great workflow for defining a strategy, which includes the rebalancing function.
As part of the EngineData object, WeightsHistory can be used to derive open positions, entry price and open pnl. Nonetheless … the same computation takes place also within the backtestEngine’s runBacktest function, which provides access to a Positions table for each strategy.
Hoping not having to re-invent the wheel, is there a way to pass the Positions table into the rebalancing function, for a given strategy? This would be a good fit for an additional field into the engineData structure. ThxHi All,
backtestStrategy provides a great workflow for defining a strategy, which includes the rebalancing function.
As part of the EngineData object, WeightsHistory can be used to derive open positions, entry price and open pnl. Nonetheless … the same computation takes place also within the backtestEngine’s runBacktest function, which provides access to a Positions table for each strategy.
Hoping not having to re-invent the wheel, is there a way to pass the Positions table into the rebalancing function, for a given strategy? This would be a good fit for an additional field into the engineData structure. Thx Hi All,
backtestStrategy provides a great workflow for defining a strategy, which includes the rebalancing function.
As part of the EngineData object, WeightsHistory can be used to derive open positions, entry price and open pnl. Nonetheless … the same computation takes place also within the backtestEngine’s runBacktest function, which provides access to a Positions table for each strategy.
Hoping not having to re-invent the wheel, is there a way to pass the Positions table into the rebalancing function, for a given strategy? This would be a good fit for an additional field into the engineData structure. Thx matlab, portfolio management, finance, rebalancing, backteststrategy, enginedatalist, backtestengine, runbacktest MATLAB Answers — New Questions
Display of values on Y axis
When varying data is displayed on a chart the Y axis displays value lines. If all the data in a given chart window is the same then no Y value is shown. Can this be changed please?When varying data is displayed on a chart the Y axis displays value lines. If all the data in a given chart window is the same then no Y value is shown. Can this be changed please? When varying data is displayed on a chart the Y axis displays value lines. If all the data in a given chart window is the same then no Y value is shown. Can this be changed please? thingspeak MATLAB Answers — New Questions
Decision Branching, modification Script
Modify the script so that the plotting code on lines 4-7 are executed only when doPlot is 1.
plot(density)
title("Sample Densities")
xticklabels(element)
ylabel("Density (g/cm^3)")Modify the script so that the plotting code on lines 4-7 are executed only when doPlot is 1.
plot(density)
title("Sample Densities")
xticklabels(element)
ylabel("Density (g/cm^3)") Modify the script so that the plotting code on lines 4-7 are executed only when doPlot is 1.
plot(density)
title("Sample Densities")
xticklabels(element)
ylabel("Density (g/cm^3)") decision MATLAB Answers — New Questions
Plot a vector with a given angle against the y-axis
Hi, so as the title states I want to simply plot a line that will make an angle I already know with the y axis, as this line will be plotted in the same figure as other graphs I want it to also be scaled such that it can be seen in these figures as the order of magnitude changes. I know that the vector will have the slope k = sin(angle)/cos(angle) (as it will always intercept the origin) but how do I plot it so that its range is covered by the whole figure. I have attached a figure that shows an example of what I’m trying to plotHi, so as the title states I want to simply plot a line that will make an angle I already know with the y axis, as this line will be plotted in the same figure as other graphs I want it to also be scaled such that it can be seen in these figures as the order of magnitude changes. I know that the vector will have the slope k = sin(angle)/cos(angle) (as it will always intercept the origin) but how do I plot it so that its range is covered by the whole figure. I have attached a figure that shows an example of what I’m trying to plot Hi, so as the title states I want to simply plot a line that will make an angle I already know with the y axis, as this line will be plotted in the same figure as other graphs I want it to also be scaled such that it can be seen in these figures as the order of magnitude changes. I know that the vector will have the slope k = sin(angle)/cos(angle) (as it will always intercept the origin) but how do I plot it so that its range is covered by the whole figure. I have attached a figure that shows an example of what I’m trying to plot vectors, plotting MATLAB Answers — New Questions
Problem facing with “setup function” in Experiment Manager App
I am trying to hypertune my parameters of a cnn archtecture in Experiment manager in MATLAB 2024a version. It describes that the setup function needs at least 4 arguments (dataset, cnn structure, loss function and the training options). But I am struggling with the setup function whenever I put the loss function what is "crossentropy" in my experiment. I have tried several ways (I have given the screenshots of those attempts).
1.
2.
3.I am trying to hypertune my parameters of a cnn archtecture in Experiment manager in MATLAB 2024a version. It describes that the setup function needs at least 4 arguments (dataset, cnn structure, loss function and the training options). But I am struggling with the setup function whenever I put the loss function what is "crossentropy" in my experiment. I have tried several ways (I have given the screenshots of those attempts).
1.
2.
3. I am trying to hypertune my parameters of a cnn archtecture in Experiment manager in MATLAB 2024a version. It describes that the setup function needs at least 4 arguments (dataset, cnn structure, loss function and the training options). But I am struggling with the setup function whenever I put the loss function what is "crossentropy" in my experiment. I have tried several ways (I have given the screenshots of those attempts).
1.
2.
3. hyperparameter_tuning, experiment manager, setup_function MATLAB Answers — New Questions
I want to hide/embed a RGB image inside another RGB image using either Reversible Data Hiding or LSB substitution
while working on my project i want to color transform one image to look like another, I used Reinhard_StainNormalization and i got it.
Next i need to hide one RGB image within another image,i have an idea to use either RDH or LSB substitution,i found answers related to gray image which is not even perfect,so can anybody help me how to achieve this esp. on RGB image not on gray one.For example i need to hide my secret image in specific bits of my target image.help me anyone!!!!!while working on my project i want to color transform one image to look like another, I used Reinhard_StainNormalization and i got it.
Next i need to hide one RGB image within another image,i have an idea to use either RDH or LSB substitution,i found answers related to gray image which is not even perfect,so can anybody help me how to achieve this esp. on RGB image not on gray one.For example i need to hide my secret image in specific bits of my target image.help me anyone!!!!! while working on my project i want to color transform one image to look like another, I used Reinhard_StainNormalization and i got it.
Next i need to hide one RGB image within another image,i have an idea to use either RDH or LSB substitution,i found answers related to gray image which is not even perfect,so can anybody help me how to achieve this esp. on RGB image not on gray one.For example i need to hide my secret image in specific bits of my target image.help me anyone!!!!! steganography, lsb MATLAB Answers — New Questions
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