Category: Matlab
Category Archives: Matlab
Control Signal Editor with Simulink Real Time
Hello MathWorks community,
I’m currently working on my Speedgoat RealTime target, and I would like to perform Data Replay, using the block Signal Editor.
My scenario is well configured, and the simulation works pretty well, but currently the data are generated by the Signal Editor as soon the simulation Start. However I need before to wake-up the DUT and let him correctly initialize …
We can imagine to use a Switch bloc with 2 differents bus with the data comming from the Signal Editor, and from the plant model to allow the DUT to correctly init. Unfortunalty, because the Signal Editor is already sending the data, I cannot perform the replay testing as expected.
Is there an option for controlling the Signal Editor (such as start/stop/loop) with Simulink RealTime during the Simulation ?
Thank you for your advice !
RegardsHello MathWorks community,
I’m currently working on my Speedgoat RealTime target, and I would like to perform Data Replay, using the block Signal Editor.
My scenario is well configured, and the simulation works pretty well, but currently the data are generated by the Signal Editor as soon the simulation Start. However I need before to wake-up the DUT and let him correctly initialize …
We can imagine to use a Switch bloc with 2 differents bus with the data comming from the Signal Editor, and from the plant model to allow the DUT to correctly init. Unfortunalty, because the Signal Editor is already sending the data, I cannot perform the replay testing as expected.
Is there an option for controlling the Signal Editor (such as start/stop/loop) with Simulink RealTime during the Simulation ?
Thank you for your advice !
Regards Hello MathWorks community,
I’m currently working on my Speedgoat RealTime target, and I would like to perform Data Replay, using the block Signal Editor.
My scenario is well configured, and the simulation works pretty well, but currently the data are generated by the Signal Editor as soon the simulation Start. However I need before to wake-up the DUT and let him correctly initialize …
We can imagine to use a Switch bloc with 2 differents bus with the data comming from the Signal Editor, and from the plant model to allow the DUT to correctly init. Unfortunalty, because the Signal Editor is already sending the data, I cannot perform the replay testing as expected.
Is there an option for controlling the Signal Editor (such as start/stop/loop) with Simulink RealTime during the Simulation ?
Thank you for your advice !
Regards signal editor, simulink realtime, speedgoat MATLAB Answers — New Questions
Find the combination that maximize the objective function values from the data set.
Hello,
I have a written a small piece of code to find the unique combinations from the excel file which has data from my objective optimzation problem.
The file has six columns other hidden columns are not important. The first column in the green shows the objective value, the second and third column with blue indicates the constraint outputs, and fourth, fifth and sixth column with the yellow represents the combinations that are maximizing my objective function.
I have to choose the maximum (green) value from first column each time in the iteration, which will then select the constraint values (blue) from second and third column, whatever they may be. Additionally, each time, it should select a unique combination (yellow) from fourth fifth and sixth column different from the previous combination that maximized the value. No combination value in column should be repeated like if in first iteration it selected [1 8 1] then in next it should [2 6 2] or [3 7 1] or [4 6 5] but every time based on the maximum value it should have unique combination which is maximizing the objective.
My code snippet is here as I am not able to figure out how to choose unique value in every column.
filename = ‘Objective Optimization MATLAB.xlsx’;
data = readtable(filename);
% Initialize variables
previous_combination = [0 0 0];
% Number of iterations (adjust as needed)
num_iterations = 10;
for i = 1:num_iterations
% Find the maximum objective value
[max_value, max_index] = max(data{:, 1});
% Get the corresponding constraint values and combination
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
% Check if the combination is unique in each column
while ~isempty(previous_combination) && any(combination == previous_combination)
% Remove the current maximum value to find the next one
data{max_index, 1} = -inf;
[max_value, max_index] = max(data{:, 1});
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
end
% Ensure no two column values are identical
while length(unique(combination)) < length(combination)
% Remove the current maximum value to find the next one
data{max_index, 1} = -inf;
[max_value, max_index] = max(data{:, 1});
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
end
% Store the combination to avoid repetition
previous_combination = combination;
% Display the results
fprintf(‘Iteration %d:n’, i);
fprintf(‘Max Objective Value: %fn’, max_value);
fprintf(‘Constraint Value 1: %fn’, constraint_value1);
fprintf(‘Constraint Value 2: %fn’, constraint_value2);
fprintf(‘Combination: %snn’, mat2str(combination));
uniquecombinations(i,:) = combination;
% Remove the current maximum value to find the next one in the next iteration
data{max_index, 1} = -inf;
end
% Getting these combinations
1 8 2
3 7 1
1 3 2
3 6 1
1 2 3
3 5 1
7 8 1
3 2 4
3 1 2
4 8 1
% Since in first column 3 and 1 are repeated
% In 2nd column 8 is repeated
% In 3rd column 2 and 1 are repeated.Hello,
I have a written a small piece of code to find the unique combinations from the excel file which has data from my objective optimzation problem.
The file has six columns other hidden columns are not important. The first column in the green shows the objective value, the second and third column with blue indicates the constraint outputs, and fourth, fifth and sixth column with the yellow represents the combinations that are maximizing my objective function.
I have to choose the maximum (green) value from first column each time in the iteration, which will then select the constraint values (blue) from second and third column, whatever they may be. Additionally, each time, it should select a unique combination (yellow) from fourth fifth and sixth column different from the previous combination that maximized the value. No combination value in column should be repeated like if in first iteration it selected [1 8 1] then in next it should [2 6 2] or [3 7 1] or [4 6 5] but every time based on the maximum value it should have unique combination which is maximizing the objective.
My code snippet is here as I am not able to figure out how to choose unique value in every column.
filename = ‘Objective Optimization MATLAB.xlsx’;
data = readtable(filename);
% Initialize variables
previous_combination = [0 0 0];
% Number of iterations (adjust as needed)
num_iterations = 10;
for i = 1:num_iterations
% Find the maximum objective value
[max_value, max_index] = max(data{:, 1});
% Get the corresponding constraint values and combination
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
% Check if the combination is unique in each column
while ~isempty(previous_combination) && any(combination == previous_combination)
% Remove the current maximum value to find the next one
data{max_index, 1} = -inf;
[max_value, max_index] = max(data{:, 1});
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
end
% Ensure no two column values are identical
while length(unique(combination)) < length(combination)
% Remove the current maximum value to find the next one
data{max_index, 1} = -inf;
[max_value, max_index] = max(data{:, 1});
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
end
% Store the combination to avoid repetition
previous_combination = combination;
% Display the results
fprintf(‘Iteration %d:n’, i);
fprintf(‘Max Objective Value: %fn’, max_value);
fprintf(‘Constraint Value 1: %fn’, constraint_value1);
fprintf(‘Constraint Value 2: %fn’, constraint_value2);
fprintf(‘Combination: %snn’, mat2str(combination));
uniquecombinations(i,:) = combination;
% Remove the current maximum value to find the next one in the next iteration
data{max_index, 1} = -inf;
end
% Getting these combinations
1 8 2
3 7 1
1 3 2
3 6 1
1 2 3
3 5 1
7 8 1
3 2 4
3 1 2
4 8 1
% Since in first column 3 and 1 are repeated
% In 2nd column 8 is repeated
% In 3rd column 2 and 1 are repeated. Hello,
I have a written a small piece of code to find the unique combinations from the excel file which has data from my objective optimzation problem.
The file has six columns other hidden columns are not important. The first column in the green shows the objective value, the second and third column with blue indicates the constraint outputs, and fourth, fifth and sixth column with the yellow represents the combinations that are maximizing my objective function.
I have to choose the maximum (green) value from first column each time in the iteration, which will then select the constraint values (blue) from second and third column, whatever they may be. Additionally, each time, it should select a unique combination (yellow) from fourth fifth and sixth column different from the previous combination that maximized the value. No combination value in column should be repeated like if in first iteration it selected [1 8 1] then in next it should [2 6 2] or [3 7 1] or [4 6 5] but every time based on the maximum value it should have unique combination which is maximizing the objective.
My code snippet is here as I am not able to figure out how to choose unique value in every column.
filename = ‘Objective Optimization MATLAB.xlsx’;
data = readtable(filename);
% Initialize variables
previous_combination = [0 0 0];
% Number of iterations (adjust as needed)
num_iterations = 10;
for i = 1:num_iterations
% Find the maximum objective value
[max_value, max_index] = max(data{:, 1});
% Get the corresponding constraint values and combination
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
% Check if the combination is unique in each column
while ~isempty(previous_combination) && any(combination == previous_combination)
% Remove the current maximum value to find the next one
data{max_index, 1} = -inf;
[max_value, max_index] = max(data{:, 1});
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
end
% Ensure no two column values are identical
while length(unique(combination)) < length(combination)
% Remove the current maximum value to find the next one
data{max_index, 1} = -inf;
[max_value, max_index] = max(data{:, 1});
constraint_value1 = data{max_index, 2};
constraint_value2 = data{max_index, 3};
combination = data{max_index, 4:6};
end
% Store the combination to avoid repetition
previous_combination = combination;
% Display the results
fprintf(‘Iteration %d:n’, i);
fprintf(‘Max Objective Value: %fn’, max_value);
fprintf(‘Constraint Value 1: %fn’, constraint_value1);
fprintf(‘Constraint Value 2: %fn’, constraint_value2);
fprintf(‘Combination: %snn’, mat2str(combination));
uniquecombinations(i,:) = combination;
% Remove the current maximum value to find the next one in the next iteration
data{max_index, 1} = -inf;
end
% Getting these combinations
1 8 2
3 7 1
1 3 2
3 6 1
1 2 3
3 5 1
7 8 1
3 2 4
3 1 2
4 8 1
% Since in first column 3 and 1 are repeated
% In 2nd column 8 is repeated
% In 3rd column 2 and 1 are repeated. combination, maximizing the objective MATLAB Answers — New Questions
What the phase C values are not coming Rpeak = 90% and Rss = 58% while other phase values are correct. Kindly explain is their any logical error in the code
What the phase C values are not coming Rpeak = 90% and Rss = 58% while other phase values are correct. Kindly explain is their any logical error in the code. Thanks
% Define parameters
Kf_Max = 100; % maximum forward rate
RLC = [0.01, 1, 10,0.01]; % RLC values
TauKf_ON = -0.01; % TauKf_ON
TauKf_OFF = -0.01; % TauKf_OFF
Kb_Max = 80; % maximum backward rate
Kb_Min = 10; % minimum backward rate
TauKb_ON = -0.01; % TauKb_ON
TauKb_OFF = -0.01; % TauKb_OFF
PhaseTimes = [0, 10, 500, 1000, 2000];% phase times (each row defines a phase)
timespan = [0, 2000]; % timespan for the simulation
% Example initial conditions for non-active and active receptor concentrations
Non_Active_Receptor_concentration = 100; % Initial non-active receptor concentration (as a vector)
Active_Receptor_concentration =0; % Initial active receptor concentration (as a vector)
[t, Non_Active_Receptor_concentration, Active_Receptor_concentration, PhaseResults, Kf_LMax, Kb] =TestCode1(Kf_Max, RLC, TauKf_ON, …
Kb_Max, Kb_Min, TauKb_ON, PhaseTimes, timespan, Non_Active_Receptor_concentration, Active_Receptor_concentration);
function [t, Non_Active_Receptor_concentration, Active_Receptor_concentration, PhaseResults, Kf_LMax, Kb] =TestCode1(Kf_Max, RLC, TauKf_ON, …
Kb_Max, Kb_Min, TauKb_ON, PhaseTimes, timespan, Non_Active_Receptor_concentration, Active_Receptor_concentration)
% Define functions for forward and backward reaction rates
Kf_L = @(t) calculate_kf(t, PhaseTimes, Kf_Max, RLC, TauKf_ON);
Kb = @(t) calculate_kb(t, PhaseTimes, Kb_Max, Kb_Min, TauKb_ON, RLC);
% Ensure that Non_Active_Receptor_concentration and Active_Receptor_concentration are column vectors
Non_Active_Receptor_concentration = Non_Active_Receptor_concentration(:);
Active_Receptor_concentration = Active_Receptor_concentration(:);
% Set initial conditions
initial_conditions = [Non_Active_Receptor_concentration(1); Active_Receptor_concentration(1)];
% Set ODE options for step size
options = odeset(‘MaxStep’, 0.05, ‘RelTol’, 1e-6, ‘AbsTol’, 1e-8);
% Solve the ODE system
[t, y] = ode45(@(t, y) ode_LR(t, y, Kf_L, Kb), timespan, initial_conditions, options);
% Extract the concentrations
Non_Active_Receptor_concentration = y(:, 1);
Active_Receptor_concentration = y(:, 2);
% Calculate forward and backward reaction rates over time
Kf_values = arrayfun(Kf_L, t);
Kb_values = arrayfun(Kb, t);
% Plot active and non-active receptor concentrations
figure;
plot(t, Non_Active_Receptor_concentration, ‘r’, ‘DisplayName’, ‘Non-Active Receptor Concentration’);
hold on;
plot(t, Active_Receptor_concentration, ‘b’, ‘DisplayName’, ‘Active Receptor Concentration’);
legend;
xlabel(‘Time’);
ylabel(‘Concentration’);
title(‘Receptor Concentrations’);
hold off;
% Plot forward and backward reaction rates
figure;
plot(t, Kf_values, ‘k’, ‘DisplayName’, ‘Forward Reaction Rate’);
hold on;
plot(t, Kb_values, ‘c’, ‘DisplayName’, ‘Backward Reaction Rate’);
legend;
xlabel(‘Time’);
ylabel(‘Reaction Rate’);
title(‘Reaction Rates’);
hold off;
% Calculate phase results
PhaseResults = arrayfun(@(i) …
calculate_phase(t, Active_Receptor_concentration, PhaseTimes(:,i:i+1), RLC(i)) …
, 1:(size(PhaseTimes, 2)-1), ‘UniformOutput’, false);
PhaseResults = vertcat(PhaseResults{:}); % Concatenate results
% Calculate maximum forward reaction rate
Kf_LMax = Kf_Max * (RLC ./ (RLC + 1));
% Write Phase results to CSV
for i = 1:size(PhaseResults, 1)
PhaseTable = struct2table(PhaseResults(i))
writetable(PhaseTable, [‘Phase’, num2str(i), ‘.csv’]);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Kf_L = calculate_kf(t, PhaseTimes, Kf_Max, RLC, TauKf_ON)
Kf_LMax = Kf_Max * (RLC ./ (RLC + 1));
Kf_L = Kf_LMax(1); % Default to the first phase value
num_phases = numel(RLC);
for j = 1:num_phases
T_start = PhaseTimes(j);
T_end = PhaseTimes(j + 1);
if t >= T_start && t < T_end
if j == 1
Kf_L = Kf_LMax(j);
else
prev_end = PhaseTimes(j);
if j < num_phases
if RLC(j-1) < RLC(j) && RLC(j) > RLC(j+1)
Kf_L = Kf_LMax(j);
elseif RLC(j-1) < RLC(j) && RLC(j) <= RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
elseif RLC(j-1) > RLC(j) && RLC(j) < RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
elseif RLC(j-1) > RLC(j) && RLC(j) >= RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
end
end
end
return;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Kb = calculate_kb(t, PhaseTimes, Kb_Max, Kb_Min, ~, RLC)
Kb = Kb_Max; % Default to the minimum value
if all(RLC == RLC(1))
Kb = Kb_Min; % Set Kb to Kb_Min if all RLC values are equal
return;
end
for j = 1:numel(RLC)
T_start = PhaseTimes(j);
T_end = PhaseTimes(j + 1);
if t >= T_start && t < T_end
if j == 1
Kb = Kb_Max;
else
% prev_end = PhaseTimes(j);
if j < numel(RLC)
if RLC(j-1) < RLC(j) && RLC(j) > RLC(j+1)
Kb = Kb_Max ;
elseif RLC(j-1) < RLC(j) && RLC(j) <= RLC(j+1)
Kb = Kb_Max ;
elseif RLC(j-1) > RLC(j) && RLC(j) < RLC(j+1)
Kb = Kb_Max;
elseif RLC(j-1) > RLC(j) && RLC(j) >= RLC(j+1)
Kb = Kb_Max ;
end
else
if RLC(j-1) < RLC(j)
Kb = Kb_Max;
elseif RLC(j-1) > RLC(j)
Kb = Kb_Max;
end
end
end
return;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dydt = ode_LR(t, y, Kf_L, Kb)
Non_Active_Receptor_concentration = y(1);
Active_Receptor_concentration = y(2);
dNonActiveReceptor_dt = -Kf_L(t) * Non_Active_Receptor_concentration + Kb(t) * Active_Receptor_concentration;
dActiveReceptor_dt = Kf_L(t) * Non_Active_Receptor_concentration – Kb(t) * Active_Receptor_concentration;
dydt = [dNonActiveReceptor_dt; dActiveReceptor_dt];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function result = calculate_phase(t, Active_Receptor_concentration, PhaseTimes, RLC)
T_start = PhaseTimes(:,1);
T_end = PhaseTimes(:,2);
Phase_indices = (t >= T_start & t <= T_end);
Phase_concentration = Active_Receptor_concentration(Phase_indices);
Phase_time = t(Phase_indices);
% Calculate peak and steady-state values
[Rpeak, Tpeak, peak_type] = findpeak(Phase_time, Phase_concentration);
Rss = mean(Active_Receptor_concentration(t >= (T_end – 10) & t <= T_end));
% Calculate the T50 (time to reach half of peak value)
half_peak_value = (Rss + Rpeak) / 2;
[~, idx_50_percent] = min(abs(Phase_concentration – half_peak_value));
T50 = Phase_time(idx_50_percent) – Tpeak;
% Calculate other metrics
ratio_Rpeak_Rss = Rpeak / Rss;
Delta = Rpeak – Rss;
L = RLC;
% Package results in a struct
result.Rpeak = Rpeak;
result.Rss = Rss;
result.Tpeak = Tpeak;
result.T50 = T50;
result.ratio_Rpeak_Rss = ratio_Rpeak_Rss;
result.Delta = Delta;
result.L = L;
result.peak_type = peak_type;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rpeak, Tpeak, peak_type] = findpeak(time, concentration)
% Compute the derivative
dt = diff(time);
dy = diff(concentration);
derivative = dy ./ dt;
% Find zero-crossings of the derivative
zero_crossings = find(diff(sign(derivative)) ~= 0);
% Initialize output variables
Rpeak = NaN;
Tpeak = NaN;
peak_type = ‘None’;
% Check if there are zero crossings
if ~isempty(zero_crossings)
% Identify peaks and troughs by examining the sign changes
max_indices = zero_crossings(derivative(zero_crossings) > 0 & derivative(zero_crossings + 1) < 0);
min_indices = zero_crossings(derivative(zero_crossings) < 0 & derivative(zero_crossings + 1) > 0);
% Check if there are maxima or minima
if ~isempty(max_indices) || ~isempty(min_indices)
if ~isempty(max_indices) && ~isempty(min_indices)
% Find the highest maximum
[Rpeak_max, maxIdx] = max(concentration(max_indices));
% Find the lowest minimum
[Rpeak_min, minIdx] = min(concentration(min_indices));
% Determine whether the highest maximum is greater or the lowest minimum is smaller
if Rpeak_max >= abs(Rpeak_min)
Rpeak = Rpeak_max;
Tpeak = time(max_indices(maxIdx));
peak_type = ‘High’;
else
Rpeak = Rpeak_min;
Tpeak = time(min_indices(minIdx));
peak_type = ‘Low’;
end
% If only maxima exist
elseif ~isempty(max_indices)
[Rpeak, maxIdx] = max(concentration(max_indices));
Tpeak = time(max_indices(maxIdx));
peak_type = ‘High’;
% If only minima exist
elseif ~isempty(min_indices)
[Rpeak, minIdx] = min(concentration(min_indices));
Tpeak = time(min_indices(minIdx));
peak_type = ‘Low’;
end
end
end
endWhat the phase C values are not coming Rpeak = 90% and Rss = 58% while other phase values are correct. Kindly explain is their any logical error in the code. Thanks
% Define parameters
Kf_Max = 100; % maximum forward rate
RLC = [0.01, 1, 10,0.01]; % RLC values
TauKf_ON = -0.01; % TauKf_ON
TauKf_OFF = -0.01; % TauKf_OFF
Kb_Max = 80; % maximum backward rate
Kb_Min = 10; % minimum backward rate
TauKb_ON = -0.01; % TauKb_ON
TauKb_OFF = -0.01; % TauKb_OFF
PhaseTimes = [0, 10, 500, 1000, 2000];% phase times (each row defines a phase)
timespan = [0, 2000]; % timespan for the simulation
% Example initial conditions for non-active and active receptor concentrations
Non_Active_Receptor_concentration = 100; % Initial non-active receptor concentration (as a vector)
Active_Receptor_concentration =0; % Initial active receptor concentration (as a vector)
[t, Non_Active_Receptor_concentration, Active_Receptor_concentration, PhaseResults, Kf_LMax, Kb] =TestCode1(Kf_Max, RLC, TauKf_ON, …
Kb_Max, Kb_Min, TauKb_ON, PhaseTimes, timespan, Non_Active_Receptor_concentration, Active_Receptor_concentration);
function [t, Non_Active_Receptor_concentration, Active_Receptor_concentration, PhaseResults, Kf_LMax, Kb] =TestCode1(Kf_Max, RLC, TauKf_ON, …
Kb_Max, Kb_Min, TauKb_ON, PhaseTimes, timespan, Non_Active_Receptor_concentration, Active_Receptor_concentration)
% Define functions for forward and backward reaction rates
Kf_L = @(t) calculate_kf(t, PhaseTimes, Kf_Max, RLC, TauKf_ON);
Kb = @(t) calculate_kb(t, PhaseTimes, Kb_Max, Kb_Min, TauKb_ON, RLC);
% Ensure that Non_Active_Receptor_concentration and Active_Receptor_concentration are column vectors
Non_Active_Receptor_concentration = Non_Active_Receptor_concentration(:);
Active_Receptor_concentration = Active_Receptor_concentration(:);
% Set initial conditions
initial_conditions = [Non_Active_Receptor_concentration(1); Active_Receptor_concentration(1)];
% Set ODE options for step size
options = odeset(‘MaxStep’, 0.05, ‘RelTol’, 1e-6, ‘AbsTol’, 1e-8);
% Solve the ODE system
[t, y] = ode45(@(t, y) ode_LR(t, y, Kf_L, Kb), timespan, initial_conditions, options);
% Extract the concentrations
Non_Active_Receptor_concentration = y(:, 1);
Active_Receptor_concentration = y(:, 2);
% Calculate forward and backward reaction rates over time
Kf_values = arrayfun(Kf_L, t);
Kb_values = arrayfun(Kb, t);
% Plot active and non-active receptor concentrations
figure;
plot(t, Non_Active_Receptor_concentration, ‘r’, ‘DisplayName’, ‘Non-Active Receptor Concentration’);
hold on;
plot(t, Active_Receptor_concentration, ‘b’, ‘DisplayName’, ‘Active Receptor Concentration’);
legend;
xlabel(‘Time’);
ylabel(‘Concentration’);
title(‘Receptor Concentrations’);
hold off;
% Plot forward and backward reaction rates
figure;
plot(t, Kf_values, ‘k’, ‘DisplayName’, ‘Forward Reaction Rate’);
hold on;
plot(t, Kb_values, ‘c’, ‘DisplayName’, ‘Backward Reaction Rate’);
legend;
xlabel(‘Time’);
ylabel(‘Reaction Rate’);
title(‘Reaction Rates’);
hold off;
% Calculate phase results
PhaseResults = arrayfun(@(i) …
calculate_phase(t, Active_Receptor_concentration, PhaseTimes(:,i:i+1), RLC(i)) …
, 1:(size(PhaseTimes, 2)-1), ‘UniformOutput’, false);
PhaseResults = vertcat(PhaseResults{:}); % Concatenate results
% Calculate maximum forward reaction rate
Kf_LMax = Kf_Max * (RLC ./ (RLC + 1));
% Write Phase results to CSV
for i = 1:size(PhaseResults, 1)
PhaseTable = struct2table(PhaseResults(i))
writetable(PhaseTable, [‘Phase’, num2str(i), ‘.csv’]);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Kf_L = calculate_kf(t, PhaseTimes, Kf_Max, RLC, TauKf_ON)
Kf_LMax = Kf_Max * (RLC ./ (RLC + 1));
Kf_L = Kf_LMax(1); % Default to the first phase value
num_phases = numel(RLC);
for j = 1:num_phases
T_start = PhaseTimes(j);
T_end = PhaseTimes(j + 1);
if t >= T_start && t < T_end
if j == 1
Kf_L = Kf_LMax(j);
else
prev_end = PhaseTimes(j);
if j < num_phases
if RLC(j-1) < RLC(j) && RLC(j) > RLC(j+1)
Kf_L = Kf_LMax(j);
elseif RLC(j-1) < RLC(j) && RLC(j) <= RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
elseif RLC(j-1) > RLC(j) && RLC(j) < RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
elseif RLC(j-1) > RLC(j) && RLC(j) >= RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
end
end
end
return;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Kb = calculate_kb(t, PhaseTimes, Kb_Max, Kb_Min, ~, RLC)
Kb = Kb_Max; % Default to the minimum value
if all(RLC == RLC(1))
Kb = Kb_Min; % Set Kb to Kb_Min if all RLC values are equal
return;
end
for j = 1:numel(RLC)
T_start = PhaseTimes(j);
T_end = PhaseTimes(j + 1);
if t >= T_start && t < T_end
if j == 1
Kb = Kb_Max;
else
% prev_end = PhaseTimes(j);
if j < numel(RLC)
if RLC(j-1) < RLC(j) && RLC(j) > RLC(j+1)
Kb = Kb_Max ;
elseif RLC(j-1) < RLC(j) && RLC(j) <= RLC(j+1)
Kb = Kb_Max ;
elseif RLC(j-1) > RLC(j) && RLC(j) < RLC(j+1)
Kb = Kb_Max;
elseif RLC(j-1) > RLC(j) && RLC(j) >= RLC(j+1)
Kb = Kb_Max ;
end
else
if RLC(j-1) < RLC(j)
Kb = Kb_Max;
elseif RLC(j-1) > RLC(j)
Kb = Kb_Max;
end
end
end
return;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dydt = ode_LR(t, y, Kf_L, Kb)
Non_Active_Receptor_concentration = y(1);
Active_Receptor_concentration = y(2);
dNonActiveReceptor_dt = -Kf_L(t) * Non_Active_Receptor_concentration + Kb(t) * Active_Receptor_concentration;
dActiveReceptor_dt = Kf_L(t) * Non_Active_Receptor_concentration – Kb(t) * Active_Receptor_concentration;
dydt = [dNonActiveReceptor_dt; dActiveReceptor_dt];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function result = calculate_phase(t, Active_Receptor_concentration, PhaseTimes, RLC)
T_start = PhaseTimes(:,1);
T_end = PhaseTimes(:,2);
Phase_indices = (t >= T_start & t <= T_end);
Phase_concentration = Active_Receptor_concentration(Phase_indices);
Phase_time = t(Phase_indices);
% Calculate peak and steady-state values
[Rpeak, Tpeak, peak_type] = findpeak(Phase_time, Phase_concentration);
Rss = mean(Active_Receptor_concentration(t >= (T_end – 10) & t <= T_end));
% Calculate the T50 (time to reach half of peak value)
half_peak_value = (Rss + Rpeak) / 2;
[~, idx_50_percent] = min(abs(Phase_concentration – half_peak_value));
T50 = Phase_time(idx_50_percent) – Tpeak;
% Calculate other metrics
ratio_Rpeak_Rss = Rpeak / Rss;
Delta = Rpeak – Rss;
L = RLC;
% Package results in a struct
result.Rpeak = Rpeak;
result.Rss = Rss;
result.Tpeak = Tpeak;
result.T50 = T50;
result.ratio_Rpeak_Rss = ratio_Rpeak_Rss;
result.Delta = Delta;
result.L = L;
result.peak_type = peak_type;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rpeak, Tpeak, peak_type] = findpeak(time, concentration)
% Compute the derivative
dt = diff(time);
dy = diff(concentration);
derivative = dy ./ dt;
% Find zero-crossings of the derivative
zero_crossings = find(diff(sign(derivative)) ~= 0);
% Initialize output variables
Rpeak = NaN;
Tpeak = NaN;
peak_type = ‘None’;
% Check if there are zero crossings
if ~isempty(zero_crossings)
% Identify peaks and troughs by examining the sign changes
max_indices = zero_crossings(derivative(zero_crossings) > 0 & derivative(zero_crossings + 1) < 0);
min_indices = zero_crossings(derivative(zero_crossings) < 0 & derivative(zero_crossings + 1) > 0);
% Check if there are maxima or minima
if ~isempty(max_indices) || ~isempty(min_indices)
if ~isempty(max_indices) && ~isempty(min_indices)
% Find the highest maximum
[Rpeak_max, maxIdx] = max(concentration(max_indices));
% Find the lowest minimum
[Rpeak_min, minIdx] = min(concentration(min_indices));
% Determine whether the highest maximum is greater or the lowest minimum is smaller
if Rpeak_max >= abs(Rpeak_min)
Rpeak = Rpeak_max;
Tpeak = time(max_indices(maxIdx));
peak_type = ‘High’;
else
Rpeak = Rpeak_min;
Tpeak = time(min_indices(minIdx));
peak_type = ‘Low’;
end
% If only maxima exist
elseif ~isempty(max_indices)
[Rpeak, maxIdx] = max(concentration(max_indices));
Tpeak = time(max_indices(maxIdx));
peak_type = ‘High’;
% If only minima exist
elseif ~isempty(min_indices)
[Rpeak, minIdx] = min(concentration(min_indices));
Tpeak = time(min_indices(minIdx));
peak_type = ‘Low’;
end
end
end
end What the phase C values are not coming Rpeak = 90% and Rss = 58% while other phase values are correct. Kindly explain is their any logical error in the code. Thanks
% Define parameters
Kf_Max = 100; % maximum forward rate
RLC = [0.01, 1, 10,0.01]; % RLC values
TauKf_ON = -0.01; % TauKf_ON
TauKf_OFF = -0.01; % TauKf_OFF
Kb_Max = 80; % maximum backward rate
Kb_Min = 10; % minimum backward rate
TauKb_ON = -0.01; % TauKb_ON
TauKb_OFF = -0.01; % TauKb_OFF
PhaseTimes = [0, 10, 500, 1000, 2000];% phase times (each row defines a phase)
timespan = [0, 2000]; % timespan for the simulation
% Example initial conditions for non-active and active receptor concentrations
Non_Active_Receptor_concentration = 100; % Initial non-active receptor concentration (as a vector)
Active_Receptor_concentration =0; % Initial active receptor concentration (as a vector)
[t, Non_Active_Receptor_concentration, Active_Receptor_concentration, PhaseResults, Kf_LMax, Kb] =TestCode1(Kf_Max, RLC, TauKf_ON, …
Kb_Max, Kb_Min, TauKb_ON, PhaseTimes, timespan, Non_Active_Receptor_concentration, Active_Receptor_concentration);
function [t, Non_Active_Receptor_concentration, Active_Receptor_concentration, PhaseResults, Kf_LMax, Kb] =TestCode1(Kf_Max, RLC, TauKf_ON, …
Kb_Max, Kb_Min, TauKb_ON, PhaseTimes, timespan, Non_Active_Receptor_concentration, Active_Receptor_concentration)
% Define functions for forward and backward reaction rates
Kf_L = @(t) calculate_kf(t, PhaseTimes, Kf_Max, RLC, TauKf_ON);
Kb = @(t) calculate_kb(t, PhaseTimes, Kb_Max, Kb_Min, TauKb_ON, RLC);
% Ensure that Non_Active_Receptor_concentration and Active_Receptor_concentration are column vectors
Non_Active_Receptor_concentration = Non_Active_Receptor_concentration(:);
Active_Receptor_concentration = Active_Receptor_concentration(:);
% Set initial conditions
initial_conditions = [Non_Active_Receptor_concentration(1); Active_Receptor_concentration(1)];
% Set ODE options for step size
options = odeset(‘MaxStep’, 0.05, ‘RelTol’, 1e-6, ‘AbsTol’, 1e-8);
% Solve the ODE system
[t, y] = ode45(@(t, y) ode_LR(t, y, Kf_L, Kb), timespan, initial_conditions, options);
% Extract the concentrations
Non_Active_Receptor_concentration = y(:, 1);
Active_Receptor_concentration = y(:, 2);
% Calculate forward and backward reaction rates over time
Kf_values = arrayfun(Kf_L, t);
Kb_values = arrayfun(Kb, t);
% Plot active and non-active receptor concentrations
figure;
plot(t, Non_Active_Receptor_concentration, ‘r’, ‘DisplayName’, ‘Non-Active Receptor Concentration’);
hold on;
plot(t, Active_Receptor_concentration, ‘b’, ‘DisplayName’, ‘Active Receptor Concentration’);
legend;
xlabel(‘Time’);
ylabel(‘Concentration’);
title(‘Receptor Concentrations’);
hold off;
% Plot forward and backward reaction rates
figure;
plot(t, Kf_values, ‘k’, ‘DisplayName’, ‘Forward Reaction Rate’);
hold on;
plot(t, Kb_values, ‘c’, ‘DisplayName’, ‘Backward Reaction Rate’);
legend;
xlabel(‘Time’);
ylabel(‘Reaction Rate’);
title(‘Reaction Rates’);
hold off;
% Calculate phase results
PhaseResults = arrayfun(@(i) …
calculate_phase(t, Active_Receptor_concentration, PhaseTimes(:,i:i+1), RLC(i)) …
, 1:(size(PhaseTimes, 2)-1), ‘UniformOutput’, false);
PhaseResults = vertcat(PhaseResults{:}); % Concatenate results
% Calculate maximum forward reaction rate
Kf_LMax = Kf_Max * (RLC ./ (RLC + 1));
% Write Phase results to CSV
for i = 1:size(PhaseResults, 1)
PhaseTable = struct2table(PhaseResults(i))
writetable(PhaseTable, [‘Phase’, num2str(i), ‘.csv’]);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Kf_L = calculate_kf(t, PhaseTimes, Kf_Max, RLC, TauKf_ON)
Kf_LMax = Kf_Max * (RLC ./ (RLC + 1));
Kf_L = Kf_LMax(1); % Default to the first phase value
num_phases = numel(RLC);
for j = 1:num_phases
T_start = PhaseTimes(j);
T_end = PhaseTimes(j + 1);
if t >= T_start && t < T_end
if j == 1
Kf_L = Kf_LMax(j);
else
prev_end = PhaseTimes(j);
if j < num_phases
if RLC(j-1) < RLC(j) && RLC(j) > RLC(j+1)
Kf_L = Kf_LMax(j);
elseif RLC(j-1) < RLC(j) && RLC(j) <= RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
elseif RLC(j-1) > RLC(j) && RLC(j) < RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
elseif RLC(j-1) > RLC(j) && RLC(j) >= RLC(j+1)
Kf_end = Kf_LMax(j) – (Kf_LMax(j) – Kf_LMax(j-1)) * exp(TauKf_ON * (T_end – T_start));
Kf_L = Kf_LMax(j) + (Kf_end – Kf_LMax(j-1)) * exp(TauKf_ON * (t – prev_end));
end
end
end
return;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Kb = calculate_kb(t, PhaseTimes, Kb_Max, Kb_Min, ~, RLC)
Kb = Kb_Max; % Default to the minimum value
if all(RLC == RLC(1))
Kb = Kb_Min; % Set Kb to Kb_Min if all RLC values are equal
return;
end
for j = 1:numel(RLC)
T_start = PhaseTimes(j);
T_end = PhaseTimes(j + 1);
if t >= T_start && t < T_end
if j == 1
Kb = Kb_Max;
else
% prev_end = PhaseTimes(j);
if j < numel(RLC)
if RLC(j-1) < RLC(j) && RLC(j) > RLC(j+1)
Kb = Kb_Max ;
elseif RLC(j-1) < RLC(j) && RLC(j) <= RLC(j+1)
Kb = Kb_Max ;
elseif RLC(j-1) > RLC(j) && RLC(j) < RLC(j+1)
Kb = Kb_Max;
elseif RLC(j-1) > RLC(j) && RLC(j) >= RLC(j+1)
Kb = Kb_Max ;
end
else
if RLC(j-1) < RLC(j)
Kb = Kb_Max;
elseif RLC(j-1) > RLC(j)
Kb = Kb_Max;
end
end
end
return;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dydt = ode_LR(t, y, Kf_L, Kb)
Non_Active_Receptor_concentration = y(1);
Active_Receptor_concentration = y(2);
dNonActiveReceptor_dt = -Kf_L(t) * Non_Active_Receptor_concentration + Kb(t) * Active_Receptor_concentration;
dActiveReceptor_dt = Kf_L(t) * Non_Active_Receptor_concentration – Kb(t) * Active_Receptor_concentration;
dydt = [dNonActiveReceptor_dt; dActiveReceptor_dt];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function result = calculate_phase(t, Active_Receptor_concentration, PhaseTimes, RLC)
T_start = PhaseTimes(:,1);
T_end = PhaseTimes(:,2);
Phase_indices = (t >= T_start & t <= T_end);
Phase_concentration = Active_Receptor_concentration(Phase_indices);
Phase_time = t(Phase_indices);
% Calculate peak and steady-state values
[Rpeak, Tpeak, peak_type] = findpeak(Phase_time, Phase_concentration);
Rss = mean(Active_Receptor_concentration(t >= (T_end – 10) & t <= T_end));
% Calculate the T50 (time to reach half of peak value)
half_peak_value = (Rss + Rpeak) / 2;
[~, idx_50_percent] = min(abs(Phase_concentration – half_peak_value));
T50 = Phase_time(idx_50_percent) – Tpeak;
% Calculate other metrics
ratio_Rpeak_Rss = Rpeak / Rss;
Delta = Rpeak – Rss;
L = RLC;
% Package results in a struct
result.Rpeak = Rpeak;
result.Rss = Rss;
result.Tpeak = Tpeak;
result.T50 = T50;
result.ratio_Rpeak_Rss = ratio_Rpeak_Rss;
result.Delta = Delta;
result.L = L;
result.peak_type = peak_type;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Rpeak, Tpeak, peak_type] = findpeak(time, concentration)
% Compute the derivative
dt = diff(time);
dy = diff(concentration);
derivative = dy ./ dt;
% Find zero-crossings of the derivative
zero_crossings = find(diff(sign(derivative)) ~= 0);
% Initialize output variables
Rpeak = NaN;
Tpeak = NaN;
peak_type = ‘None’;
% Check if there are zero crossings
if ~isempty(zero_crossings)
% Identify peaks and troughs by examining the sign changes
max_indices = zero_crossings(derivative(zero_crossings) > 0 & derivative(zero_crossings + 1) < 0);
min_indices = zero_crossings(derivative(zero_crossings) < 0 & derivative(zero_crossings + 1) > 0);
% Check if there are maxima or minima
if ~isempty(max_indices) || ~isempty(min_indices)
if ~isempty(max_indices) && ~isempty(min_indices)
% Find the highest maximum
[Rpeak_max, maxIdx] = max(concentration(max_indices));
% Find the lowest minimum
[Rpeak_min, minIdx] = min(concentration(min_indices));
% Determine whether the highest maximum is greater or the lowest minimum is smaller
if Rpeak_max >= abs(Rpeak_min)
Rpeak = Rpeak_max;
Tpeak = time(max_indices(maxIdx));
peak_type = ‘High’;
else
Rpeak = Rpeak_min;
Tpeak = time(min_indices(minIdx));
peak_type = ‘Low’;
end
% If only maxima exist
elseif ~isempty(max_indices)
[Rpeak, maxIdx] = max(concentration(max_indices));
Tpeak = time(max_indices(maxIdx));
peak_type = ‘High’;
% If only minima exist
elseif ~isempty(min_indices)
[Rpeak, minIdx] = min(concentration(min_indices));
Tpeak = time(min_indices(minIdx));
peak_type = ‘Low’;
end
end
end
end matlab MATLAB Answers — New Questions
Issue with changing Xlabel in DensityScatterChart fucntion
Hi,
I am using DensityScatterChart() function to color code the data points based on the density.
Unfortunately, I couldn’t change the X label and colorbar, I inded tried the following
d.XLabel=’pixels’,’fontweight’,’bold’,’FontSize’,10,’Interpreter’,’latex’;
However, it prints only pixels without taking taking into acount the other font properties.
Actully my aim is to color code the data points in the scatter plot based on the desnity. Any other alternatives also appreciable.Hi,
I am using DensityScatterChart() function to color code the data points based on the density.
Unfortunately, I couldn’t change the X label and colorbar, I inded tried the following
d.XLabel=’pixels’,’fontweight’,’bold’,’FontSize’,10,’Interpreter’,’latex’;
However, it prints only pixels without taking taking into acount the other font properties.
Actully my aim is to color code the data points in the scatter plot based on the desnity. Any other alternatives also appreciable. Hi,
I am using DensityScatterChart() function to color code the data points based on the density.
Unfortunately, I couldn’t change the X label and colorbar, I inded tried the following
d.XLabel=’pixels’,’fontweight’,’bold’,’FontSize’,10,’Interpreter’,’latex’;
However, it prints only pixels without taking taking into acount the other font properties.
Actully my aim is to color code the data points in the scatter plot based on the desnity. Any other alternatives also appreciable. scatter plot, desnity scatter plot, color based on number density MATLAB Answers — New Questions
How to filter out the noisy portion of contourf plot?
The code below shows a ´contourf´ plot
load(‘impdta.mat’)
[C,h] = contourf(x1,y1,ua, ‘ShowText’,’on’,FaceAlpha=0.3,EdgeAlpha=0.2,EdgeColor=’k’,LevelStep=10);
clabel(C,h,’FontSize’,7,’Color’,[0.6 0.6 0.6])
axis equal
In the above contour plot, the left side of the contour shows a smooth trend. I want to use this contour plot to interpolate to a value (say 60), which in current situation gives multiple ‘lines’ (marked in red). Is there a way the cluttered contours can be filtered out? An idea could be to use limits of x from zero to 600, but there are multiple plots in which this noncluttered area changes location and the limits cannot be simply applied. I would like to filter out the cluttered portion and left with the smooth contour lines only so that when I interpolate the value, only distinct contours can be extracted. I would appreciate if a solution can be attained.
hold on
contourf(x1,y1,ua, [60 60], ‘ShowText’,’on’,FaceAlpha=0,EdgeAlpha=0.5,EdgeColor=’r’);The code below shows a ´contourf´ plot
load(‘impdta.mat’)
[C,h] = contourf(x1,y1,ua, ‘ShowText’,’on’,FaceAlpha=0.3,EdgeAlpha=0.2,EdgeColor=’k’,LevelStep=10);
clabel(C,h,’FontSize’,7,’Color’,[0.6 0.6 0.6])
axis equal
In the above contour plot, the left side of the contour shows a smooth trend. I want to use this contour plot to interpolate to a value (say 60), which in current situation gives multiple ‘lines’ (marked in red). Is there a way the cluttered contours can be filtered out? An idea could be to use limits of x from zero to 600, but there are multiple plots in which this noncluttered area changes location and the limits cannot be simply applied. I would like to filter out the cluttered portion and left with the smooth contour lines only so that when I interpolate the value, only distinct contours can be extracted. I would appreciate if a solution can be attained.
hold on
contourf(x1,y1,ua, [60 60], ‘ShowText’,’on’,FaceAlpha=0,EdgeAlpha=0.5,EdgeColor=’r’); The code below shows a ´contourf´ plot
load(‘impdta.mat’)
[C,h] = contourf(x1,y1,ua, ‘ShowText’,’on’,FaceAlpha=0.3,EdgeAlpha=0.2,EdgeColor=’k’,LevelStep=10);
clabel(C,h,’FontSize’,7,’Color’,[0.6 0.6 0.6])
axis equal
In the above contour plot, the left side of the contour shows a smooth trend. I want to use this contour plot to interpolate to a value (say 60), which in current situation gives multiple ‘lines’ (marked in red). Is there a way the cluttered contours can be filtered out? An idea could be to use limits of x from zero to 600, but there are multiple plots in which this noncluttered area changes location and the limits cannot be simply applied. I would like to filter out the cluttered portion and left with the smooth contour lines only so that when I interpolate the value, only distinct contours can be extracted. I would appreciate if a solution can be attained.
hold on
contourf(x1,y1,ua, [60 60], ‘ShowText’,’on’,FaceAlpha=0,EdgeAlpha=0.5,EdgeColor=’r’); contourf, filtering, noise, cluttering, discard noise MATLAB Answers — New Questions
how can I increase the font size in the “help on selection” window to improve readability?
when I request help on selected command the "help on selection" opens a small window on screen with explanation but in small letters almost unreadable for me. How can I increase the fontsize on screen?when I request help on selected command the "help on selection" opens a small window on screen with explanation but in small letters almost unreadable for me. How can I increase the fontsize on screen? when I request help on selected command the "help on selection" opens a small window on screen with explanation but in small letters almost unreadable for me. How can I increase the fontsize on screen? help window, fontsize on screen MATLAB Answers — New Questions
Extract cell rows to new array after strfind or strcmp matching.
Hi everyone,
I have an array of data (500*7) and the 7th column is a series of date array, they are all in random order so I would like to rearrange by month_array. So for each cell matching the portion of string ’01/2015′ i want a loop that extract the all rows (1:7) for example and store it in a new array etc.
I have included a picture to ease the understanding.
jan_table = [];
for i=1:size(ship_table);
idx = strfind(ship_table(i,7),’01/2015′);
if idx isequal(‘4’)
STORE ROW IN NEW ARRAY jan_table
else
jan_table = [jan_table num2cell(ships_table{i})];
end
end
If anyone could help, thanks!Hi everyone,
I have an array of data (500*7) and the 7th column is a series of date array, they are all in random order so I would like to rearrange by month_array. So for each cell matching the portion of string ’01/2015′ i want a loop that extract the all rows (1:7) for example and store it in a new array etc.
I have included a picture to ease the understanding.
jan_table = [];
for i=1:size(ship_table);
idx = strfind(ship_table(i,7),’01/2015′);
if idx isequal(‘4’)
STORE ROW IN NEW ARRAY jan_table
else
jan_table = [jan_table num2cell(ships_table{i})];
end
end
If anyone could help, thanks! Hi everyone,
I have an array of data (500*7) and the 7th column is a series of date array, they are all in random order so I would like to rearrange by month_array. So for each cell matching the portion of string ’01/2015′ i want a loop that extract the all rows (1:7) for example and store it in a new array etc.
I have included a picture to ease the understanding.
jan_table = [];
for i=1:size(ship_table);
idx = strfind(ship_table(i,7),’01/2015′);
if idx isequal(‘4’)
STORE ROW IN NEW ARRAY jan_table
else
jan_table = [jan_table num2cell(ships_table{i})];
end
end
If anyone could help, thanks! strfind, strcmp, extract cell to new array MATLAB Answers — New Questions
Issues when exporting Creo Model with Simscape toolkit
Hello,
I went through the setup guide for enabling Simscape Multibody Plugin in Creo-Pro/E.
The issue that I’m running into is when I try to export, I receive an error saying that Matlab is not running as an automation server. I have ran Matlab as an Administrator and typed in: regmatlabserver and checked that it was enabled by running [s, msg] = regmatlabserver
What I’m noticing is that when I export, it creates a new matlab command window instance – Is this creating another automation server instance with default permissions?
Creo version: 8Hello,
I went through the setup guide for enabling Simscape Multibody Plugin in Creo-Pro/E.
The issue that I’m running into is when I try to export, I receive an error saying that Matlab is not running as an automation server. I have ran Matlab as an Administrator and typed in: regmatlabserver and checked that it was enabled by running [s, msg] = regmatlabserver
What I’m noticing is that when I export, it creates a new matlab command window instance – Is this creating another automation server instance with default permissions?
Creo version: 8 Hello,
I went through the setup guide for enabling Simscape Multibody Plugin in Creo-Pro/E.
The issue that I’m running into is when I try to export, I receive an error saying that Matlab is not running as an automation server. I have ran Matlab as an Administrator and typed in: regmatlabserver and checked that it was enabled by running [s, msg] = regmatlabserver
What I’m noticing is that when I export, it creates a new matlab command window instance – Is this creating another automation server instance with default permissions?
Creo version: 8 matlab, simscape, plugin, creo, issues MATLAB Answers — New Questions
How to share a fully connected layer and is it possible to use a channel direction pooling?
(한국어로 답변주실 수 있다면 한국어로 답변 부탁드립니다.)
I am currently designing a model using the Deep Network Designer to implement a Convolutional Block Attention Module (CBAM).
For this, I need to use a channel-wise max/average pooling layer, and I am wondering if there is a way to implement this within MATLAB.
Additionally, I would like to know if there is a method to share a fully connected layer across different parts of the network. The current implementation of the fully connected layer seems to be limited to a single input and output.
Lastly, when passing through the fully connected layer, the dimension of the output is converted to (C x B). Is there a way to reshape this back to (S x S x C x B) in order to perform element-wise multiplication?(한국어로 답변주실 수 있다면 한국어로 답변 부탁드립니다.)
I am currently designing a model using the Deep Network Designer to implement a Convolutional Block Attention Module (CBAM).
For this, I need to use a channel-wise max/average pooling layer, and I am wondering if there is a way to implement this within MATLAB.
Additionally, I would like to know if there is a method to share a fully connected layer across different parts of the network. The current implementation of the fully connected layer seems to be limited to a single input and output.
Lastly, when passing through the fully connected layer, the dimension of the output is converted to (C x B). Is there a way to reshape this back to (S x S x C x B) in order to perform element-wise multiplication? (한국어로 답변주실 수 있다면 한국어로 답변 부탁드립니다.)
I am currently designing a model using the Deep Network Designer to implement a Convolutional Block Attention Module (CBAM).
For this, I need to use a channel-wise max/average pooling layer, and I am wondering if there is a way to implement this within MATLAB.
Additionally, I would like to know if there is a method to share a fully connected layer across different parts of the network. The current implementation of the fully connected layer seems to be limited to a single input and output.
Lastly, when passing through the fully connected layer, the dimension of the output is converted to (C x B). Is there a way to reshape this back to (S x S x C x B) in order to perform element-wise multiplication? deep learning, cbam, channel-wise pooling layer, reshape layer MATLAB Answers — New Questions
Estimation the parameters of a non-linear equation
The equation is P =(1-(1-q)*x*m)^(1/(1-q)), where P is probability and x is inter-event time (s), q and m are the parameters that need to be determined.
I have attached the excel file, column A is the ‘x’ value, column B is the value of ‘P’…So I need to determine the best possible q and m in a log-log plot (I have attached a plot in the excel file for your reference where blue line is the drawn plot (P_actual vs x) and orange one is the fitted plot after estimating the parameters (P_calculated vs x)…
There are 21115 values..so you have to first consider the data from 1 to 2000 (Group 1), calculate the q and m for this group..Then take the data from 2 to 20001 (Group 2), calculate the q and m for this group.. and so on..i.e., calculating the parameters for each and every group..U can also increase the group size, this is just an example.
Also, I don’t have much idea about the initial guess of the parameters…whenever i give the initial guess it never converges..still for your convenience this is the range 1 < q < 3..and 10 < m < 1000…But one thing is sure ‘q’ should always be more than 1..
Please help!!The equation is P =(1-(1-q)*x*m)^(1/(1-q)), where P is probability and x is inter-event time (s), q and m are the parameters that need to be determined.
I have attached the excel file, column A is the ‘x’ value, column B is the value of ‘P’…So I need to determine the best possible q and m in a log-log plot (I have attached a plot in the excel file for your reference where blue line is the drawn plot (P_actual vs x) and orange one is the fitted plot after estimating the parameters (P_calculated vs x)…
There are 21115 values..so you have to first consider the data from 1 to 2000 (Group 1), calculate the q and m for this group..Then take the data from 2 to 20001 (Group 2), calculate the q and m for this group.. and so on..i.e., calculating the parameters for each and every group..U can also increase the group size, this is just an example.
Also, I don’t have much idea about the initial guess of the parameters…whenever i give the initial guess it never converges..still for your convenience this is the range 1 < q < 3..and 10 < m < 1000…But one thing is sure ‘q’ should always be more than 1..
Please help!! The equation is P =(1-(1-q)*x*m)^(1/(1-q)), where P is probability and x is inter-event time (s), q and m are the parameters that need to be determined.
I have attached the excel file, column A is the ‘x’ value, column B is the value of ‘P’…So I need to determine the best possible q and m in a log-log plot (I have attached a plot in the excel file for your reference where blue line is the drawn plot (P_actual vs x) and orange one is the fitted plot after estimating the parameters (P_calculated vs x)…
There are 21115 values..so you have to first consider the data from 1 to 2000 (Group 1), calculate the q and m for this group..Then take the data from 2 to 20001 (Group 2), calculate the q and m for this group.. and so on..i.e., calculating the parameters for each and every group..U can also increase the group size, this is just an example.
Also, I don’t have much idea about the initial guess of the parameters…whenever i give the initial guess it never converges..still for your convenience this is the range 1 < q < 3..and 10 < m < 1000…But one thing is sure ‘q’ should always be more than 1..
Please help!! parameter estimation, maximum likelihood MATLAB Answers — New Questions
How to create a S-function for targetlink generated code .
I tried legacy tool for generating S-function which I was able to do .
eg. when I have a function with input parameters and return type well defined there is no issue .
When the function looks like this==>int sum (int a, int b) inside sum.c.
But in Targetlink generated code the main function is a void function.
eg. void sum (void), where i am struggling to create S-Function.
Can you please let me know any workaround for the same.
Regards
SumitI tried legacy tool for generating S-function which I was able to do .
eg. when I have a function with input parameters and return type well defined there is no issue .
When the function looks like this==>int sum (int a, int b) inside sum.c.
But in Targetlink generated code the main function is a void function.
eg. void sum (void), where i am struggling to create S-Function.
Can you please let me know any workaround for the same.
Regards
Sumit I tried legacy tool for generating S-function which I was able to do .
eg. when I have a function with input parameters and return type well defined there is no issue .
When the function looks like this==>int sum (int a, int b) inside sum.c.
But in Targetlink generated code the main function is a void function.
eg. void sum (void), where i am struggling to create S-Function.
Can you please let me know any workaround for the same.
Regards
Sumit s-function creation for targetlink generated code MATLAB Answers — New Questions
S-Function creation for Target link generated code
Hello Team,
I am creating on S-Function creation for Target Link generated codes.
I tried Legacy tool, but Legacy tool works well only when the input parameters and the return type are properly defined.
Example: When i have a function like==> double Sum( double a, double b).
Using def.OutputFcnSpec = ‘double y1 = doubleIt(double u1, double u2)’.
But Target Link generated code, the main function is Void.
Example: The function looks like this, Void Sum(Void), in Sum.c file.
Facing difficulty in creating S-Function for this.
Can you please suggest any work around for the above issue.
Regards
Santhosh AHello Team,
I am creating on S-Function creation for Target Link generated codes.
I tried Legacy tool, but Legacy tool works well only when the input parameters and the return type are properly defined.
Example: When i have a function like==> double Sum( double a, double b).
Using def.OutputFcnSpec = ‘double y1 = doubleIt(double u1, double u2)’.
But Target Link generated code, the main function is Void.
Example: The function looks like this, Void Sum(Void), in Sum.c file.
Facing difficulty in creating S-Function for this.
Can you please suggest any work around for the above issue.
Regards
Santhosh A Hello Team,
I am creating on S-Function creation for Target Link generated codes.
I tried Legacy tool, but Legacy tool works well only when the input parameters and the return type are properly defined.
Example: When i have a function like==> double Sum( double a, double b).
Using def.OutputFcnSpec = ‘double y1 = doubleIt(double u1, double u2)’.
But Target Link generated code, the main function is Void.
Example: The function looks like this, Void Sum(Void), in Sum.c file.
Facing difficulty in creating S-Function for this.
Can you please suggest any work around for the above issue.
Regards
Santhosh A s-function creation for target link generated code MATLAB Answers — New Questions
How to get var from base workspace in test sequence
How to get var from base workspace in test sequenceHow to get var from base workspace in test sequence How to get var from base workspace in test sequence test MATLAB Answers — New Questions
About the CenterOfMass property of rigidBodyTree
The CenterOfMass property in the rigidBodyTree class seems to not work. The code is as follows
clear;
load exampleRobots.mat
% Set lbr robot dynamics input data format to ‘column’
lbr.DataFormat = ‘column’;
lbr.Gravity=[0 0 -9.80665];
% Generate a random configuration for lbr
q = [0 0 0 0 0 0 0]’;
dq = [0 0 0 0 0 0 0]’;
ddq = [0.1 0 0 0 0 0 0]’;
%
% Compute the required joint torques for lbr to
% statically hold that configuration
tau = inverseDynamics(lbr, q);
disp(tau);
lbr.Bodies{1}.CenterOfMass=[1000 0 0];
tau = inverseDynamics(lbr, q);
disp(tau);
No matter how I change the position of the center of mass, the moment always remains the same.It looks like the center of mass position or body mass is set to 0,
matlab version is 2022a.The CenterOfMass property in the rigidBodyTree class seems to not work. The code is as follows
clear;
load exampleRobots.mat
% Set lbr robot dynamics input data format to ‘column’
lbr.DataFormat = ‘column’;
lbr.Gravity=[0 0 -9.80665];
% Generate a random configuration for lbr
q = [0 0 0 0 0 0 0]’;
dq = [0 0 0 0 0 0 0]’;
ddq = [0.1 0 0 0 0 0 0]’;
%
% Compute the required joint torques for lbr to
% statically hold that configuration
tau = inverseDynamics(lbr, q);
disp(tau);
lbr.Bodies{1}.CenterOfMass=[1000 0 0];
tau = inverseDynamics(lbr, q);
disp(tau);
No matter how I change the position of the center of mass, the moment always remains the same.It looks like the center of mass position or body mass is set to 0,
matlab version is 2022a. The CenterOfMass property in the rigidBodyTree class seems to not work. The code is as follows
clear;
load exampleRobots.mat
% Set lbr robot dynamics input data format to ‘column’
lbr.DataFormat = ‘column’;
lbr.Gravity=[0 0 -9.80665];
% Generate a random configuration for lbr
q = [0 0 0 0 0 0 0]’;
dq = [0 0 0 0 0 0 0]’;
ddq = [0.1 0 0 0 0 0 0]’;
%
% Compute the required joint torques for lbr to
% statically hold that configuration
tau = inverseDynamics(lbr, q);
disp(tau);
lbr.Bodies{1}.CenterOfMass=[1000 0 0];
tau = inverseDynamics(lbr, q);
disp(tau);
No matter how I change the position of the center of mass, the moment always remains the same.It looks like the center of mass position or body mass is set to 0,
matlab version is 2022a. 2022a, rigidbodytree MATLAB Answers — New Questions
Error when using lstm with cnn
XTrain = single(DL_input_reshaped(:,1,1,Training_Ind));
YTrain = single(DL_output_reshaped(1,1,:,Training_Ind)); XValidation = single(DL_input_reshaped(:,1,1,Validation_Ind));
YValidation = single(DL_output_reshaped(1,1,:,Validation_Ind));
YValidation_un = single(DL_output_reshaped_un);
%% DL Model definition with adjusted pooling and convolution layers layers = [ imageInputLayer([size(XTrain,1), 1, 1],’Name’,’input’,’Normalization’,’none’)
convolution2dLayer(3, 64, ‘Padding’, ‘same’, ‘Name’, ‘conv1’)
batchNormalizationLayer(‘Name’, ‘bn1’)
reluLayer(‘Name’, ‘relu1’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool1’)
convolution2dLayer(3, 128, ‘Padding’, ‘same’, ‘Name’, ‘conv2’)
batchNormalizationLayer(‘Name’, ‘bn2’)
reluLayer(‘Name’, ‘relu2’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool2’)
convolution2dLayer(3, 256, ‘Padding’, ‘same’, ‘Name’, ‘conv3’)
batchNormalizationLayer(‘Name’, ‘bn3’)
reluLayer(‘Name’, ‘relu3’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool3’)
flattenLayer(‘Name’, ‘flatten’) % Flatten to 1D per sample
lstmLayer(200, ‘OutputMode’, ‘last’, ‘Name’, ‘lstm1’) % LSTM layer
fullyConnectedLayer(512, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu4’)
dropoutLayer(0.5, ‘Name’, ‘dropout1’)
fullyConnectedLayer(1024, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu5’)
dropoutLayer(0.5, ‘Name’, ‘dropout2’)
fullyConnectedLayer(2048, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu6’)
dropoutLayer(0.5, ‘Name’, ‘dropout3’)
fullyConnectedLayer(size(YTrain,3), ‘Name’, ‘fc4’)
regressionLayer(‘Name’, ‘output’) ];
options = trainingOptions(‘rmsprop’, …
.
.
.
so this error is appear to me
((error useing trainNetwork Invalid training data.
The output size (1024) of the last layer does not match the response size (1).))
so the size or XTrain and YTrain is (features x 1 x 1 x minbatchsize)XTrain = single(DL_input_reshaped(:,1,1,Training_Ind));
YTrain = single(DL_output_reshaped(1,1,:,Training_Ind)); XValidation = single(DL_input_reshaped(:,1,1,Validation_Ind));
YValidation = single(DL_output_reshaped(1,1,:,Validation_Ind));
YValidation_un = single(DL_output_reshaped_un);
%% DL Model definition with adjusted pooling and convolution layers layers = [ imageInputLayer([size(XTrain,1), 1, 1],’Name’,’input’,’Normalization’,’none’)
convolution2dLayer(3, 64, ‘Padding’, ‘same’, ‘Name’, ‘conv1’)
batchNormalizationLayer(‘Name’, ‘bn1’)
reluLayer(‘Name’, ‘relu1’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool1’)
convolution2dLayer(3, 128, ‘Padding’, ‘same’, ‘Name’, ‘conv2’)
batchNormalizationLayer(‘Name’, ‘bn2’)
reluLayer(‘Name’, ‘relu2’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool2’)
convolution2dLayer(3, 256, ‘Padding’, ‘same’, ‘Name’, ‘conv3’)
batchNormalizationLayer(‘Name’, ‘bn3’)
reluLayer(‘Name’, ‘relu3’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool3’)
flattenLayer(‘Name’, ‘flatten’) % Flatten to 1D per sample
lstmLayer(200, ‘OutputMode’, ‘last’, ‘Name’, ‘lstm1’) % LSTM layer
fullyConnectedLayer(512, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu4’)
dropoutLayer(0.5, ‘Name’, ‘dropout1’)
fullyConnectedLayer(1024, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu5’)
dropoutLayer(0.5, ‘Name’, ‘dropout2’)
fullyConnectedLayer(2048, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu6’)
dropoutLayer(0.5, ‘Name’, ‘dropout3’)
fullyConnectedLayer(size(YTrain,3), ‘Name’, ‘fc4’)
regressionLayer(‘Name’, ‘output’) ];
options = trainingOptions(‘rmsprop’, …
.
.
.
so this error is appear to me
((error useing trainNetwork Invalid training data.
The output size (1024) of the last layer does not match the response size (1).))
so the size or XTrain and YTrain is (features x 1 x 1 x minbatchsize) XTrain = single(DL_input_reshaped(:,1,1,Training_Ind));
YTrain = single(DL_output_reshaped(1,1,:,Training_Ind)); XValidation = single(DL_input_reshaped(:,1,1,Validation_Ind));
YValidation = single(DL_output_reshaped(1,1,:,Validation_Ind));
YValidation_un = single(DL_output_reshaped_un);
%% DL Model definition with adjusted pooling and convolution layers layers = [ imageInputLayer([size(XTrain,1), 1, 1],’Name’,’input’,’Normalization’,’none’)
convolution2dLayer(3, 64, ‘Padding’, ‘same’, ‘Name’, ‘conv1’)
batchNormalizationLayer(‘Name’, ‘bn1’)
reluLayer(‘Name’, ‘relu1’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool1’)
convolution2dLayer(3, 128, ‘Padding’, ‘same’, ‘Name’, ‘conv2’)
batchNormalizationLayer(‘Name’, ‘bn2’)
reluLayer(‘Name’, ‘relu2’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool2’)
convolution2dLayer(3, 256, ‘Padding’, ‘same’, ‘Name’, ‘conv3’)
batchNormalizationLayer(‘Name’, ‘bn3’)
reluLayer(‘Name’, ‘relu3’)
maxPooling2dLayer([3,1], ‘Stride’, [3,1], ‘Name’, ‘maxpool3’)
flattenLayer(‘Name’, ‘flatten’) % Flatten to 1D per sample
lstmLayer(200, ‘OutputMode’, ‘last’, ‘Name’, ‘lstm1’) % LSTM layer
fullyConnectedLayer(512, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu4’)
dropoutLayer(0.5, ‘Name’, ‘dropout1’)
fullyConnectedLayer(1024, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu5’)
dropoutLayer(0.5, ‘Name’, ‘dropout2’)
fullyConnectedLayer(2048, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu6’)
dropoutLayer(0.5, ‘Name’, ‘dropout3’)
fullyConnectedLayer(size(YTrain,3), ‘Name’, ‘fc4’)
regressionLayer(‘Name’, ‘output’) ];
options = trainingOptions(‘rmsprop’, …
.
.
.
so this error is appear to me
((error useing trainNetwork Invalid training data.
The output size (1024) of the last layer does not match the response size (1).))
so the size or XTrain and YTrain is (features x 1 x 1 x minbatchsize) cnn, lstm, deep learning MATLAB Answers — New Questions
How to connect value in app designer to simulink
I have Simscape Simulink Model. I set the parameter of Spring Stiffness is k, Mass is m.
How to add value from Appdesign and Simulink ?
Thank you!I have Simscape Simulink Model. I set the parameter of Spring Stiffness is k, Mass is m.
How to add value from Appdesign and Simulink ?
Thank you! I have Simscape Simulink Model. I set the parameter of Spring Stiffness is k, Mass is m.
How to add value from Appdesign and Simulink ?
Thank you! app designer, simulink MATLAB Answers — New Questions
How to use Genetic Algorithm to solve discrete data for optimization?
Hello Everyone,
I have a question regarding Genetic Algorithm.
I have a data set for muffler optimisation in which I have calculated Transmission loss for various changes in muffler such as Inlet dia meter change and 5 other parameters for various frequiencies ranging from 60 Hz to 2000Hz. Each parameter is calculated for -15% to +15%.
change = [-15 , -10 , -5 , 0 , 5 , 10 , 15]; % Variable
input_length_RMSTL = [16.74 , 19.38 , 20.06 , 20.90 , 19.43 , 18.71 , 18.62];
output_length_RMSTL = [21.01 , 19.81 , 19.36 , 20.90 , 20.68 , 20.42 , 20.12];
muffler_length_RMSTL = [18.89 , 18.92 , 18.97 , 20.90 , 19.84 , 20.02 , 19.93];
input_dia_RMSTL = [18.77 , 19.47 , 18.98 , 20.90 , 19.56 , 19.68 , 19.99];
muffler_dia_RMSTL = [18.89 , 19.55 , 19.50 , 20.90 , 19.39 , 19.19 , 19.13];
output_dia_RMSTL = [18.99 , 19.24 , 19.49 , 20.90 , 19.46 , 19.52 , 19.77];
I have to optimise it using genetic algorithm. I have created function using curve fitting tool but this does seem to help as the curve is not properly fitting to all data points.
Can anybody help me with this problem?
Thanks in Advance.Hello Everyone,
I have a question regarding Genetic Algorithm.
I have a data set for muffler optimisation in which I have calculated Transmission loss for various changes in muffler such as Inlet dia meter change and 5 other parameters for various frequiencies ranging from 60 Hz to 2000Hz. Each parameter is calculated for -15% to +15%.
change = [-15 , -10 , -5 , 0 , 5 , 10 , 15]; % Variable
input_length_RMSTL = [16.74 , 19.38 , 20.06 , 20.90 , 19.43 , 18.71 , 18.62];
output_length_RMSTL = [21.01 , 19.81 , 19.36 , 20.90 , 20.68 , 20.42 , 20.12];
muffler_length_RMSTL = [18.89 , 18.92 , 18.97 , 20.90 , 19.84 , 20.02 , 19.93];
input_dia_RMSTL = [18.77 , 19.47 , 18.98 , 20.90 , 19.56 , 19.68 , 19.99];
muffler_dia_RMSTL = [18.89 , 19.55 , 19.50 , 20.90 , 19.39 , 19.19 , 19.13];
output_dia_RMSTL = [18.99 , 19.24 , 19.49 , 20.90 , 19.46 , 19.52 , 19.77];
I have to optimise it using genetic algorithm. I have created function using curve fitting tool but this does seem to help as the curve is not properly fitting to all data points.
Can anybody help me with this problem?
Thanks in Advance. Hello Everyone,
I have a question regarding Genetic Algorithm.
I have a data set for muffler optimisation in which I have calculated Transmission loss for various changes in muffler such as Inlet dia meter change and 5 other parameters for various frequiencies ranging from 60 Hz to 2000Hz. Each parameter is calculated for -15% to +15%.
change = [-15 , -10 , -5 , 0 , 5 , 10 , 15]; % Variable
input_length_RMSTL = [16.74 , 19.38 , 20.06 , 20.90 , 19.43 , 18.71 , 18.62];
output_length_RMSTL = [21.01 , 19.81 , 19.36 , 20.90 , 20.68 , 20.42 , 20.12];
muffler_length_RMSTL = [18.89 , 18.92 , 18.97 , 20.90 , 19.84 , 20.02 , 19.93];
input_dia_RMSTL = [18.77 , 19.47 , 18.98 , 20.90 , 19.56 , 19.68 , 19.99];
muffler_dia_RMSTL = [18.89 , 19.55 , 19.50 , 20.90 , 19.39 , 19.19 , 19.13];
output_dia_RMSTL = [18.99 , 19.24 , 19.49 , 20.90 , 19.46 , 19.52 , 19.77];
I have to optimise it using genetic algorithm. I have created function using curve fitting tool but this does seem to help as the curve is not properly fitting to all data points.
Can anybody help me with this problem?
Thanks in Advance. optimization, genetic algorithm MATLAB Answers — New Questions
How to Access Enum Bus Signal in Variant Subsystem within Referenced Model?
Hello everyone,
I’m facing an issue with a Simulink model where I’m using an enum bus signal to switch between two models configured as variant subsystems. These variant subsystems are part of a referenced model.
The problem is that the models in the referenced subsystem don’t seem to have access to the enum bus signal or even to the base workspace variables.
I need the enum bus signal to be available in the referenced models so that it can control the variant conditions. Does anyone have suggestions on how to pass this enum bus signal to the referenced model or how to make it accessible within these models?
Any help or insight would be greatly appreciated!
Thanks in advance!Hello everyone,
I’m facing an issue with a Simulink model where I’m using an enum bus signal to switch between two models configured as variant subsystems. These variant subsystems are part of a referenced model.
The problem is that the models in the referenced subsystem don’t seem to have access to the enum bus signal or even to the base workspace variables.
I need the enum bus signal to be available in the referenced models so that it can control the variant conditions. Does anyone have suggestions on how to pass this enum bus signal to the referenced model or how to make it accessible within these models?
Any help or insight would be greatly appreciated!
Thanks in advance! Hello everyone,
I’m facing an issue with a Simulink model where I’m using an enum bus signal to switch between two models configured as variant subsystems. These variant subsystems are part of a referenced model.
The problem is that the models in the referenced subsystem don’t seem to have access to the enum bus signal or even to the base workspace variables.
I need the enum bus signal to be available in the referenced models so that it can control the variant conditions. Does anyone have suggestions on how to pass this enum bus signal to the referenced model or how to make it accessible within these models?
Any help or insight would be greatly appreciated!
Thanks in advance! variant subsystem, referenced model MATLAB Answers — New Questions
function “getFileInfoForToolstrip” endless loop
I use the cvx tool box in my code. "getFileInfoForToolstrip" function is called. And it become endless loop. It can’t jump out of this function. But this function is written by MathWorks, I am confuse how i can solve it?
Following is the function I copy from the function.
function [isTestFile, isValidFile, isClassBasedTest] = getFileInfoForToolstrip(file)
[SL: snipped the full body of the MathWorks function]I use the cvx tool box in my code. "getFileInfoForToolstrip" function is called. And it become endless loop. It can’t jump out of this function. But this function is written by MathWorks, I am confuse how i can solve it?
Following is the function I copy from the function.
function [isTestFile, isValidFile, isClassBasedTest] = getFileInfoForToolstrip(file)
[SL: snipped the full body of the MathWorks function] I use the cvx tool box in my code. "getFileInfoForToolstrip" function is called. And it become endless loop. It can’t jump out of this function. But this function is written by MathWorks, I am confuse how i can solve it?
Following is the function I copy from the function.
function [isTestFile, isValidFile, isClassBasedTest] = getFileInfoForToolstrip(file)
[SL: snipped the full body of the MathWorks function] convex, optimization, official function MATLAB Answers — New Questions
Must return a column vector error when using “ode45”
%% Clean the Workspace
clc
clear all
%% Format
format long
%% Variables
global m_ExtraSteam U0_shell V rho_0 U_steam
T0_shell = 105; % initial shell side temp, degC
P0_shell = 1.2; % initial pressure, bara
U0_shell = XSteam(‘uV_p’, P0_shell);
Plimit = 3.3; % max pressure, bara
MW = 0.018015; % kg/mol
R = 0.00008205736; % bar.m3/mol.K
V = 233.21; % m3
rho_0 = XSteam(‘rhoV_p’, P0_shell);
tb = 20; % Upper time interval limit
m_ExtraSteam = 35.08; % Flowrate of extra steam due to ST trip, kg/sec
t_interval = [0.001 tb]; % Time interval
%% Solve the DE
[tsol,Usol] = ode45(@(t, U_steam) cfunc(t, U_steam) , t_interval , U0_shell); % Temperature with time, degC
%% Dynamic Parameter Calculation
Ptube_in = 7;
Ptube_out = 6.5;
m_tube = [707.9 707.9 707.9 707.9];
T_tube_in = [91.7 91.7 91.7 91.7];
for m=1:lenght(Usol)
U_steam = Usol(m);
Tsol(m) = fsolve(@TfinderwU,100);
end
for p=5:length(Tsol)
T_tube_in(p) = 80.1;
m_tube(p) = 1131.2;
end
T_tube_out = 98;
for k = 1:length(Tsol)
deltaH_tube(k) = XSteam(‘h_pT’, Ptube_out, T_tube_out) – XSteam(‘h_pT’, Ptube_in, T_tube_in(k)); % Specific enthalpy difference between the inlet and outlet of the tube side, kJ/kg
if ((m_tube(k)*deltaH_tube(k))/(XSteam(‘hV_T’, Tsol(k)) – XSteam(‘hL_T’, Tsol(k)))) >= m_ExtraSteam
m_ExtraSteam_Condensation(k) = m_ExtraSteam;
else
m_ExtraSteam_Condensation(k) = (m_tube(k)*deltaH_tube(k))/(XSteam(‘hV_T’, Tsol(k)) – XSteam(‘hL_T’, Tsol(k)));
end
end
m_steam_accumulated = (m_ExtraSteam – m_ExtraSteam_Condensation)’; % Steam accumulated in the shell side, kg/sec
nfor(1) = m_steam_accumulated(1)*(tsol(1))/MW;
for k1 = 2:length(Tsol)
nfor(k1) = m_steam_accumulated(k1)*(tsol(k1)-tsol(k1-1))/MW;
end
%% Final Pressure Calculation
%% Plotting
figure(‘Name’,’Temperature, Pressure vs Time’,’NumberTitle’,’off’);
yyaxis left % subplot(1,2,1)
plot(tsol,Tsol)
xlabel(‘Time (s)’)
ylabel(‘Temperature (C)’)
yyaxis right % subplot(1,2,2)
plot(tsol,Psol)
xlabel(‘Time (s)’)
ylabel(‘Pressure (bara)’)
%% Display Results
fprintf(‘Max pressure during the observed time interval = %.3f bara.n’, max(Psol))
%% Functions
% Main Function
function dUdt = cfunc(t,U_steam)
% Variables
global m_ExtraSteam U0_shell V rho_0 U_steam
Ptube_in = 7;
Ptube_out = 6.5;
T_tube_out = 98;
if t<3.3
m_tube = 707.9;
T_tube_in = 91.7;
else
m_tube = 1131.2;
T_tube_in = 80.1;
end
% Find the Temp with Internal Energy
T = fsolve(@TfinderwU,100);
deltaH_tube = XSteam(‘h_pT’, Ptube_out, T_tube_out) – XSteam(‘h_pT’, Ptube_in, T_tube_in); % Specific enthalpy difference between the inlet and outlet of the tube side, kJ/kg
if ((m_tube*deltaH_tube)/(XSteam(‘hV_T’, T) – XSteam(‘hL_T’, T))) >= m_ExtraSteam
m_ExtraSteam_Condensation = m_ExtraSteam;
else
m_ExtraSteam_Condensation = (m_tube*deltaH_tube)/(XSteam(‘hV_T’, T) – XSteam(‘hL_T’, T));
end
m_steam_accumulated = m_ExtraSteam – m_ExtraSteam_Condensation; % Steam accumulated in the shell side, kg/sec
steam_mass = rho_0*V + m_steam_accumulated*t;
U_condensate = XSteam(‘uL_T’, T);
CpL = XSteam(‘CpL_T’, T);
Qcv = m_tube*CpL*(T_tube_out-T_tube_in);
% Differential Equation
dUdt = (-Qcv + m_ExtraSteam*U0_shell – m_ExtraSteam_Condensation*U_condensate – U_steam*m_steam_accumulated)/steam_mass;
end
% Temperature Finder Function with Internal Energy
function Obj = TfinderwU(T)
global U_steam
uV_T = XSteam(‘uV_T’, T);
Obj = U_steam- uV_T;
end%% Clean the Workspace
clc
clear all
%% Format
format long
%% Variables
global m_ExtraSteam U0_shell V rho_0 U_steam
T0_shell = 105; % initial shell side temp, degC
P0_shell = 1.2; % initial pressure, bara
U0_shell = XSteam(‘uV_p’, P0_shell);
Plimit = 3.3; % max pressure, bara
MW = 0.018015; % kg/mol
R = 0.00008205736; % bar.m3/mol.K
V = 233.21; % m3
rho_0 = XSteam(‘rhoV_p’, P0_shell);
tb = 20; % Upper time interval limit
m_ExtraSteam = 35.08; % Flowrate of extra steam due to ST trip, kg/sec
t_interval = [0.001 tb]; % Time interval
%% Solve the DE
[tsol,Usol] = ode45(@(t, U_steam) cfunc(t, U_steam) , t_interval , U0_shell); % Temperature with time, degC
%% Dynamic Parameter Calculation
Ptube_in = 7;
Ptube_out = 6.5;
m_tube = [707.9 707.9 707.9 707.9];
T_tube_in = [91.7 91.7 91.7 91.7];
for m=1:lenght(Usol)
U_steam = Usol(m);
Tsol(m) = fsolve(@TfinderwU,100);
end
for p=5:length(Tsol)
T_tube_in(p) = 80.1;
m_tube(p) = 1131.2;
end
T_tube_out = 98;
for k = 1:length(Tsol)
deltaH_tube(k) = XSteam(‘h_pT’, Ptube_out, T_tube_out) – XSteam(‘h_pT’, Ptube_in, T_tube_in(k)); % Specific enthalpy difference between the inlet and outlet of the tube side, kJ/kg
if ((m_tube(k)*deltaH_tube(k))/(XSteam(‘hV_T’, Tsol(k)) – XSteam(‘hL_T’, Tsol(k)))) >= m_ExtraSteam
m_ExtraSteam_Condensation(k) = m_ExtraSteam;
else
m_ExtraSteam_Condensation(k) = (m_tube(k)*deltaH_tube(k))/(XSteam(‘hV_T’, Tsol(k)) – XSteam(‘hL_T’, Tsol(k)));
end
end
m_steam_accumulated = (m_ExtraSteam – m_ExtraSteam_Condensation)’; % Steam accumulated in the shell side, kg/sec
nfor(1) = m_steam_accumulated(1)*(tsol(1))/MW;
for k1 = 2:length(Tsol)
nfor(k1) = m_steam_accumulated(k1)*(tsol(k1)-tsol(k1-1))/MW;
end
%% Final Pressure Calculation
%% Plotting
figure(‘Name’,’Temperature, Pressure vs Time’,’NumberTitle’,’off’);
yyaxis left % subplot(1,2,1)
plot(tsol,Tsol)
xlabel(‘Time (s)’)
ylabel(‘Temperature (C)’)
yyaxis right % subplot(1,2,2)
plot(tsol,Psol)
xlabel(‘Time (s)’)
ylabel(‘Pressure (bara)’)
%% Display Results
fprintf(‘Max pressure during the observed time interval = %.3f bara.n’, max(Psol))
%% Functions
% Main Function
function dUdt = cfunc(t,U_steam)
% Variables
global m_ExtraSteam U0_shell V rho_0 U_steam
Ptube_in = 7;
Ptube_out = 6.5;
T_tube_out = 98;
if t<3.3
m_tube = 707.9;
T_tube_in = 91.7;
else
m_tube = 1131.2;
T_tube_in = 80.1;
end
% Find the Temp with Internal Energy
T = fsolve(@TfinderwU,100);
deltaH_tube = XSteam(‘h_pT’, Ptube_out, T_tube_out) – XSteam(‘h_pT’, Ptube_in, T_tube_in); % Specific enthalpy difference between the inlet and outlet of the tube side, kJ/kg
if ((m_tube*deltaH_tube)/(XSteam(‘hV_T’, T) – XSteam(‘hL_T’, T))) >= m_ExtraSteam
m_ExtraSteam_Condensation = m_ExtraSteam;
else
m_ExtraSteam_Condensation = (m_tube*deltaH_tube)/(XSteam(‘hV_T’, T) – XSteam(‘hL_T’, T));
end
m_steam_accumulated = m_ExtraSteam – m_ExtraSteam_Condensation; % Steam accumulated in the shell side, kg/sec
steam_mass = rho_0*V + m_steam_accumulated*t;
U_condensate = XSteam(‘uL_T’, T);
CpL = XSteam(‘CpL_T’, T);
Qcv = m_tube*CpL*(T_tube_out-T_tube_in);
% Differential Equation
dUdt = (-Qcv + m_ExtraSteam*U0_shell – m_ExtraSteam_Condensation*U_condensate – U_steam*m_steam_accumulated)/steam_mass;
end
% Temperature Finder Function with Internal Energy
function Obj = TfinderwU(T)
global U_steam
uV_T = XSteam(‘uV_T’, T);
Obj = U_steam- uV_T;
end %% Clean the Workspace
clc
clear all
%% Format
format long
%% Variables
global m_ExtraSteam U0_shell V rho_0 U_steam
T0_shell = 105; % initial shell side temp, degC
P0_shell = 1.2; % initial pressure, bara
U0_shell = XSteam(‘uV_p’, P0_shell);
Plimit = 3.3; % max pressure, bara
MW = 0.018015; % kg/mol
R = 0.00008205736; % bar.m3/mol.K
V = 233.21; % m3
rho_0 = XSteam(‘rhoV_p’, P0_shell);
tb = 20; % Upper time interval limit
m_ExtraSteam = 35.08; % Flowrate of extra steam due to ST trip, kg/sec
t_interval = [0.001 tb]; % Time interval
%% Solve the DE
[tsol,Usol] = ode45(@(t, U_steam) cfunc(t, U_steam) , t_interval , U0_shell); % Temperature with time, degC
%% Dynamic Parameter Calculation
Ptube_in = 7;
Ptube_out = 6.5;
m_tube = [707.9 707.9 707.9 707.9];
T_tube_in = [91.7 91.7 91.7 91.7];
for m=1:lenght(Usol)
U_steam = Usol(m);
Tsol(m) = fsolve(@TfinderwU,100);
end
for p=5:length(Tsol)
T_tube_in(p) = 80.1;
m_tube(p) = 1131.2;
end
T_tube_out = 98;
for k = 1:length(Tsol)
deltaH_tube(k) = XSteam(‘h_pT’, Ptube_out, T_tube_out) – XSteam(‘h_pT’, Ptube_in, T_tube_in(k)); % Specific enthalpy difference between the inlet and outlet of the tube side, kJ/kg
if ((m_tube(k)*deltaH_tube(k))/(XSteam(‘hV_T’, Tsol(k)) – XSteam(‘hL_T’, Tsol(k)))) >= m_ExtraSteam
m_ExtraSteam_Condensation(k) = m_ExtraSteam;
else
m_ExtraSteam_Condensation(k) = (m_tube(k)*deltaH_tube(k))/(XSteam(‘hV_T’, Tsol(k)) – XSteam(‘hL_T’, Tsol(k)));
end
end
m_steam_accumulated = (m_ExtraSteam – m_ExtraSteam_Condensation)’; % Steam accumulated in the shell side, kg/sec
nfor(1) = m_steam_accumulated(1)*(tsol(1))/MW;
for k1 = 2:length(Tsol)
nfor(k1) = m_steam_accumulated(k1)*(tsol(k1)-tsol(k1-1))/MW;
end
%% Final Pressure Calculation
%% Plotting
figure(‘Name’,’Temperature, Pressure vs Time’,’NumberTitle’,’off’);
yyaxis left % subplot(1,2,1)
plot(tsol,Tsol)
xlabel(‘Time (s)’)
ylabel(‘Temperature (C)’)
yyaxis right % subplot(1,2,2)
plot(tsol,Psol)
xlabel(‘Time (s)’)
ylabel(‘Pressure (bara)’)
%% Display Results
fprintf(‘Max pressure during the observed time interval = %.3f bara.n’, max(Psol))
%% Functions
% Main Function
function dUdt = cfunc(t,U_steam)
% Variables
global m_ExtraSteam U0_shell V rho_0 U_steam
Ptube_in = 7;
Ptube_out = 6.5;
T_tube_out = 98;
if t<3.3
m_tube = 707.9;
T_tube_in = 91.7;
else
m_tube = 1131.2;
T_tube_in = 80.1;
end
% Find the Temp with Internal Energy
T = fsolve(@TfinderwU,100);
deltaH_tube = XSteam(‘h_pT’, Ptube_out, T_tube_out) – XSteam(‘h_pT’, Ptube_in, T_tube_in); % Specific enthalpy difference between the inlet and outlet of the tube side, kJ/kg
if ((m_tube*deltaH_tube)/(XSteam(‘hV_T’, T) – XSteam(‘hL_T’, T))) >= m_ExtraSteam
m_ExtraSteam_Condensation = m_ExtraSteam;
else
m_ExtraSteam_Condensation = (m_tube*deltaH_tube)/(XSteam(‘hV_T’, T) – XSteam(‘hL_T’, T));
end
m_steam_accumulated = m_ExtraSteam – m_ExtraSteam_Condensation; % Steam accumulated in the shell side, kg/sec
steam_mass = rho_0*V + m_steam_accumulated*t;
U_condensate = XSteam(‘uL_T’, T);
CpL = XSteam(‘CpL_T’, T);
Qcv = m_tube*CpL*(T_tube_out-T_tube_in);
% Differential Equation
dUdt = (-Qcv + m_ExtraSteam*U0_shell – m_ExtraSteam_Condensation*U_condensate – U_steam*m_steam_accumulated)/steam_mass;
end
% Temperature Finder Function with Internal Energy
function Obj = TfinderwU(T)
global U_steam
uV_T = XSteam(‘uV_T’, T);
Obj = U_steam- uV_T;
end ode45, function, error MATLAB Answers — New Questions