Tag Archives: matlab
I have problem using the simulink block obtained from LSTM trained network. The following is the error. number of inputs to be used is 2 and number of ouputs is 1
Error:Layer "sequenceinput": Invalid input data. Invalid size of channel dimension. Layer expects input with channel dimension size 2 but received input with size 1.
Function ‘Subsystem/Stateful Predict/MLFB’ (#218.166.365), line 5, column 19:
"deep.blocks.internal.sequenceNetworkPredict({in_1}, {size(in_1)}, {class(in_1)},"
Errors occurred during parsing of ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’.
Component:MATLAB Function | Category:Coder error
Simulink unable to determine sizes and/or types of the outputs for block ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’ due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Component:MATLAB Function | Category:Coder error
Simulink unable to determine sizes and/or types of the outputs for block ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’ due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Component:Simulink | Category:Model error
Error in port widths or dimensions. ‘Output Port 1’ of ‘neural_network_deep/Subsystem/Stateful Predict/MLFB/in_1’ is a one dimensionalError:Layer "sequenceinput": Invalid input data. Invalid size of channel dimension. Layer expects input with channel dimension size 2 but received input with size 1.
Function ‘Subsystem/Stateful Predict/MLFB’ (#218.166.365), line 5, column 19:
"deep.blocks.internal.sequenceNetworkPredict({in_1}, {size(in_1)}, {class(in_1)},"
Errors occurred during parsing of ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’.
Component:MATLAB Function | Category:Coder error
Simulink unable to determine sizes and/or types of the outputs for block ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’ due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Component:MATLAB Function | Category:Coder error
Simulink unable to determine sizes and/or types of the outputs for block ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’ due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Component:Simulink | Category:Model error
Error in port widths or dimensions. ‘Output Port 1’ of ‘neural_network_deep/Subsystem/Stateful Predict/MLFB/in_1’ is a one dimensional Error:Layer "sequenceinput": Invalid input data. Invalid size of channel dimension. Layer expects input with channel dimension size 2 but received input with size 1.
Function ‘Subsystem/Stateful Predict/MLFB’ (#218.166.365), line 5, column 19:
"deep.blocks.internal.sequenceNetworkPredict({in_1}, {size(in_1)}, {class(in_1)},"
Errors occurred during parsing of ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’.
Component:MATLAB Function | Category:Coder error
Simulink unable to determine sizes and/or types of the outputs for block ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’ due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Component:MATLAB Function | Category:Coder error
Simulink unable to determine sizes and/or types of the outputs for block ‘neural_network_deep/Subsystem/Stateful Predict/MLFB’ due to errors in the block body, or limitations of the underlying analysis. The errors might be inaccurate. Fix the indicated errors, or explicitly specify sizes and/or types for all block outputs.
Component:Simulink | Category:Model error
Error in port widths or dimensions. ‘Output Port 1’ of ‘neural_network_deep/Subsystem/Stateful Predict/MLFB/in_1’ is a one dimensional deep learning, lstm, simulink MATLAB Answers — New Questions
Simulink中生成Autosar代码中如何使得Min Max 生成fminf 或fmaxf 函数 ( How to make Min Max generate fminf or fmaxf functions when generating Autosar code in Simulink)
simulink 生成Autosar 代码中
如何设置Min 或 Max 在生成代码中使用fminf ,fmaxf 函数,
不想使得代码通过if else的方式来实现 Min 或Max
Generating Autosar code using Simulink
How to set Min or Max to use the fminf and fmaxf functions in generating code,
I don’t want the code to implement Min or Max through if else
目前在非Autosar代码中可以实现Min 或Max,但是在Autosar代码中不能实现Min 或Max,
Currently, Min or Max can be implemented in non Autosar code, but it cannot be implemented in Autosar code,simulink 生成Autosar 代码中
如何设置Min 或 Max 在生成代码中使用fminf ,fmaxf 函数,
不想使得代码通过if else的方式来实现 Min 或Max
Generating Autosar code using Simulink
How to set Min or Max to use the fminf and fmaxf functions in generating code,
I don’t want the code to implement Min or Max through if else
目前在非Autosar代码中可以实现Min 或Max,但是在Autosar代码中不能实现Min 或Max,
Currently, Min or Max can be implemented in non Autosar code, but it cannot be implemented in Autosar code, simulink 生成Autosar 代码中
如何设置Min 或 Max 在生成代码中使用fminf ,fmaxf 函数,
不想使得代码通过if else的方式来实现 Min 或Max
Generating Autosar code using Simulink
How to set Min or Max to use the fminf and fmaxf functions in generating code,
I don’t want the code to implement Min or Max through if else
目前在非Autosar代码中可以实现Min 或Max,但是在Autosar代码中不能实现Min 或Max,
Currently, Min or Max can be implemented in non Autosar code, but it cannot be implemented in Autosar code, autosar, fminf, fmaxf, simulink generated autosar code MATLAB Answers — New Questions
how to read the data of type a*b?
I have input dataset of following type:
‘1*5 5*4 6 8 3 12 -5 9*0 7*-1’
how can I read each value and store it in nice format.I have input dataset of following type:
‘1*5 5*4 6 8 3 12 -5 9*0 7*-1’
how can I read each value and store it in nice format. I have input dataset of following type:
‘1*5 5*4 6 8 3 12 -5 9*0 7*-1’
how can I read each value and store it in nice format. data, text file MATLAB Answers — New Questions
help me to do nonlinear fitting use lsqcurvefit
please help me, I am begginer in matlab and thsi is my first time doing nonlinear fitting, I have problem to fit data with the model non linear fitting (here I use lsqcurvefit), the flow of my code is something like this
get autocorrelation function(ACF), isolate half of it
get envelop of ACF,
fit envelope of ACF with equation E=1/t^2 exp (-2*pi*f*Qc) to get optimum Qc (with f is my freq=3, t is time lapse)
here the ilustration from source that i use
Here is my code, but i don’t really trust my self since the Qc value is not match with range (is uppose to get Wc between 100-400) but using my code i get thousand. Please is anyone can help me to clarify my code
clear; clc; %close all;
% Define the folder containing ACF files
folder_path = pwd; % Adjust the path to your ACF files
file_pattern = ‘cBPCen3_s6h_ACF_HGSD_HHZ_2023-12_2023-12-01T00_00.txt’; % Match ACF filenames
files = dir(fullfile(folder_path, file_pattern));
% Define the model function for nonlinear fitting
f=3;
m=2;
model = @(Qc, t) (1 ./ t.^m).*exp(-2 * pi * f * t ./ Qc);
% Initial guess for Qc
Qc_initial = 110;
options = optimset(‘Display’, ‘off’); % Suppress output
% File to store Qc_fitted_envelope results
results_file = fullfile(folder_path, ‘Qc_fitted_envelope_results.txt’);
if exist(results_file, ‘file’)
delete(results_file); % Clear old results if file exists
end
% Loop over each ACF file
for i = 1:length(files)
% Load ACF file
file_name = files(i).name;
file_path = fullfile(folder_path, file_name);
acf = load(file_path);
% Extract the ACF data
y_obs = acf((length(acf)/2):(end))’; % Adjust this as needed
% Compute the squared envelope of the ACF
envel = envelope(y_obs,5,’peak’)’;
envel = envel(1:round(0.5 * length(envel)));
tenvel = (1:length(envel))’;
% Perform nonlinear optimization for envelope
Qc_fitted_envelope = lsqcurvefit(@(Qc, tenvel) model(Qc, tenvel), Qc_initial, tenvel, envel, [], [], options);
y_fitted_envelope = model(Qc_fitted_envelope, tenvel);
rms_error_envelope = sqrt(mean((envel – y_fitted_envelope).^2));
% Plot results for each file – DEACTIVATE FOR BIG LOOPING
figure;
plot(tenvel/100,envel, ‘k-‘, ‘DisplayName’, ‘Envelope (Observed)’);
hold on;
plot(tenvel/100, y_fitted_envelope, ‘r-‘, ‘LineWidth’, 1.5, ‘DisplayName’, sprintf(‘Envelope (Fitted, RMS=%.4f)’, rms_error_envelope));
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(sprintf(‘Envelope Fit – Qc = %.4f, RMS Error = %.4f’, Qc_fitted_envelope, rms_error_envelope));
legend(‘Location’, ‘northeast’);
%set(gca, ‘YScale’, ‘log’)
grid on;
% Save the envelope to a text file – DO YOU REALLY NEED SAVE THIS??
% output_file_name = [‘envel_’ file_name];
% output_file_path = fullfile(folder_path, output_file_name);
% save(output_file_path, ‘envelope’, ‘-ascii’);
% fprintf(‘Envelope saved to %sn’, output_file_name);
% Save the Qc_fitted_envelope result to the text file
fid = fopen(results_file, ‘a’); % Open in append mode
fprintf(fid, ‘%st%.4fn’, file_name, Qc_fitted_envelope);
fclose(fid);
% Display results in the command window
fprintf(‘File: %sn’, file_name);
fprintf(‘ Envelope: Fitted Qc = %.4f, RMS Error = %.4fnn’, Qc_fitted_envelope, rms_error_envelope);
endplease help me, I am begginer in matlab and thsi is my first time doing nonlinear fitting, I have problem to fit data with the model non linear fitting (here I use lsqcurvefit), the flow of my code is something like this
get autocorrelation function(ACF), isolate half of it
get envelop of ACF,
fit envelope of ACF with equation E=1/t^2 exp (-2*pi*f*Qc) to get optimum Qc (with f is my freq=3, t is time lapse)
here the ilustration from source that i use
Here is my code, but i don’t really trust my self since the Qc value is not match with range (is uppose to get Wc between 100-400) but using my code i get thousand. Please is anyone can help me to clarify my code
clear; clc; %close all;
% Define the folder containing ACF files
folder_path = pwd; % Adjust the path to your ACF files
file_pattern = ‘cBPCen3_s6h_ACF_HGSD_HHZ_2023-12_2023-12-01T00_00.txt’; % Match ACF filenames
files = dir(fullfile(folder_path, file_pattern));
% Define the model function for nonlinear fitting
f=3;
m=2;
model = @(Qc, t) (1 ./ t.^m).*exp(-2 * pi * f * t ./ Qc);
% Initial guess for Qc
Qc_initial = 110;
options = optimset(‘Display’, ‘off’); % Suppress output
% File to store Qc_fitted_envelope results
results_file = fullfile(folder_path, ‘Qc_fitted_envelope_results.txt’);
if exist(results_file, ‘file’)
delete(results_file); % Clear old results if file exists
end
% Loop over each ACF file
for i = 1:length(files)
% Load ACF file
file_name = files(i).name;
file_path = fullfile(folder_path, file_name);
acf = load(file_path);
% Extract the ACF data
y_obs = acf((length(acf)/2):(end))’; % Adjust this as needed
% Compute the squared envelope of the ACF
envel = envelope(y_obs,5,’peak’)’;
envel = envel(1:round(0.5 * length(envel)));
tenvel = (1:length(envel))’;
% Perform nonlinear optimization for envelope
Qc_fitted_envelope = lsqcurvefit(@(Qc, tenvel) model(Qc, tenvel), Qc_initial, tenvel, envel, [], [], options);
y_fitted_envelope = model(Qc_fitted_envelope, tenvel);
rms_error_envelope = sqrt(mean((envel – y_fitted_envelope).^2));
% Plot results for each file – DEACTIVATE FOR BIG LOOPING
figure;
plot(tenvel/100,envel, ‘k-‘, ‘DisplayName’, ‘Envelope (Observed)’);
hold on;
plot(tenvel/100, y_fitted_envelope, ‘r-‘, ‘LineWidth’, 1.5, ‘DisplayName’, sprintf(‘Envelope (Fitted, RMS=%.4f)’, rms_error_envelope));
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(sprintf(‘Envelope Fit – Qc = %.4f, RMS Error = %.4f’, Qc_fitted_envelope, rms_error_envelope));
legend(‘Location’, ‘northeast’);
%set(gca, ‘YScale’, ‘log’)
grid on;
% Save the envelope to a text file – DO YOU REALLY NEED SAVE THIS??
% output_file_name = [‘envel_’ file_name];
% output_file_path = fullfile(folder_path, output_file_name);
% save(output_file_path, ‘envelope’, ‘-ascii’);
% fprintf(‘Envelope saved to %sn’, output_file_name);
% Save the Qc_fitted_envelope result to the text file
fid = fopen(results_file, ‘a’); % Open in append mode
fprintf(fid, ‘%st%.4fn’, file_name, Qc_fitted_envelope);
fclose(fid);
% Display results in the command window
fprintf(‘File: %sn’, file_name);
fprintf(‘ Envelope: Fitted Qc = %.4f, RMS Error = %.4fnn’, Qc_fitted_envelope, rms_error_envelope);
end please help me, I am begginer in matlab and thsi is my first time doing nonlinear fitting, I have problem to fit data with the model non linear fitting (here I use lsqcurvefit), the flow of my code is something like this
get autocorrelation function(ACF), isolate half of it
get envelop of ACF,
fit envelope of ACF with equation E=1/t^2 exp (-2*pi*f*Qc) to get optimum Qc (with f is my freq=3, t is time lapse)
here the ilustration from source that i use
Here is my code, but i don’t really trust my self since the Qc value is not match with range (is uppose to get Wc between 100-400) but using my code i get thousand. Please is anyone can help me to clarify my code
clear; clc; %close all;
% Define the folder containing ACF files
folder_path = pwd; % Adjust the path to your ACF files
file_pattern = ‘cBPCen3_s6h_ACF_HGSD_HHZ_2023-12_2023-12-01T00_00.txt’; % Match ACF filenames
files = dir(fullfile(folder_path, file_pattern));
% Define the model function for nonlinear fitting
f=3;
m=2;
model = @(Qc, t) (1 ./ t.^m).*exp(-2 * pi * f * t ./ Qc);
% Initial guess for Qc
Qc_initial = 110;
options = optimset(‘Display’, ‘off’); % Suppress output
% File to store Qc_fitted_envelope results
results_file = fullfile(folder_path, ‘Qc_fitted_envelope_results.txt’);
if exist(results_file, ‘file’)
delete(results_file); % Clear old results if file exists
end
% Loop over each ACF file
for i = 1:length(files)
% Load ACF file
file_name = files(i).name;
file_path = fullfile(folder_path, file_name);
acf = load(file_path);
% Extract the ACF data
y_obs = acf((length(acf)/2):(end))’; % Adjust this as needed
% Compute the squared envelope of the ACF
envel = envelope(y_obs,5,’peak’)’;
envel = envel(1:round(0.5 * length(envel)));
tenvel = (1:length(envel))’;
% Perform nonlinear optimization for envelope
Qc_fitted_envelope = lsqcurvefit(@(Qc, tenvel) model(Qc, tenvel), Qc_initial, tenvel, envel, [], [], options);
y_fitted_envelope = model(Qc_fitted_envelope, tenvel);
rms_error_envelope = sqrt(mean((envel – y_fitted_envelope).^2));
% Plot results for each file – DEACTIVATE FOR BIG LOOPING
figure;
plot(tenvel/100,envel, ‘k-‘, ‘DisplayName’, ‘Envelope (Observed)’);
hold on;
plot(tenvel/100, y_fitted_envelope, ‘r-‘, ‘LineWidth’, 1.5, ‘DisplayName’, sprintf(‘Envelope (Fitted, RMS=%.4f)’, rms_error_envelope));
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(sprintf(‘Envelope Fit – Qc = %.4f, RMS Error = %.4f’, Qc_fitted_envelope, rms_error_envelope));
legend(‘Location’, ‘northeast’);
%set(gca, ‘YScale’, ‘log’)
grid on;
% Save the envelope to a text file – DO YOU REALLY NEED SAVE THIS??
% output_file_name = [‘envel_’ file_name];
% output_file_path = fullfile(folder_path, output_file_name);
% save(output_file_path, ‘envelope’, ‘-ascii’);
% fprintf(‘Envelope saved to %sn’, output_file_name);
% Save the Qc_fitted_envelope result to the text file
fid = fopen(results_file, ‘a’); % Open in append mode
fprintf(fid, ‘%st%.4fn’, file_name, Qc_fitted_envelope);
fclose(fid);
% Display results in the command window
fprintf(‘File: %sn’, file_name);
fprintf(‘ Envelope: Fitted Qc = %.4f, RMS Error = %.4fnn’, Qc_fitted_envelope, rms_error_envelope);
end nonlinear fitting, lsqcurvefit, envelope MATLAB Answers — New Questions
How to install RFblockset on a standalone PC witth installed Matlab2024a
Hello,
We have installed Matlab2024a on a standalone PC. We have got an updated licence for RFblockset. It seems to be that the RFblockset wasn’t previuously installed on the PC. Thus,we ran again the setup.exe with the iso file (used previously). The licence file was put in the previous licence directory. When we run the installation, we got a message explaining it was unable to install Matlab in the same directory.
Is there another trick to install an additionnal toolbox?
Many thanks.
Best regardsHello,
We have installed Matlab2024a on a standalone PC. We have got an updated licence for RFblockset. It seems to be that the RFblockset wasn’t previuously installed on the PC. Thus,we ran again the setup.exe with the iso file (used previously). The licence file was put in the previous licence directory. When we run the installation, we got a message explaining it was unable to install Matlab in the same directory.
Is there another trick to install an additionnal toolbox?
Many thanks.
Best regards Hello,
We have installed Matlab2024a on a standalone PC. We have got an updated licence for RFblockset. It seems to be that the RFblockset wasn’t previuously installed on the PC. Thus,we ran again the setup.exe with the iso file (used previously). The licence file was put in the previous licence directory. When we run the installation, we got a message explaining it was unable to install Matlab in the same directory.
Is there another trick to install an additionnal toolbox?
Many thanks.
Best regards rfblockset installation MATLAB Answers — New Questions
Simulink can’t simulation with three Carsim(2019) car
I use Carsim2019 create two car Send to Simulink is workd, but can’t simulation when i create three carsim car.I use Carsim2019 create two car Send to Simulink is workd, but can’t simulation when i create three carsim car. I use Carsim2019 create two car Send to Simulink is workd, but can’t simulation when i create three carsim car. carsim2019, simulink, threecar MATLAB Answers — New Questions
Problem in boundary condition
Hi
im trying to solve a proble in EM with method of MAS ( METHOD OF AUXILARY SOURCE)
I have a infiite cylinder ( PERFECT CONDUCTOR) and in incominf fileld strike the cylinder FROM THE Ein+Escat=0 in the surface of cylinder i solve th system and i fins the current Is ( the function is the currentMAS()) . After i find the Escat field form the epresion of MAS theort. After the i check the
sumEs_surf =abs(Etotal(xs,ys))
Etotal= Escat(x,y)+E_in_z(x,y)
xs=ra cos(phi)
ys=cos(phi)
rho = ra;
phi =2*pi*(0:Nc-1)/Nc% Create phi values
% Compute Cartesian coordinates (xa, ya)
xs = rho .* cos(phi); % x-coordinates
ys = rho .* sin(phi); % y-coordinates
the sum is not equal to zero !! the real part is zero but the imaginary not
function [Is] = currentMAS()
%UNTITLED Summary of this function goes here
% Detailed explanation goes her
[~,N,Nc,a,ra,k0,Z0,~] = parameter();
% Preallocate arrays for efficiency
xc = ra * cos(2 * pi * (0:N-1)/N); % Observation points (x-coordinates)
yc = ra* sin(2 * pi*(0:N-1)/N); % Observation points (y-coordinates)
xa = a * cos(2 * pi * (0:Nc-1) / Nc); % Source points (x-coordinates)
ya = a * sin(2 * pi * (0:Nc-1) / Nc); % Source points (y-coordinates)
% Compute distance matrix R between source and observation points
[Xa, XC] = meshgrid(xa, xc); % Observation (columns), Source (rows)
[Ya, YC] = meshgrid(ya, yc);
Ra= sqrt((Xa – XC).^2 + (Ya – YC).^2);
% Compute matrix WI based on the Green’s function
WI = (1 / 4) * k0 * Z0 .* besselh(0, 2, k0 .* Ra);
% Compute the source field at each source point
Source = arrayfun(@(xi, yi)E_in_z(xi,yi),xc,yc);
%Source = E_in_z(xc, 0);
%Is = linsolve(WI, Source’);
%lambda = 1e-1; % Regularization factor
%Is = (WI’ * WI + lambda * eye(size(WI, 2))) (WI’ * Source’);
Is =(pinv(WI)* Source’)
end
function z = Escat(x, y)
% Get the current values from the input parameters
[Is] = currentMAS()
[f,N,Nc,a,ra,k0,Z0,lambda] = parameter();
% Precompute coordinates of the points
xx = a * cos(2 * pi * (0:Nc-1) / Nc); % Length Nc
yy = a * sin(2 * pi * (0:Nc-1) / Nc); % Length Nc
% Initialize the S_UM for each (x, y) pair
E_scat = zeros(size(x)); % Result will be the same size as x and y
% Compute the distances and the contributions for each (x, y) pair
for jj = 1:Nc
RR = sqrt((x – xx(jj)).^2 + (y – yy(jj)).^2); % Calculate distance for all (x, y)
% Sum the contributions (note the broadcasting)
E_scat = E_scat – (1/4).*Is(jj) .* k0 * Z0 .* besselh(0, 2, k0 .* RR);
end
% Output the computed value
z = E_scat;
end
function [f,N,Nc,a,ra,k0,Z0,lambda] = parameter()
%UNTITLED Summary of this function goes here
c0=3e8;
Z0=120.*pi;
ra=1;
a=0.85;
N=120;
Nc=120;
f=300e6;
lambda=c0./f;
k0=2*pi./lambda;
end
function y = Etotal(x,y)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
y=Escat(x,y)+E_in_z(x,y);
end
function z=E_in_z(x,y)
%amplitude
[f,N,Nc,a,ra,k0,Z0] = parameter();
E0=1;
z=E0.*exp(1i.*k0*x);
end
I Atach the mathematical description
tnank you
i wish a happy new yearHi
im trying to solve a proble in EM with method of MAS ( METHOD OF AUXILARY SOURCE)
I have a infiite cylinder ( PERFECT CONDUCTOR) and in incominf fileld strike the cylinder FROM THE Ein+Escat=0 in the surface of cylinder i solve th system and i fins the current Is ( the function is the currentMAS()) . After i find the Escat field form the epresion of MAS theort. After the i check the
sumEs_surf =abs(Etotal(xs,ys))
Etotal= Escat(x,y)+E_in_z(x,y)
xs=ra cos(phi)
ys=cos(phi)
rho = ra;
phi =2*pi*(0:Nc-1)/Nc% Create phi values
% Compute Cartesian coordinates (xa, ya)
xs = rho .* cos(phi); % x-coordinates
ys = rho .* sin(phi); % y-coordinates
the sum is not equal to zero !! the real part is zero but the imaginary not
function [Is] = currentMAS()
%UNTITLED Summary of this function goes here
% Detailed explanation goes her
[~,N,Nc,a,ra,k0,Z0,~] = parameter();
% Preallocate arrays for efficiency
xc = ra * cos(2 * pi * (0:N-1)/N); % Observation points (x-coordinates)
yc = ra* sin(2 * pi*(0:N-1)/N); % Observation points (y-coordinates)
xa = a * cos(2 * pi * (0:Nc-1) / Nc); % Source points (x-coordinates)
ya = a * sin(2 * pi * (0:Nc-1) / Nc); % Source points (y-coordinates)
% Compute distance matrix R between source and observation points
[Xa, XC] = meshgrid(xa, xc); % Observation (columns), Source (rows)
[Ya, YC] = meshgrid(ya, yc);
Ra= sqrt((Xa – XC).^2 + (Ya – YC).^2);
% Compute matrix WI based on the Green’s function
WI = (1 / 4) * k0 * Z0 .* besselh(0, 2, k0 .* Ra);
% Compute the source field at each source point
Source = arrayfun(@(xi, yi)E_in_z(xi,yi),xc,yc);
%Source = E_in_z(xc, 0);
%Is = linsolve(WI, Source’);
%lambda = 1e-1; % Regularization factor
%Is = (WI’ * WI + lambda * eye(size(WI, 2))) (WI’ * Source’);
Is =(pinv(WI)* Source’)
end
function z = Escat(x, y)
% Get the current values from the input parameters
[Is] = currentMAS()
[f,N,Nc,a,ra,k0,Z0,lambda] = parameter();
% Precompute coordinates of the points
xx = a * cos(2 * pi * (0:Nc-1) / Nc); % Length Nc
yy = a * sin(2 * pi * (0:Nc-1) / Nc); % Length Nc
% Initialize the S_UM for each (x, y) pair
E_scat = zeros(size(x)); % Result will be the same size as x and y
% Compute the distances and the contributions for each (x, y) pair
for jj = 1:Nc
RR = sqrt((x – xx(jj)).^2 + (y – yy(jj)).^2); % Calculate distance for all (x, y)
% Sum the contributions (note the broadcasting)
E_scat = E_scat – (1/4).*Is(jj) .* k0 * Z0 .* besselh(0, 2, k0 .* RR);
end
% Output the computed value
z = E_scat;
end
function [f,N,Nc,a,ra,k0,Z0,lambda] = parameter()
%UNTITLED Summary of this function goes here
c0=3e8;
Z0=120.*pi;
ra=1;
a=0.85;
N=120;
Nc=120;
f=300e6;
lambda=c0./f;
k0=2*pi./lambda;
end
function y = Etotal(x,y)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
y=Escat(x,y)+E_in_z(x,y);
end
function z=E_in_z(x,y)
%amplitude
[f,N,Nc,a,ra,k0,Z0] = parameter();
E0=1;
z=E0.*exp(1i.*k0*x);
end
I Atach the mathematical description
tnank you
i wish a happy new year Hi
im trying to solve a proble in EM with method of MAS ( METHOD OF AUXILARY SOURCE)
I have a infiite cylinder ( PERFECT CONDUCTOR) and in incominf fileld strike the cylinder FROM THE Ein+Escat=0 in the surface of cylinder i solve th system and i fins the current Is ( the function is the currentMAS()) . After i find the Escat field form the epresion of MAS theort. After the i check the
sumEs_surf =abs(Etotal(xs,ys))
Etotal= Escat(x,y)+E_in_z(x,y)
xs=ra cos(phi)
ys=cos(phi)
rho = ra;
phi =2*pi*(0:Nc-1)/Nc% Create phi values
% Compute Cartesian coordinates (xa, ya)
xs = rho .* cos(phi); % x-coordinates
ys = rho .* sin(phi); % y-coordinates
the sum is not equal to zero !! the real part is zero but the imaginary not
function [Is] = currentMAS()
%UNTITLED Summary of this function goes here
% Detailed explanation goes her
[~,N,Nc,a,ra,k0,Z0,~] = parameter();
% Preallocate arrays for efficiency
xc = ra * cos(2 * pi * (0:N-1)/N); % Observation points (x-coordinates)
yc = ra* sin(2 * pi*(0:N-1)/N); % Observation points (y-coordinates)
xa = a * cos(2 * pi * (0:Nc-1) / Nc); % Source points (x-coordinates)
ya = a * sin(2 * pi * (0:Nc-1) / Nc); % Source points (y-coordinates)
% Compute distance matrix R between source and observation points
[Xa, XC] = meshgrid(xa, xc); % Observation (columns), Source (rows)
[Ya, YC] = meshgrid(ya, yc);
Ra= sqrt((Xa – XC).^2 + (Ya – YC).^2);
% Compute matrix WI based on the Green’s function
WI = (1 / 4) * k0 * Z0 .* besselh(0, 2, k0 .* Ra);
% Compute the source field at each source point
Source = arrayfun(@(xi, yi)E_in_z(xi,yi),xc,yc);
%Source = E_in_z(xc, 0);
%Is = linsolve(WI, Source’);
%lambda = 1e-1; % Regularization factor
%Is = (WI’ * WI + lambda * eye(size(WI, 2))) (WI’ * Source’);
Is =(pinv(WI)* Source’)
end
function z = Escat(x, y)
% Get the current values from the input parameters
[Is] = currentMAS()
[f,N,Nc,a,ra,k0,Z0,lambda] = parameter();
% Precompute coordinates of the points
xx = a * cos(2 * pi * (0:Nc-1) / Nc); % Length Nc
yy = a * sin(2 * pi * (0:Nc-1) / Nc); % Length Nc
% Initialize the S_UM for each (x, y) pair
E_scat = zeros(size(x)); % Result will be the same size as x and y
% Compute the distances and the contributions for each (x, y) pair
for jj = 1:Nc
RR = sqrt((x – xx(jj)).^2 + (y – yy(jj)).^2); % Calculate distance for all (x, y)
% Sum the contributions (note the broadcasting)
E_scat = E_scat – (1/4).*Is(jj) .* k0 * Z0 .* besselh(0, 2, k0 .* RR);
end
% Output the computed value
z = E_scat;
end
function [f,N,Nc,a,ra,k0,Z0,lambda] = parameter()
%UNTITLED Summary of this function goes here
c0=3e8;
Z0=120.*pi;
ra=1;
a=0.85;
N=120;
Nc=120;
f=300e6;
lambda=c0./f;
k0=2*pi./lambda;
end
function y = Etotal(x,y)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
y=Escat(x,y)+E_in_z(x,y);
end
function z=E_in_z(x,y)
%amplitude
[f,N,Nc,a,ra,k0,Z0] = parameter();
E0=1;
z=E0.*exp(1i.*k0*x);
end
I Atach the mathematical description
tnank you
i wish a happy new year matrix array, boundary, mas MATLAB Answers — New Questions
Why are graphic positions not observable properties?
Back story: I am trying to port dialog boxes based on uicontrols to their uifigure equivalents: uilabel, uibutton, etc. The old system allowed you to size items based on the text contained within using the Extent property. For example, one could add a button with the String ‘Apply’, adjust the position to accomodate that text, and then size the figure as needed. Newer components lack an Extent property, and the closest I can come to that feature is stacking things in a uigridlayout using ‘fit’ for the row height and column width. However, there is noticeable lag, around a second or so, between when the component is created and grid sizing. The attached function illustrates this with a separate plot showing how long it takes for a uilable’s width/height to change from its default value.
I thought one would be able to add a listener to the grid or component contained within to see when sizing is complete. However, the Position property is not an observable property for the grid layout or a uilable inside. Is there some reason for that? The lag is bad enough, but at least I could keep the figure hidden until all resizing is complete. Right now I have to guess as to how long this might take, put in a manual delay, and then hope all layout grids are done changing before sizing the figure based on what is inside.
FWIW I am using the latest update of R2024b with the desktop beta on a Mac.Back story: I am trying to port dialog boxes based on uicontrols to their uifigure equivalents: uilabel, uibutton, etc. The old system allowed you to size items based on the text contained within using the Extent property. For example, one could add a button with the String ‘Apply’, adjust the position to accomodate that text, and then size the figure as needed. Newer components lack an Extent property, and the closest I can come to that feature is stacking things in a uigridlayout using ‘fit’ for the row height and column width. However, there is noticeable lag, around a second or so, between when the component is created and grid sizing. The attached function illustrates this with a separate plot showing how long it takes for a uilable’s width/height to change from its default value.
I thought one would be able to add a listener to the grid or component contained within to see when sizing is complete. However, the Position property is not an observable property for the grid layout or a uilable inside. Is there some reason for that? The lag is bad enough, but at least I could keep the figure hidden until all resizing is complete. Right now I have to guess as to how long this might take, put in a manual delay, and then hope all layout grids are done changing before sizing the figure based on what is inside.
FWIW I am using the latest update of R2024b with the desktop beta on a Mac. Back story: I am trying to port dialog boxes based on uicontrols to their uifigure equivalents: uilabel, uibutton, etc. The old system allowed you to size items based on the text contained within using the Extent property. For example, one could add a button with the String ‘Apply’, adjust the position to accomodate that text, and then size the figure as needed. Newer components lack an Extent property, and the closest I can come to that feature is stacking things in a uigridlayout using ‘fit’ for the row height and column width. However, there is noticeable lag, around a second or so, between when the component is created and grid sizing. The attached function illustrates this with a separate plot showing how long it takes for a uilable’s width/height to change from its default value.
I thought one would be able to add a listener to the grid or component contained within to see when sizing is complete. However, the Position property is not an observable property for the grid layout or a uilable inside. Is there some reason for that? The lag is bad enough, but at least I could keep the figure hidden until all resizing is complete. Right now I have to guess as to how long this might take, put in a manual delay, and then hope all layout grids are done changing before sizing the figure based on what is inside.
FWIW I am using the latest update of R2024b with the desktop beta on a Mac. graphics, slow, listener MATLAB Answers — New Questions
How can i remove singular Jacobin error from this code?
william()
function william
clc
clear all format long
w=1; %wlmsn
Ha=0.1;
Re=0.4;
angle_degrees=0.1; %omega N,a,Ha,Re,angle_degrees,E,Pr
E=0.1; %Ec
Pr=0.2; %0.01
phi1=0.001;%0.02,0.03
phi2=0.001;%0.03,0.2
rof=997.1;
ro1=8933;
ro2=3970;
rocpf=4179;
rocp1= 385;
rocp2= 765;
kf=0.613;
k1=401;
k2=40
sigmaf=0.05;
sigma1=5.96*10^7;
sigma2=3.69*10^7;
A1=(phi2*rocp2)/rocpf+ (1-phi2)*((1-phi1)+(rocp1*phi1)/rocpf);
A2=((1-phi2)*((1-phi1)+(ro1*phi1)/rof)+(ro2*phi2)/rof);
A= ((sigma1*(1-2*(phi1)) + 2*sigmaf*(1-phi1))/(sigma1*(1-phi1) + 2*sigmaf*(1+phi1))); %sigmaf
A3=((sigma2*(1+2*(phi2))+2*(1-phi2)*A)/(sigma2*(1-phi2)+(2+phi2)*A))*A;
%A3=((sigma2+2*(1-phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))+2*phi2*sigma2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1)))/(sigma2+2*(1+phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))-phi2*sigma2);
A4=((1-phi1)^-2.5)*((1-phi2)^-2.5); %meuf
A5=(((2 * (1 + phi1) * (2 * kf – 2 * phi2 * (k2 – kf) + k2)) / (2 * kf + phi2 * (k2 – kf) + k2) + ((1 – 2 * phi1) * k1) / kf) / (2 – phi1)) * ((2 * kf – 2 * phi2 * (k2 – kf) + k2) / (2 * kf + phi2 * (k2 – kf) + k2)) + ((1 + phi1) * k1) / kf;
infinity=1;
solinit = bvpinit(linspace(0,infinity,20),zeros(5,1));
options=bvpset(‘Stats’,’on’,’RelTol’,1e-6);
lines={‘k’,’r’,’g’,’m’,’k–‘,’r–‘,’g–‘,’b–‘,’y’,’m’,’k’,’b’};
Ha=0.1;
sol1 = bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.3;
sol2 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.5;
sol3 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.7;
sol4= bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
figure(1);
plot(sol1.x,sol1.y(1,:),lines{1},sol2.x,sol2.y(1,:),lines{2},sol3.x,sol3.y(1,:),lines{3},sol4.x,sol4.y(1,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘eta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
figure(2);
plot(sol1.x,sol1.y(4,:),lines{1},sol2.x,sol2.y(4,:),lines{2},sol3.x,sol3.y(4,:),lines{3},sol4.x,sol4.y(4,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘kappa’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
y1 = sol1.y;
y2 = sol2.y;
function dydx = williamode(x,y,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
dydx =zeros(5,1);
dydx = [y(2)
y(3)
%-(sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) / (sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2))) * (2 * angle_degrees * Re * A2 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * y(1) * y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+(w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2)*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3))+(1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2)));
-(sqrt((2*y(1)*angle_degrees)^2+y(2)^2)/((sqrt((2*y(1)*angle_degrees)^2+y(2)^2))+w*(2*y(2)^2+4*y(1)^2*angle_degrees^2)))*(2*angle_degrees*Re*A2*(1-phi1)^2.5*(1-phi2)^2.5*y(1)*y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+((w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2))*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3)))+((1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2))))
%-(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) /(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2)))*(2*angle_degrees *Re*A2*(1 – phi1)^2.5*(1 – phi2)^2.5 * y(1) * y(2) +(4 – A3 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * (Ha)^2) * y(2) * angle_degrees^2 +((w * (sqrt(2 * y(1) * angle_degrees)^2 + y(2)^2)) *((16 * y(1)^3 * angle_degrees^4 + 8 * y(1) * y(2)^2 * angle_degrees^2 + 2 * y(2)^2 * y(3) +4 * y(1)^2 * y(3) * angle_degrees^2) /(4 * y(1) * y(2) * angle_degrees^2 + y(2) * y(3)) +((1 / ((2 * y(1) * angle_degrees)^2 + y(2)^2)) *(80 * y(1)^2 * y(2) * angle_degrees^4 + 32 * y(1) * y(2) * y(3) * angle_degrees^2+8 * y(2)^3 * angle_degrees^2 + 4 * y(2) * y(3)^2)));
y(5)
(-1/A5)*((E*Pr*A1)/(1-phi1)^2.5*(1-phi2)^2.5)*((4*y(1)^2*angle_degrees^2+y(2)^2)+w*((4*y(1)^2*angle_degrees^2+y(2)^2)^3/2))]
end
function res = williambc(ya,yb,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,~,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
res =[ya(1)-1;
ya(2);
ya(5);
yb(1);
yb(4)-1;];
hold on
end
grid on
endwilliam()
function william
clc
clear all format long
w=1; %wlmsn
Ha=0.1;
Re=0.4;
angle_degrees=0.1; %omega N,a,Ha,Re,angle_degrees,E,Pr
E=0.1; %Ec
Pr=0.2; %0.01
phi1=0.001;%0.02,0.03
phi2=0.001;%0.03,0.2
rof=997.1;
ro1=8933;
ro2=3970;
rocpf=4179;
rocp1= 385;
rocp2= 765;
kf=0.613;
k1=401;
k2=40
sigmaf=0.05;
sigma1=5.96*10^7;
sigma2=3.69*10^7;
A1=(phi2*rocp2)/rocpf+ (1-phi2)*((1-phi1)+(rocp1*phi1)/rocpf);
A2=((1-phi2)*((1-phi1)+(ro1*phi1)/rof)+(ro2*phi2)/rof);
A= ((sigma1*(1-2*(phi1)) + 2*sigmaf*(1-phi1))/(sigma1*(1-phi1) + 2*sigmaf*(1+phi1))); %sigmaf
A3=((sigma2*(1+2*(phi2))+2*(1-phi2)*A)/(sigma2*(1-phi2)+(2+phi2)*A))*A;
%A3=((sigma2+2*(1-phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))+2*phi2*sigma2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1)))/(sigma2+2*(1+phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))-phi2*sigma2);
A4=((1-phi1)^-2.5)*((1-phi2)^-2.5); %meuf
A5=(((2 * (1 + phi1) * (2 * kf – 2 * phi2 * (k2 – kf) + k2)) / (2 * kf + phi2 * (k2 – kf) + k2) + ((1 – 2 * phi1) * k1) / kf) / (2 – phi1)) * ((2 * kf – 2 * phi2 * (k2 – kf) + k2) / (2 * kf + phi2 * (k2 – kf) + k2)) + ((1 + phi1) * k1) / kf;
infinity=1;
solinit = bvpinit(linspace(0,infinity,20),zeros(5,1));
options=bvpset(‘Stats’,’on’,’RelTol’,1e-6);
lines={‘k’,’r’,’g’,’m’,’k–‘,’r–‘,’g–‘,’b–‘,’y’,’m’,’k’,’b’};
Ha=0.1;
sol1 = bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.3;
sol2 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.5;
sol3 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.7;
sol4= bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
figure(1);
plot(sol1.x,sol1.y(1,:),lines{1},sol2.x,sol2.y(1,:),lines{2},sol3.x,sol3.y(1,:),lines{3},sol4.x,sol4.y(1,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘eta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
figure(2);
plot(sol1.x,sol1.y(4,:),lines{1},sol2.x,sol2.y(4,:),lines{2},sol3.x,sol3.y(4,:),lines{3},sol4.x,sol4.y(4,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘kappa’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
y1 = sol1.y;
y2 = sol2.y;
function dydx = williamode(x,y,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
dydx =zeros(5,1);
dydx = [y(2)
y(3)
%-(sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) / (sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2))) * (2 * angle_degrees * Re * A2 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * y(1) * y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+(w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2)*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3))+(1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2)));
-(sqrt((2*y(1)*angle_degrees)^2+y(2)^2)/((sqrt((2*y(1)*angle_degrees)^2+y(2)^2))+w*(2*y(2)^2+4*y(1)^2*angle_degrees^2)))*(2*angle_degrees*Re*A2*(1-phi1)^2.5*(1-phi2)^2.5*y(1)*y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+((w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2))*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3)))+((1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2))))
%-(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) /(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2)))*(2*angle_degrees *Re*A2*(1 – phi1)^2.5*(1 – phi2)^2.5 * y(1) * y(2) +(4 – A3 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * (Ha)^2) * y(2) * angle_degrees^2 +((w * (sqrt(2 * y(1) * angle_degrees)^2 + y(2)^2)) *((16 * y(1)^3 * angle_degrees^4 + 8 * y(1) * y(2)^2 * angle_degrees^2 + 2 * y(2)^2 * y(3) +4 * y(1)^2 * y(3) * angle_degrees^2) /(4 * y(1) * y(2) * angle_degrees^2 + y(2) * y(3)) +((1 / ((2 * y(1) * angle_degrees)^2 + y(2)^2)) *(80 * y(1)^2 * y(2) * angle_degrees^4 + 32 * y(1) * y(2) * y(3) * angle_degrees^2+8 * y(2)^3 * angle_degrees^2 + 4 * y(2) * y(3)^2)));
y(5)
(-1/A5)*((E*Pr*A1)/(1-phi1)^2.5*(1-phi2)^2.5)*((4*y(1)^2*angle_degrees^2+y(2)^2)+w*((4*y(1)^2*angle_degrees^2+y(2)^2)^3/2))]
end
function res = williambc(ya,yb,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,~,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
res =[ya(1)-1;
ya(2);
ya(5);
yb(1);
yb(4)-1;];
hold on
end
grid on
end william()
function william
clc
clear all format long
w=1; %wlmsn
Ha=0.1;
Re=0.4;
angle_degrees=0.1; %omega N,a,Ha,Re,angle_degrees,E,Pr
E=0.1; %Ec
Pr=0.2; %0.01
phi1=0.001;%0.02,0.03
phi2=0.001;%0.03,0.2
rof=997.1;
ro1=8933;
ro2=3970;
rocpf=4179;
rocp1= 385;
rocp2= 765;
kf=0.613;
k1=401;
k2=40
sigmaf=0.05;
sigma1=5.96*10^7;
sigma2=3.69*10^7;
A1=(phi2*rocp2)/rocpf+ (1-phi2)*((1-phi1)+(rocp1*phi1)/rocpf);
A2=((1-phi2)*((1-phi1)+(ro1*phi1)/rof)+(ro2*phi2)/rof);
A= ((sigma1*(1-2*(phi1)) + 2*sigmaf*(1-phi1))/(sigma1*(1-phi1) + 2*sigmaf*(1+phi1))); %sigmaf
A3=((sigma2*(1+2*(phi2))+2*(1-phi2)*A)/(sigma2*(1-phi2)+(2+phi2)*A))*A;
%A3=((sigma2+2*(1-phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))+2*phi2*sigma2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1)))/(sigma2+2*(1+phi2)*(sigma1 + 2*sigmaf – 2*phi1*(sigmaf – sigma1)) * sigmaf / (sigma1 + 2*sigmaf + phi1 * (sigmaf – sigma1))-phi2*sigma2);
A4=((1-phi1)^-2.5)*((1-phi2)^-2.5); %meuf
A5=(((2 * (1 + phi1) * (2 * kf – 2 * phi2 * (k2 – kf) + k2)) / (2 * kf + phi2 * (k2 – kf) + k2) + ((1 – 2 * phi1) * k1) / kf) / (2 – phi1)) * ((2 * kf – 2 * phi2 * (k2 – kf) + k2) / (2 * kf + phi2 * (k2 – kf) + k2)) + ((1 + phi1) * k1) / kf;
infinity=1;
solinit = bvpinit(linspace(0,infinity,20),zeros(5,1));
options=bvpset(‘Stats’,’on’,’RelTol’,1e-6);
lines={‘k’,’r’,’g’,’m’,’k–‘,’r–‘,’g–‘,’b–‘,’y’,’m’,’k’,’b’};
Ha=0.1;
sol1 = bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.3;
sol2 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.5;
sol3 =bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
Ha=0.7;
sol4= bvp4c(@williamode,@williambc,solinit,options,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2);
figure(1);
plot(sol1.x,sol1.y(1,:),lines{1},sol2.x,sol2.y(1,:),lines{2},sol3.x,sol3.y(1,:),lines{3},sol4.x,sol4.y(1,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘eta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
figure(2);
plot(sol1.x,sol1.y(4,:),lines{1},sol2.x,sol2.y(4,:),lines{2},sol3.x,sol3.y(4,:),lines{3},sol4.x,sol4.y(4,:),lines{4},’LineWidth’,3,’MarkerSize’,16,’linestyle’,’-‘);
xlabel(‘zeta’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
ylabel(‘kappa’,’Interpreter’,’tex’,’FontSize’,16,’FontWeight’,’bold’);
grid on
hold on
y1 = sol1.y;
y2 = sol2.y;
function dydx = williamode(x,y,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,rof,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
dydx =zeros(5,1);
dydx = [y(2)
y(3)
%-(sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) / (sqrt((2*y(1)*angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2))) * (2 * angle_degrees * Re * A2 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * y(1) * y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+(w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2)*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3))+(1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2)));
-(sqrt((2*y(1)*angle_degrees)^2+y(2)^2)/((sqrt((2*y(1)*angle_degrees)^2+y(2)^2))+w*(2*y(2)^2+4*y(1)^2*angle_degrees^2)))*(2*angle_degrees*Re*A2*(1-phi1)^2.5*(1-phi2)^2.5*y(1)*y(2)+(4-A3*(1-phi1)^2.5*(1-phi2)^2.5*(Ha)^2)*y(2)*angle_degrees^2+((w*(sqrt(2*y(1)*angle_degrees)^2+y(2)^2))*((16*y(1)^3*angle_degrees^4*+8*y(1)*y(2)^2*angle_degrees^2+2*y(2)^2*y(3)+4*y(1)^2*y(3)*angle_degrees^2)/(4*y(1)*y(2)*angle_degrees^2+y(2)*y(3)))+((1/((2*y(1)*angle_degrees)^2*+y(2)^2))*(80*y(1)^2*y(2)*angle_degrees^4+32*y(1)*y(2)*y(3)*angle_degrees^2+8*y(2)^3*angle_degrees^2+4*y(2)*y(3)^2))))
%-(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) /(sqrt((2 * y(1) * angle_degrees)^2 + y(2)^2) + w * (2 * y(2)^2 + 4 * y(1)^2 * angle_degrees^2)))*(2*angle_degrees *Re*A2*(1 – phi1)^2.5*(1 – phi2)^2.5 * y(1) * y(2) +(4 – A3 * (1 – phi1)^2.5 * (1 – phi2)^2.5 * (Ha)^2) * y(2) * angle_degrees^2 +((w * (sqrt(2 * y(1) * angle_degrees)^2 + y(2)^2)) *((16 * y(1)^3 * angle_degrees^4 + 8 * y(1) * y(2)^2 * angle_degrees^2 + 2 * y(2)^2 * y(3) +4 * y(1)^2 * y(3) * angle_degrees^2) /(4 * y(1) * y(2) * angle_degrees^2 + y(2) * y(3)) +((1 / ((2 * y(1) * angle_degrees)^2 + y(2)^2)) *(80 * y(1)^2 * y(2) * angle_degrees^4 + 32 * y(1) * y(2) * y(3) * angle_degrees^2+8 * y(2)^3 * angle_degrees^2 + 4 * y(2) * y(3)^2)));
y(5)
(-1/A5)*((E*Pr*A1)/(1-phi1)^2.5*(1-phi2)^2.5)*((4*y(1)^2*angle_degrees^2+y(2)^2)+w*((4*y(1)^2*angle_degrees^2+y(2)^2)^3/2))]
end
function res = williambc(ya,yb,w,Ha,Re,angle_degrees,E,Pr,phi1,phi2,~,ro1,ro2,rocpf,rocp1,rocp2,kf,k1,k2,sigmaf,sigma1,sigma2)
res =[ya(1)-1;
ya(2);
ya(5);
yb(1);
yb(4)-1;];
hold on
end
grid on
end remove singular jacobin error MATLAB Answers — New Questions
Are the full models available for vehicle dynamic blocks?
I’m trying to use the blocks in the Vehicle Dynamics Blockset, but there’s not quite enough in the documentation for me to understand the full model being used for various blocks.
For example, in the Vehicle Body 3 DOF block, I’m trying to derive complete equations of motion from the documentation, but the documentation only seems to include information on the forces and some accelerations.
It would be very nice if there was clear information available describing how the vehicle’s position and orientation changes with each time step, or how yaw rate is calculated. I tried looking under the mask of the block to see if this would provide any more information, but it seems like the underlying code is protected.
In short, I’m looking for a clearer understanding of how the outputs are calculated from the inputs, but the documentation doesn’t really organize the equations this way, and it seems like some helpful information is left out.
Is there any more information available for these models?I’m trying to use the blocks in the Vehicle Dynamics Blockset, but there’s not quite enough in the documentation for me to understand the full model being used for various blocks.
For example, in the Vehicle Body 3 DOF block, I’m trying to derive complete equations of motion from the documentation, but the documentation only seems to include information on the forces and some accelerations.
It would be very nice if there was clear information available describing how the vehicle’s position and orientation changes with each time step, or how yaw rate is calculated. I tried looking under the mask of the block to see if this would provide any more information, but it seems like the underlying code is protected.
In short, I’m looking for a clearer understanding of how the outputs are calculated from the inputs, but the documentation doesn’t really organize the equations this way, and it seems like some helpful information is left out.
Is there any more information available for these models? I’m trying to use the blocks in the Vehicle Dynamics Blockset, but there’s not quite enough in the documentation for me to understand the full model being used for various blocks.
For example, in the Vehicle Body 3 DOF block, I’m trying to derive complete equations of motion from the documentation, but the documentation only seems to include information on the forces and some accelerations.
It would be very nice if there was clear information available describing how the vehicle’s position and orientation changes with each time step, or how yaw rate is calculated. I tried looking under the mask of the block to see if this would provide any more information, but it seems like the underlying code is protected.
In short, I’m looking for a clearer understanding of how the outputs are calculated from the inputs, but the documentation doesn’t really organize the equations this way, and it seems like some helpful information is left out.
Is there any more information available for these models? simulink, vehicle dynamics MATLAB Answers — New Questions
Simulating salient pole synchronous generator runaway condition
Hello, I want to examine the runaway condition for a salient pole synchronous generator. For this, I want to remove the load while the synchronous generator is operating at full load and find the acceleration graph of the rotor and the maximum speed it will reach. How can I design this system? generator values: 850 kVA 400V 6 poleHello, I want to examine the runaway condition for a salient pole synchronous generator. For this, I want to remove the load while the synchronous generator is operating at full load and find the acceleration graph of the rotor and the maximum speed it will reach. How can I design this system? generator values: 850 kVA 400V 6 pole Hello, I want to examine the runaway condition for a salient pole synchronous generator. For this, I want to remove the load while the synchronous generator is operating at full load and find the acceleration graph of the rotor and the maximum speed it will reach. How can I design this system? generator values: 850 kVA 400V 6 pole runaway, simulink, synchronous generator MATLAB Answers — New Questions
Multioutput Regression models for non-linear data
Resistance or capacitance (with voltage) and its frequency range as input and my target or to be predicted is magnitude and phase. As u now magnitude and phase are interdependent data it needs to be predicted together. Most of the regression algorithm is failing to capture the interdependency between magnitude and phase.
Please can u suggest a algorithm which best fit this application/Resistance or capacitance (with voltage) and its frequency range as input and my target or to be predicted is magnitude and phase. As u now magnitude and phase are interdependent data it needs to be predicted together. Most of the regression algorithm is failing to capture the interdependency between magnitude and phase.
Please can u suggest a algorithm which best fit this application/ Resistance or capacitance (with voltage) and its frequency range as input and my target or to be predicted is magnitude and phase. As u now magnitude and phase are interdependent data it needs to be predicted together. Most of the regression algorithm is failing to capture the interdependency between magnitude and phase.
Please can u suggest a algorithm which best fit this application/ non-linear, multioutput, regression MATLAB Answers — New Questions
Code Generation for Delay block generates continuous if statement for loading initial value
Hello, I have the following model:
it is a delay block with that should use the input at the first time step as the value.
In the generated code I see that in the initialize function it is setting "untitled_DW.icLoad = true" such that it loads the value on the first execution. However this generates an if statement that only needs to be checked at the 1st iteration, is it possible to have this load statement in the initialize function such that it is removed from the step the function?
/* Model step function */
void untitled_step(void)
{
/* Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
if (untitled_DW.icLoad) {
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Outport: ‘<Root>/Out’ incorporates:
* Delay: ‘<Root>/Delay’
*/
untitled_Y.Out = untitled_DW.Delay_DSTATE;
/* Update for Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
untitled_DW.icLoad = false;
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Model initialize function */
void untitled_initialize(void)
{
/* InitializeConditions for Delay: ‘<Root>/Delay’ */
untitled_DW.icLoad = true;
}Hello, I have the following model:
it is a delay block with that should use the input at the first time step as the value.
In the generated code I see that in the initialize function it is setting "untitled_DW.icLoad = true" such that it loads the value on the first execution. However this generates an if statement that only needs to be checked at the 1st iteration, is it possible to have this load statement in the initialize function such that it is removed from the step the function?
/* Model step function */
void untitled_step(void)
{
/* Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
if (untitled_DW.icLoad) {
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Outport: ‘<Root>/Out’ incorporates:
* Delay: ‘<Root>/Delay’
*/
untitled_Y.Out = untitled_DW.Delay_DSTATE;
/* Update for Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
untitled_DW.icLoad = false;
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Model initialize function */
void untitled_initialize(void)
{
/* InitializeConditions for Delay: ‘<Root>/Delay’ */
untitled_DW.icLoad = true;
} Hello, I have the following model:
it is a delay block with that should use the input at the first time step as the value.
In the generated code I see that in the initialize function it is setting "untitled_DW.icLoad = true" such that it loads the value on the first execution. However this generates an if statement that only needs to be checked at the 1st iteration, is it possible to have this load statement in the initialize function such that it is removed from the step the function?
/* Model step function */
void untitled_step(void)
{
/* Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
if (untitled_DW.icLoad) {
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Outport: ‘<Root>/Out’ incorporates:
* Delay: ‘<Root>/Delay’
*/
untitled_Y.Out = untitled_DW.Delay_DSTATE;
/* Update for Delay: ‘<Root>/Delay’ incorporates:
* Inport: ‘<Root>/Input’
*/
untitled_DW.icLoad = false;
untitled_DW.Delay_DSTATE = untitled_U.Input;
}
/* Model initialize function */
void untitled_initialize(void)
{
/* InitializeConditions for Delay: ‘<Root>/Delay’ */
untitled_DW.icLoad = true;
} embedded coder, delay block MATLAB Answers — New Questions
Publishing /diagnostics ros2 Topic in Simulink
Hello,
I am trying to publish a ROS2 diagnostics topic in Simulink. The topic uses the DiagnosticArray message type, which makes it difficult to use the Bus Assignment block. To address this, I created a custom function for the task. Here is the function I implemented:
function msg = assignNestedArrayMessages(blankMessage)
blankMessage.status_SL_Info.CurrentLength = uint32(2);
blankMessage.status(1).level = uint8(1);
blankMessage.status(2).level = uint8(2);
blankMessage.header.stamp.sec = int32(1);
msg =blankMessage;
end
However, despite the simplicity of the function, I encountered the following error:
One or more signal names in the input bus to block ‘pp/pub_diagnostics/SignalSpecification’ does not match the signal names in the bus specified by the bus object ‘SL_Bus_diagnostic_msgs_DiagnosticArray’ on the block dialog. Signal Specification blocks always treat element name mismatches as errors, regardless of the ‘Element name mismatch’ option setting. Either change the specified bus object or rename the input bus element signals to match the bus object.
I would appreciate it if you could provide guidance on how to resolve this issue.Hello,
I am trying to publish a ROS2 diagnostics topic in Simulink. The topic uses the DiagnosticArray message type, which makes it difficult to use the Bus Assignment block. To address this, I created a custom function for the task. Here is the function I implemented:
function msg = assignNestedArrayMessages(blankMessage)
blankMessage.status_SL_Info.CurrentLength = uint32(2);
blankMessage.status(1).level = uint8(1);
blankMessage.status(2).level = uint8(2);
blankMessage.header.stamp.sec = int32(1);
msg =blankMessage;
end
However, despite the simplicity of the function, I encountered the following error:
One or more signal names in the input bus to block ‘pp/pub_diagnostics/SignalSpecification’ does not match the signal names in the bus specified by the bus object ‘SL_Bus_diagnostic_msgs_DiagnosticArray’ on the block dialog. Signal Specification blocks always treat element name mismatches as errors, regardless of the ‘Element name mismatch’ option setting. Either change the specified bus object or rename the input bus element signals to match the bus object.
I would appreciate it if you could provide guidance on how to resolve this issue. Hello,
I am trying to publish a ROS2 diagnostics topic in Simulink. The topic uses the DiagnosticArray message type, which makes it difficult to use the Bus Assignment block. To address this, I created a custom function for the task. Here is the function I implemented:
function msg = assignNestedArrayMessages(blankMessage)
blankMessage.status_SL_Info.CurrentLength = uint32(2);
blankMessage.status(1).level = uint8(1);
blankMessage.status(2).level = uint8(2);
blankMessage.header.stamp.sec = int32(1);
msg =blankMessage;
end
However, despite the simplicity of the function, I encountered the following error:
One or more signal names in the input bus to block ‘pp/pub_diagnostics/SignalSpecification’ does not match the signal names in the bus specified by the bus object ‘SL_Bus_diagnostic_msgs_DiagnosticArray’ on the block dialog. Signal Specification blocks always treat element name mismatches as errors, regardless of the ‘Element name mismatch’ option setting. Either change the specified bus object or rename the input bus element signals to match the bus object.
I would appreciate it if you could provide guidance on how to resolve this issue. ros2, diagnostics MATLAB Answers — New Questions
trying perform an image classification using RL but facing error, Any suggestion?
clc;
%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);
% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);
%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;
% Feature extraction layer
featureLayer = ‘fc7’;
% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);
% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);
% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);
%% RL Environment Setup
% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);
ObservationInfo.Description = ‘Feature vector extracted from CNN’;
% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;
% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);
% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);
%% Define RL Agent
% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions
criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);
% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);
agent = rlDQNAgent(critic, agentOpts);
%% Train RL Agent
trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);
trainingStats = train(agent, env);
%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.
% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();
% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;
% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector
% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end
% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end
%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;
% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end
% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);
% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR
Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.
Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);
Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:});clc;
%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);
% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);
%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;
% Feature extraction layer
featureLayer = ‘fc7’;
% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);
% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);
% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);
%% RL Environment Setup
% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);
ObservationInfo.Description = ‘Feature vector extracted from CNN’;
% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;
% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);
% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);
%% Define RL Agent
% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions
criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);
% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);
agent = rlDQNAgent(critic, agentOpts);
%% Train RL Agent
trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);
trainingStats = train(agent, env);
%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.
% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();
% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;
% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector
% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end
% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end
%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;
% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end
% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);
% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR
Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.
Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);
Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:}); clc;
%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);
% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);
% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);
%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;
% Feature extraction layer
featureLayer = ‘fc7’;
% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);
% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);
% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);
%% RL Environment Setup
% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);
ObservationInfo.Description = ‘Feature vector extracted from CNN’;
% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;
% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);
% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);
%% Define RL Agent
% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions
criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);
% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);
agent = rlDQNAgent(critic, agentOpts);
%% Train RL Agent
trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);
trainingStats = train(agent, env);
%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.
% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();
% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;
% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector
% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end
% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end
%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;
% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end
% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);
% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR
Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.
Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);
Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:}); rl, image-classification MATLAB Answers — New Questions
error in testing matpower
hi everyone, I want to install matpower 6.0 in my matlab 2019b but after I install it same as instruction I get errors in testing it.
when I write test_matpower in command window I recieve these errors.
please help me to install it successfully.
>> test_matpower
t_test_fcns………….ok
t_nested_struct_copy….ok
t_feval_w_path……….ok
t_mpoption…………..ok
t_loadcase…………..Error using save
Unable to write file t_mat9_opf.mat:
permission denied.
Error in t_loadcase (line 40)
eval([‘save ‘ matfile ‘.mat baseMVA bus
gen branch areas gencost’]);
Error in t_run_tests (line 58)
feval( test_names{k}, ~verbose );
Error in test_matpower (line 128)
t_run_tests( tests, verbose );hi everyone, I want to install matpower 6.0 in my matlab 2019b but after I install it same as instruction I get errors in testing it.
when I write test_matpower in command window I recieve these errors.
please help me to install it successfully.
>> test_matpower
t_test_fcns………….ok
t_nested_struct_copy….ok
t_feval_w_path……….ok
t_mpoption…………..ok
t_loadcase…………..Error using save
Unable to write file t_mat9_opf.mat:
permission denied.
Error in t_loadcase (line 40)
eval([‘save ‘ matfile ‘.mat baseMVA bus
gen branch areas gencost’]);
Error in t_run_tests (line 58)
feval( test_names{k}, ~verbose );
Error in test_matpower (line 128)
t_run_tests( tests, verbose ); hi everyone, I want to install matpower 6.0 in my matlab 2019b but after I install it same as instruction I get errors in testing it.
when I write test_matpower in command window I recieve these errors.
please help me to install it successfully.
>> test_matpower
t_test_fcns………….ok
t_nested_struct_copy….ok
t_feval_w_path……….ok
t_mpoption…………..ok
t_loadcase…………..Error using save
Unable to write file t_mat9_opf.mat:
permission denied.
Error in t_loadcase (line 40)
eval([‘save ‘ matfile ‘.mat baseMVA bus
gen branch areas gencost’]);
Error in t_run_tests (line 58)
feval( test_names{k}, ~verbose );
Error in test_matpower (line 128)
t_run_tests( tests, verbose ); matpower MATLAB Answers — New Questions
how to identify the cracks from the image
<</matlabcentral/answers/uploaded_files/129987/el2.jpg>><</matlabcentral/answers/uploaded_files/129987/el2.jpg>> <</matlabcentral/answers/uploaded_files/129987/el2.jpg>> ir image, cracks, image segmentation, tiles MATLAB Answers — New Questions
Crack Detection
I have problem for detection for surface ceramics image, how i can detect crack surface , pls give me some advice. this my code for detect crack surface
function [img1_array, img2_array,img3_array, img4_array,Zme]= DefectScan(input_path,input_path2);
% clear all;
% close all;
I = imread(input_path2);
J = imread(input_path);
I = rgb2gray(I);
J = rgb2gray(J);
% f=figure,imshow(I);
% g=figure,imshow(J);
hy = fspecial(‘sobel’);
hx = hy’;
Iy = imfilter(double(I), hy, ‘replicate’);
Ix = imfilter(double(I), hx, ‘replicate’);
ey = fspecial(‘sobel’);
fx = ey’;
Jy = imfilter(double(J), ey, ‘replicate’);
Jx = imfilter(double(J), fx, ‘replicate’);
gradmag = sqrt(Ix.^2 + Iy.^2);
gradmag2 = sqrt(Jx.^2 + Jy.^2);
K=figure,imshow(gradmag,[]);
L=figure,imshow(gradmag2,[]);
set(K, ‘visible’,’off’);
set(L, ‘visible’,’off’);
filename = ‘temp_file.jpg’
filename2 = ‘temp_file2.jpg’
saveas(K, filename)
saveas(L, filename2)
i1 = imread(filename)
i2 = imread(filename2)
delete(filename)
delete(filename2)
[x, y, rgb] = ind2sub([size(i1,1) size(i1,2) size(i1,3)], find(i1 ~= 255));
A = i1(min(x):max(x)-1,min(y):max(y)-1,:);
[x, y, rgb] = ind2sub([size(i2,1) size(i2,2) size(i2,3)], find(i2 ~= 255));
B = i2(min(x):max(x)-1,min(y):max(y)-1,:);
A = rgb2gray(A)
B = rgb2gray(B)
I = edge(A,’sobel’)
J = edge(B,’sobel’)I have problem for detection for surface ceramics image, how i can detect crack surface , pls give me some advice. this my code for detect crack surface
function [img1_array, img2_array,img3_array, img4_array,Zme]= DefectScan(input_path,input_path2);
% clear all;
% close all;
I = imread(input_path2);
J = imread(input_path);
I = rgb2gray(I);
J = rgb2gray(J);
% f=figure,imshow(I);
% g=figure,imshow(J);
hy = fspecial(‘sobel’);
hx = hy’;
Iy = imfilter(double(I), hy, ‘replicate’);
Ix = imfilter(double(I), hx, ‘replicate’);
ey = fspecial(‘sobel’);
fx = ey’;
Jy = imfilter(double(J), ey, ‘replicate’);
Jx = imfilter(double(J), fx, ‘replicate’);
gradmag = sqrt(Ix.^2 + Iy.^2);
gradmag2 = sqrt(Jx.^2 + Jy.^2);
K=figure,imshow(gradmag,[]);
L=figure,imshow(gradmag2,[]);
set(K, ‘visible’,’off’);
set(L, ‘visible’,’off’);
filename = ‘temp_file.jpg’
filename2 = ‘temp_file2.jpg’
saveas(K, filename)
saveas(L, filename2)
i1 = imread(filename)
i2 = imread(filename2)
delete(filename)
delete(filename2)
[x, y, rgb] = ind2sub([size(i1,1) size(i1,2) size(i1,3)], find(i1 ~= 255));
A = i1(min(x):max(x)-1,min(y):max(y)-1,:);
[x, y, rgb] = ind2sub([size(i2,1) size(i2,2) size(i2,3)], find(i2 ~= 255));
B = i2(min(x):max(x)-1,min(y):max(y)-1,:);
A = rgb2gray(A)
B = rgb2gray(B)
I = edge(A,’sobel’)
J = edge(B,’sobel’) I have problem for detection for surface ceramics image, how i can detect crack surface , pls give me some advice. this my code for detect crack surface
function [img1_array, img2_array,img3_array, img4_array,Zme]= DefectScan(input_path,input_path2);
% clear all;
% close all;
I = imread(input_path2);
J = imread(input_path);
I = rgb2gray(I);
J = rgb2gray(J);
% f=figure,imshow(I);
% g=figure,imshow(J);
hy = fspecial(‘sobel’);
hx = hy’;
Iy = imfilter(double(I), hy, ‘replicate’);
Ix = imfilter(double(I), hx, ‘replicate’);
ey = fspecial(‘sobel’);
fx = ey’;
Jy = imfilter(double(J), ey, ‘replicate’);
Jx = imfilter(double(J), fx, ‘replicate’);
gradmag = sqrt(Ix.^2 + Iy.^2);
gradmag2 = sqrt(Jx.^2 + Jy.^2);
K=figure,imshow(gradmag,[]);
L=figure,imshow(gradmag2,[]);
set(K, ‘visible’,’off’);
set(L, ‘visible’,’off’);
filename = ‘temp_file.jpg’
filename2 = ‘temp_file2.jpg’
saveas(K, filename)
saveas(L, filename2)
i1 = imread(filename)
i2 = imread(filename2)
delete(filename)
delete(filename2)
[x, y, rgb] = ind2sub([size(i1,1) size(i1,2) size(i1,3)], find(i1 ~= 255));
A = i1(min(x):max(x)-1,min(y):max(y)-1,:);
[x, y, rgb] = ind2sub([size(i2,1) size(i2,2) size(i2,3)], find(i2 ~= 255));
B = i2(min(x):max(x)-1,min(y):max(y)-1,:);
A = rgb2gray(A)
B = rgb2gray(B)
I = edge(A,’sobel’)
J = edge(B,’sobel’) detection crack surface, doit4me, sendit2me MATLAB Answers — New Questions
Crack detection on concrete
Hi, i have problem in measuring the length and width the crack image.
i have follow the code but it only measure straight line (endpoint). I want the measurement by following the crack pattern. Please help me on this.
%load image
path=imgetfile();
originalImage1=imread(path);
imshow(originalImage1);
%image to grayscale
originalImage = rgb2gray(originalImage1);
figure
imshow(originalImage);
%treshold
thresholdValue = 100;
binaryImage = originalImage > thresholdValue;
binaryImage = imfill(binaryImage, ‘holes’);
hold on;
% maxYValue = ylim;
% line([thresholdValue, thresholdValue], maxYValue, ‘Color’, ‘r’);
% annotationText = sprintf(‘Thresholded at %d gray levels’, thresholdValue);
% text(double(thresholdValue + 5), double(0.5 * maxYValue(2)), annotationText, ‘FontSize’, 10, ‘Color’, [0 .5 0]);
% text(double(thresholdValue – 70), double(0.94 * maxYValue(2)), ‘Background’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
% text(double(thresholdValue + 50), double(0.94 * maxYValue(2)), ‘Foreground’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
figure
imshow(binaryImage);
% bw = bwareaopen(binaryImage,100,8);
bw= bwareaopen(binaryImage, round(0.1*numel(binaryImage)));
figure
imshow(bw)
g=bwmorph(bw,’clean’);
figure
imshow(g);
% %labeled image (on hold)
labeledImage = bwlabel(g,4);
figure
imshow(labeledImage, []);
%colored label image
coloredLabels = label2rgb (labeledImage, ‘hsv’, ‘k’, ‘shuffle’);
figure
imshow(coloredLabels);
axis image;
%blobmeasurement
blobMeasurements = regionprops(labeledImage, originalImage, ‘all’);
numberOfBlobs = size(blobMeasurements, 1);
figure
imshow(originalImage);
axis image; % Make sure image is not artificially stretched because of screen’s aspect ratio.
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), ‘g’, ‘LineWidth’, 2);
end
hold off;
% Measure the area
measurements = regionprops(labeledImage, ‘Area’);
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for blobIndex = 1 : numberOfBoundaries
thisBoundary = boundaries{blobIndex};
x = thisBoundary(:, 2); % x = columns.
y = thisBoundary(:, 1); % y = rows.
% Find which two bounary points are farthest from each other.
maxDistance = -inf;
for k = 1 : length(x)
distances = sqrt( (x(k) – x) .^ 2 + (y(k) – y) .^ 2 );
[thisMaxDistance, indexOfMaxDistance] = max(distances);
if thisMaxDistance > maxDistance
maxDistance = thisMaxDistance;
index1 = k;
index2 = indexOfMaxDistance;
end
end
% Find the midpoint of the line.
xMidPoint = mean([x(index1), x(index2)]);
yMidPoint = mean([y(index1), y(index2)]);
longSlope = (y(index1) – y(index2)) / (x(index1) – x(index2))
perpendicularSlope = -1/longSlope
% Use point slope formula (y-ym) = slope * (x – xm) to get points
y1 = perpendicularSlope * (1 – xMidPoint) + yMidPoint;
y2 = perpendicularSlope * (columns – xMidPoint) + yMidPoint;
% Get the profile perpendicular to the midpoint so we can find out when if first enters and last leaves the object.
[cx,cy,c] = improfile(binaryImage,[1, columns], [y1, y2], 1000);
% Get rid of NAN’s that occur when the line’s endpoints go above or below the image.
c(isnan(c)) = 0;
firstIndex = find(c, 1, ‘first’);
lastIndex = find(c, 1, ‘last’);
% Compute the distance of that perpendicular width.
perpendicularWidth = sqrt( (cx(firstIndex) – cx(lastIndex)) .^ 2 + (cy(firstIndex) – cy(lastIndex)) .^ 2 );
% Get the average perpendicular width. This will approximately be the area divided by the longest length.
averageWidth = measurements(blobIndex).Area / maxDistance;
% Plot the boundaries, line, and midpoints over the two images.
% Plot the boundary over the gray scale image
subplot(2, 2, 3);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
% Plot the boundary over the binary image
subplot(2, 2, 4);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
message = sprintf(‘The longest line is red.nPerpendicular to that, at the midpoint, is green.nMax distance for blob #%d = %.2fnPerpendicular distance at midpoint = %.2fnAverage perpendicular width = %.2f (approximatelynArea = %d’, …
blobIndex, maxDistance, perpendicularWidth, averageWidth, measurements(blobIndex).Area);
fprintf(‘%sn’, message);
uiwait(helpdlg(message));
end
hold off;Hi, i have problem in measuring the length and width the crack image.
i have follow the code but it only measure straight line (endpoint). I want the measurement by following the crack pattern. Please help me on this.
%load image
path=imgetfile();
originalImage1=imread(path);
imshow(originalImage1);
%image to grayscale
originalImage = rgb2gray(originalImage1);
figure
imshow(originalImage);
%treshold
thresholdValue = 100;
binaryImage = originalImage > thresholdValue;
binaryImage = imfill(binaryImage, ‘holes’);
hold on;
% maxYValue = ylim;
% line([thresholdValue, thresholdValue], maxYValue, ‘Color’, ‘r’);
% annotationText = sprintf(‘Thresholded at %d gray levels’, thresholdValue);
% text(double(thresholdValue + 5), double(0.5 * maxYValue(2)), annotationText, ‘FontSize’, 10, ‘Color’, [0 .5 0]);
% text(double(thresholdValue – 70), double(0.94 * maxYValue(2)), ‘Background’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
% text(double(thresholdValue + 50), double(0.94 * maxYValue(2)), ‘Foreground’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
figure
imshow(binaryImage);
% bw = bwareaopen(binaryImage,100,8);
bw= bwareaopen(binaryImage, round(0.1*numel(binaryImage)));
figure
imshow(bw)
g=bwmorph(bw,’clean’);
figure
imshow(g);
% %labeled image (on hold)
labeledImage = bwlabel(g,4);
figure
imshow(labeledImage, []);
%colored label image
coloredLabels = label2rgb (labeledImage, ‘hsv’, ‘k’, ‘shuffle’);
figure
imshow(coloredLabels);
axis image;
%blobmeasurement
blobMeasurements = regionprops(labeledImage, originalImage, ‘all’);
numberOfBlobs = size(blobMeasurements, 1);
figure
imshow(originalImage);
axis image; % Make sure image is not artificially stretched because of screen’s aspect ratio.
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), ‘g’, ‘LineWidth’, 2);
end
hold off;
% Measure the area
measurements = regionprops(labeledImage, ‘Area’);
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for blobIndex = 1 : numberOfBoundaries
thisBoundary = boundaries{blobIndex};
x = thisBoundary(:, 2); % x = columns.
y = thisBoundary(:, 1); % y = rows.
% Find which two bounary points are farthest from each other.
maxDistance = -inf;
for k = 1 : length(x)
distances = sqrt( (x(k) – x) .^ 2 + (y(k) – y) .^ 2 );
[thisMaxDistance, indexOfMaxDistance] = max(distances);
if thisMaxDistance > maxDistance
maxDistance = thisMaxDistance;
index1 = k;
index2 = indexOfMaxDistance;
end
end
% Find the midpoint of the line.
xMidPoint = mean([x(index1), x(index2)]);
yMidPoint = mean([y(index1), y(index2)]);
longSlope = (y(index1) – y(index2)) / (x(index1) – x(index2))
perpendicularSlope = -1/longSlope
% Use point slope formula (y-ym) = slope * (x – xm) to get points
y1 = perpendicularSlope * (1 – xMidPoint) + yMidPoint;
y2 = perpendicularSlope * (columns – xMidPoint) + yMidPoint;
% Get the profile perpendicular to the midpoint so we can find out when if first enters and last leaves the object.
[cx,cy,c] = improfile(binaryImage,[1, columns], [y1, y2], 1000);
% Get rid of NAN’s that occur when the line’s endpoints go above or below the image.
c(isnan(c)) = 0;
firstIndex = find(c, 1, ‘first’);
lastIndex = find(c, 1, ‘last’);
% Compute the distance of that perpendicular width.
perpendicularWidth = sqrt( (cx(firstIndex) – cx(lastIndex)) .^ 2 + (cy(firstIndex) – cy(lastIndex)) .^ 2 );
% Get the average perpendicular width. This will approximately be the area divided by the longest length.
averageWidth = measurements(blobIndex).Area / maxDistance;
% Plot the boundaries, line, and midpoints over the two images.
% Plot the boundary over the gray scale image
subplot(2, 2, 3);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
% Plot the boundary over the binary image
subplot(2, 2, 4);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
message = sprintf(‘The longest line is red.nPerpendicular to that, at the midpoint, is green.nMax distance for blob #%d = %.2fnPerpendicular distance at midpoint = %.2fnAverage perpendicular width = %.2f (approximatelynArea = %d’, …
blobIndex, maxDistance, perpendicularWidth, averageWidth, measurements(blobIndex).Area);
fprintf(‘%sn’, message);
uiwait(helpdlg(message));
end
hold off; Hi, i have problem in measuring the length and width the crack image.
i have follow the code but it only measure straight line (endpoint). I want the measurement by following the crack pattern. Please help me on this.
%load image
path=imgetfile();
originalImage1=imread(path);
imshow(originalImage1);
%image to grayscale
originalImage = rgb2gray(originalImage1);
figure
imshow(originalImage);
%treshold
thresholdValue = 100;
binaryImage = originalImage > thresholdValue;
binaryImage = imfill(binaryImage, ‘holes’);
hold on;
% maxYValue = ylim;
% line([thresholdValue, thresholdValue], maxYValue, ‘Color’, ‘r’);
% annotationText = sprintf(‘Thresholded at %d gray levels’, thresholdValue);
% text(double(thresholdValue + 5), double(0.5 * maxYValue(2)), annotationText, ‘FontSize’, 10, ‘Color’, [0 .5 0]);
% text(double(thresholdValue – 70), double(0.94 * maxYValue(2)), ‘Background’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
% text(double(thresholdValue + 50), double(0.94 * maxYValue(2)), ‘Foreground’, ‘FontSize’, 10, ‘Color’, [0 0 .5]);
figure
imshow(binaryImage);
% bw = bwareaopen(binaryImage,100,8);
bw= bwareaopen(binaryImage, round(0.1*numel(binaryImage)));
figure
imshow(bw)
g=bwmorph(bw,’clean’);
figure
imshow(g);
% %labeled image (on hold)
labeledImage = bwlabel(g,4);
figure
imshow(labeledImage, []);
%colored label image
coloredLabels = label2rgb (labeledImage, ‘hsv’, ‘k’, ‘shuffle’);
figure
imshow(coloredLabels);
axis image;
%blobmeasurement
blobMeasurements = regionprops(labeledImage, originalImage, ‘all’);
numberOfBlobs = size(blobMeasurements, 1);
figure
imshow(originalImage);
axis image; % Make sure image is not artificially stretched because of screen’s aspect ratio.
hold on;
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for k = 1 : numberOfBoundaries
thisBoundary = boundaries{k};
plot(thisBoundary(:,2), thisBoundary(:,1), ‘g’, ‘LineWidth’, 2);
end
hold off;
% Measure the area
measurements = regionprops(labeledImage, ‘Area’);
boundaries = bwboundaries(binaryImage);
numberOfBoundaries = size(boundaries, 1);
for blobIndex = 1 : numberOfBoundaries
thisBoundary = boundaries{blobIndex};
x = thisBoundary(:, 2); % x = columns.
y = thisBoundary(:, 1); % y = rows.
% Find which two bounary points are farthest from each other.
maxDistance = -inf;
for k = 1 : length(x)
distances = sqrt( (x(k) – x) .^ 2 + (y(k) – y) .^ 2 );
[thisMaxDistance, indexOfMaxDistance] = max(distances);
if thisMaxDistance > maxDistance
maxDistance = thisMaxDistance;
index1 = k;
index2 = indexOfMaxDistance;
end
end
% Find the midpoint of the line.
xMidPoint = mean([x(index1), x(index2)]);
yMidPoint = mean([y(index1), y(index2)]);
longSlope = (y(index1) – y(index2)) / (x(index1) – x(index2))
perpendicularSlope = -1/longSlope
% Use point slope formula (y-ym) = slope * (x – xm) to get points
y1 = perpendicularSlope * (1 – xMidPoint) + yMidPoint;
y2 = perpendicularSlope * (columns – xMidPoint) + yMidPoint;
% Get the profile perpendicular to the midpoint so we can find out when if first enters and last leaves the object.
[cx,cy,c] = improfile(binaryImage,[1, columns], [y1, y2], 1000);
% Get rid of NAN’s that occur when the line’s endpoints go above or below the image.
c(isnan(c)) = 0;
firstIndex = find(c, 1, ‘first’);
lastIndex = find(c, 1, ‘last’);
% Compute the distance of that perpendicular width.
perpendicularWidth = sqrt( (cx(firstIndex) – cx(lastIndex)) .^ 2 + (cy(firstIndex) – cy(lastIndex)) .^ 2 );
% Get the average perpendicular width. This will approximately be the area divided by the longest length.
averageWidth = measurements(blobIndex).Area / maxDistance;
% Plot the boundaries, line, and midpoints over the two images.
% Plot the boundary over the gray scale image
subplot(2, 2, 3);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
% Plot the boundary over the binary image
subplot(2, 2, 4);
plot(x, y, ‘y-‘, ‘LineWidth’, 3);
% For this blob, put a line between the points farthest away from each other.
line([x(index1), x(index2)], [y(index1), y(index2)], ‘Color’, ‘r’, ‘LineWidth’, 3);
plot(xMidPoint, yMidPoint, ‘r*’, ‘MarkerSize’, 15, ‘LineWidth’, 2);
% Plot perpendicular line. Make it green across the whole image but magenta inside the blob.
line([1, columns], [y1, y2], ‘Color’, ‘g’, ‘LineWidth’, 3);
line([cx(firstIndex), cx(lastIndex)], [cy(firstIndex), cy(lastIndex)], ‘Color’, ‘m’, ‘LineWidth’, 3);
message = sprintf(‘The longest line is red.nPerpendicular to that, at the midpoint, is green.nMax distance for blob #%d = %.2fnPerpendicular distance at midpoint = %.2fnAverage perpendicular width = %.2f (approximatelynArea = %d’, …
blobIndex, maxDistance, perpendicularWidth, averageWidth, measurements(blobIndex).Area);
fprintf(‘%sn’, message);
uiwait(helpdlg(message));
end
hold off; image processing, crack detection, length, width, regionprops, crack MATLAB Answers — New Questions
How to detect and show the crack in this image and eliminate the rest of the objects (noises)?
I have tried used the morphological structuring element (STREL-line),but there is one problem with my images, the line crack is fixed not only in horizontal and vertical line , it has its degree(0-360), which is this strel-line can’t be used. I used strel-line in order to maintain the line cracks and remove any shapes in the images which is I can’t solve that. I got an idea how to differentiate between the lines and the noises, low gray-level value and high gradient, however this seems not work to this image since the value of gray scale and gradient almost similar to the noises.Can you show me the right way? Attached is the image.I have tried used the morphological structuring element (STREL-line),but there is one problem with my images, the line crack is fixed not only in horizontal and vertical line , it has its degree(0-360), which is this strel-line can’t be used. I used strel-line in order to maintain the line cracks and remove any shapes in the images which is I can’t solve that. I got an idea how to differentiate between the lines and the noises, low gray-level value and high gradient, however this seems not work to this image since the value of gray scale and gradient almost similar to the noises.Can you show me the right way? Attached is the image. I have tried used the morphological structuring element (STREL-line),but there is one problem with my images, the line crack is fixed not only in horizontal and vertical line , it has its degree(0-360), which is this strel-line can’t be used. I used strel-line in order to maintain the line cracks and remove any shapes in the images which is I can’t solve that. I got an idea how to differentiate between the lines and the noises, low gray-level value and high gradient, however this seems not work to this image since the value of gray scale and gradient almost similar to the noises.Can you show me the right way? Attached is the image. image processing, crack detection MATLAB Answers — New Questions