Category: Matlab
Category Archives: Matlab
Error code line 19 with my Y=f(x), equation used is x^3+x^2-4x-4
function [x,y,err]=muller(f,x0,x1,x2,delta,epsilon,max1)
%Input – f is the object function
% – x0, x1, and x2 are the initial approximations
% – delta is the tolerance for x0, x1, and x2
% – epsilon the the tolerance for the function values y
% – max1 is the maximum number of iterations
%Output- x is the Muller approximation to the zero of f
% – y is the function value y = f(x)
% – err is the error in the approximation of x.
%Initalize the matrices X and Y
X=[x0 x1 x2];
Y=f(X);
%Calculate a and b in formula (15)
for k=1:max1
h0=X(1)-X(3);h1=X(2)-X(3);e0=Y(1)-Y(3);e1=Y(2)-Y(3);c=Y(3);
denom=h1*h0^2-h0*h1^2;
a=(e0*h1-e1*h0)/denom;
b=(e1*h0^2-e0*h1^2)/denom;
%Find the smallest root of (17)
if b < 0
disc=-disc;
end
z=-2*c/(b+disc);
x=X(3)+z;
%Sort the entries of X to find the two closest to x
if abs(x-X(2))<abs(x-X(1))
Q=[X(2) X(1) X(3)];
X=Q;
Y=f(X);
end
if abs(x-X(3))<abs(x-X(2))
R=[X(1) X(3) X(2)];
X=R;
Y=f(X);
end
%Replace the entry of X that was farthest from x with x
X(3)=x;
Y(3) = f(X(3));
y=Y(3);
%Determine stopping criteria
err=abs(z);
relerr=err/(abs(x)+delta);
if (err<delta)||(relerr<delta)||(abs(y)<epsilon)
break
end
endfunction [x,y,err]=muller(f,x0,x1,x2,delta,epsilon,max1)
%Input – f is the object function
% – x0, x1, and x2 are the initial approximations
% – delta is the tolerance for x0, x1, and x2
% – epsilon the the tolerance for the function values y
% – max1 is the maximum number of iterations
%Output- x is the Muller approximation to the zero of f
% – y is the function value y = f(x)
% – err is the error in the approximation of x.
%Initalize the matrices X and Y
X=[x0 x1 x2];
Y=f(X);
%Calculate a and b in formula (15)
for k=1:max1
h0=X(1)-X(3);h1=X(2)-X(3);e0=Y(1)-Y(3);e1=Y(2)-Y(3);c=Y(3);
denom=h1*h0^2-h0*h1^2;
a=(e0*h1-e1*h0)/denom;
b=(e1*h0^2-e0*h1^2)/denom;
%Find the smallest root of (17)
if b < 0
disc=-disc;
end
z=-2*c/(b+disc);
x=X(3)+z;
%Sort the entries of X to find the two closest to x
if abs(x-X(2))<abs(x-X(1))
Q=[X(2) X(1) X(3)];
X=Q;
Y=f(X);
end
if abs(x-X(3))<abs(x-X(2))
R=[X(1) X(3) X(2)];
X=R;
Y=f(X);
end
%Replace the entry of X that was farthest from x with x
X(3)=x;
Y(3) = f(X(3));
y=Y(3);
%Determine stopping criteria
err=abs(z);
relerr=err/(abs(x)+delta);
if (err<delta)||(relerr<delta)||(abs(y)<epsilon)
break
end
end function [x,y,err]=muller(f,x0,x1,x2,delta,epsilon,max1)
%Input – f is the object function
% – x0, x1, and x2 are the initial approximations
% – delta is the tolerance for x0, x1, and x2
% – epsilon the the tolerance for the function values y
% – max1 is the maximum number of iterations
%Output- x is the Muller approximation to the zero of f
% – y is the function value y = f(x)
% – err is the error in the approximation of x.
%Initalize the matrices X and Y
X=[x0 x1 x2];
Y=f(X);
%Calculate a and b in formula (15)
for k=1:max1
h0=X(1)-X(3);h1=X(2)-X(3);e0=Y(1)-Y(3);e1=Y(2)-Y(3);c=Y(3);
denom=h1*h0^2-h0*h1^2;
a=(e0*h1-e1*h0)/denom;
b=(e1*h0^2-e0*h1^2)/denom;
%Find the smallest root of (17)
if b < 0
disc=-disc;
end
z=-2*c/(b+disc);
x=X(3)+z;
%Sort the entries of X to find the two closest to x
if abs(x-X(2))<abs(x-X(1))
Q=[X(2) X(1) X(3)];
X=Q;
Y=f(X);
end
if abs(x-X(3))<abs(x-X(2))
R=[X(1) X(3) X(2)];
X=R;
Y=f(X);
end
%Replace the entry of X that was farthest from x with x
X(3)=x;
Y(3) = f(X(3));
y=Y(3);
%Determine stopping criteria
err=abs(z);
relerr=err/(abs(x)+delta);
if (err<delta)||(relerr<delta)||(abs(y)<epsilon)
break
end
end muller method MATLAB Answers — New Questions
BLDC motor driver usinf FOC simulation problem
Hi, i tried to create the simulink model of bldc motor driver using IFOC, but i just can not figure why the speed plot was not right? i tried to tune the pi controller, but seems that there might be problem with system.Hi, i tried to create the simulink model of bldc motor driver using IFOC, but i just can not figure why the speed plot was not right? i tried to tune the pi controller, but seems that there might be problem with system. Hi, i tried to create the simulink model of bldc motor driver using IFOC, but i just can not figure why the speed plot was not right? i tried to tune the pi controller, but seems that there might be problem with system. bldc foc, foc MATLAB Answers — New Questions
Hello, i need help on least square fitting for an infectious disease
An SIR model for COVID-19, Flu, and RSV
We utilize mathematical modeling based on differential equations to investigate the trans-
mission dynamics of the three respiratory infections: COVID-19, Flu, and RSV. To start, let
us consider a simple SIR model, which involves three compartments: the susceptible individ-
uals (denoted by S), the infected individuals (denoted by I), and the recovered individuals
(denoted by R).
The model is described as follows:
dS
dt = Lambda − beta SI − mu S,
dI
dt = beta SI − (gamma + w + mu )I,
dR
dt = gamma I − mu R.
The parameter Lambda is the population influx rate, beta is the transmission rates, mu is the natural
death rate for the human hosts, gamma is the rate of recovery from the infection, and w is the
disease induced death rate. For simplicity, we set Lambda = mu N, where N is the total population.
For the US, mu = 1/76.33 year−1 = 1/(76.33 ∗ 365) day−1
, and N = 345, 426, 571 people.
Other parameter values are:
COVID-19: gamma = 1/14 day−1
, w = 0.01/7 day−1
;
Flu: gamma = 1/3.5 day−1
, w = 0.006/7 day−1
;
RSV: gamma = 1/10.5 day−1
, w = 0.002/7 day−1
.
Apply this model separately to the US data on COVID-19, Flu, and RSV, and estimate the
value of the transmission rate beta in each case. The data fitting is typically done by using the
least squares method. Based on the fitted beta , calculate the basic reproduction number R0
for each.
I am supposed to consider the above instruction to write matlab codes to find the transmission rate for the flu, covid and the RSV data. Each of these diseases has six seasons starting from 2018-2019 seaons to 2023-2024 seasons.
if the matlab data for 2018-2019 flu season is this:
% Filter for the 2018-19 flu season
Flu_data_2018_2019 = Flu_data(strcmp(Flu_data.Season, ‘2018-19’), :);
% Display the filtered data for the 2018-19 season
disp(Flu_data_2018_2019);
% Display the ‘Weekly_Rate’ column (replace with the correct column name if needed)
Weekly_Rate_2018_2019 = Flu_data_2018_2019.WeeklyRate;
disp(Weekly_Rate_2018_2019);
help write a matlab code to find the transmission rate for the 2018-2019 flu season and the reproduction numberAn SIR model for COVID-19, Flu, and RSV
We utilize mathematical modeling based on differential equations to investigate the trans-
mission dynamics of the three respiratory infections: COVID-19, Flu, and RSV. To start, let
us consider a simple SIR model, which involves three compartments: the susceptible individ-
uals (denoted by S), the infected individuals (denoted by I), and the recovered individuals
(denoted by R).
The model is described as follows:
dS
dt = Lambda − beta SI − mu S,
dI
dt = beta SI − (gamma + w + mu )I,
dR
dt = gamma I − mu R.
The parameter Lambda is the population influx rate, beta is the transmission rates, mu is the natural
death rate for the human hosts, gamma is the rate of recovery from the infection, and w is the
disease induced death rate. For simplicity, we set Lambda = mu N, where N is the total population.
For the US, mu = 1/76.33 year−1 = 1/(76.33 ∗ 365) day−1
, and N = 345, 426, 571 people.
Other parameter values are:
COVID-19: gamma = 1/14 day−1
, w = 0.01/7 day−1
;
Flu: gamma = 1/3.5 day−1
, w = 0.006/7 day−1
;
RSV: gamma = 1/10.5 day−1
, w = 0.002/7 day−1
.
Apply this model separately to the US data on COVID-19, Flu, and RSV, and estimate the
value of the transmission rate beta in each case. The data fitting is typically done by using the
least squares method. Based on the fitted beta , calculate the basic reproduction number R0
for each.
I am supposed to consider the above instruction to write matlab codes to find the transmission rate for the flu, covid and the RSV data. Each of these diseases has six seasons starting from 2018-2019 seaons to 2023-2024 seasons.
if the matlab data for 2018-2019 flu season is this:
% Filter for the 2018-19 flu season
Flu_data_2018_2019 = Flu_data(strcmp(Flu_data.Season, ‘2018-19’), :);
% Display the filtered data for the 2018-19 season
disp(Flu_data_2018_2019);
% Display the ‘Weekly_Rate’ column (replace with the correct column name if needed)
Weekly_Rate_2018_2019 = Flu_data_2018_2019.WeeklyRate;
disp(Weekly_Rate_2018_2019);
help write a matlab code to find the transmission rate for the 2018-2019 flu season and the reproduction number An SIR model for COVID-19, Flu, and RSV
We utilize mathematical modeling based on differential equations to investigate the trans-
mission dynamics of the three respiratory infections: COVID-19, Flu, and RSV. To start, let
us consider a simple SIR model, which involves three compartments: the susceptible individ-
uals (denoted by S), the infected individuals (denoted by I), and the recovered individuals
(denoted by R).
The model is described as follows:
dS
dt = Lambda − beta SI − mu S,
dI
dt = beta SI − (gamma + w + mu )I,
dR
dt = gamma I − mu R.
The parameter Lambda is the population influx rate, beta is the transmission rates, mu is the natural
death rate for the human hosts, gamma is the rate of recovery from the infection, and w is the
disease induced death rate. For simplicity, we set Lambda = mu N, where N is the total population.
For the US, mu = 1/76.33 year−1 = 1/(76.33 ∗ 365) day−1
, and N = 345, 426, 571 people.
Other parameter values are:
COVID-19: gamma = 1/14 day−1
, w = 0.01/7 day−1
;
Flu: gamma = 1/3.5 day−1
, w = 0.006/7 day−1
;
RSV: gamma = 1/10.5 day−1
, w = 0.002/7 day−1
.
Apply this model separately to the US data on COVID-19, Flu, and RSV, and estimate the
value of the transmission rate beta in each case. The data fitting is typically done by using the
least squares method. Based on the fitted beta , calculate the basic reproduction number R0
for each.
I am supposed to consider the above instruction to write matlab codes to find the transmission rate for the flu, covid and the RSV data. Each of these diseases has six seasons starting from 2018-2019 seaons to 2023-2024 seasons.
if the matlab data for 2018-2019 flu season is this:
% Filter for the 2018-19 flu season
Flu_data_2018_2019 = Flu_data(strcmp(Flu_data.Season, ‘2018-19’), :);
% Display the filtered data for the 2018-19 season
disp(Flu_data_2018_2019);
% Display the ‘Weekly_Rate’ column (replace with the correct column name if needed)
Weekly_Rate_2018_2019 = Flu_data_2018_2019.WeeklyRate;
disp(Weekly_Rate_2018_2019);
help write a matlab code to find the transmission rate for the 2018-2019 flu season and the reproduction number matlab, least square fitting MATLAB Answers — New Questions
Real-Time error after the last update windows 10
Hi,
My Matlab / Simulink after the latest Windows 10 update (19041.329) can’t simulate in real time, the error message is:
An error occurred while running the simulation and the simulation was terminated
Caused by:
Error reported by S-function ‘sldrtsync’ in ‘ForcesCompensation_vRo_Ce_Be_Ga_v3/Real-Time Synchronization’: Hardware timer cannot be allocated. Real-time kernel cannot run.
Yesterday before the update everything works fine.
I tried to reinstall the following packages:
– Simulink in real time.
– Real-time desktop simulation.
– MATLAB support for the MinGW-w64 C / C ++ compiler.
And reinstall the real-time kernel with "sldrtkernel -install" command.
But the problem was not resolved.
I have the Matlab 2018b and Matlab 2019b and both have the same problem.
Can anyone help me?
Thanks.Hi,
My Matlab / Simulink after the latest Windows 10 update (19041.329) can’t simulate in real time, the error message is:
An error occurred while running the simulation and the simulation was terminated
Caused by:
Error reported by S-function ‘sldrtsync’ in ‘ForcesCompensation_vRo_Ce_Be_Ga_v3/Real-Time Synchronization’: Hardware timer cannot be allocated. Real-time kernel cannot run.
Yesterday before the update everything works fine.
I tried to reinstall the following packages:
– Simulink in real time.
– Real-time desktop simulation.
– MATLAB support for the MinGW-w64 C / C ++ compiler.
And reinstall the real-time kernel with "sldrtkernel -install" command.
But the problem was not resolved.
I have the Matlab 2018b and Matlab 2019b and both have the same problem.
Can anyone help me?
Thanks. Hi,
My Matlab / Simulink after the latest Windows 10 update (19041.329) can’t simulate in real time, the error message is:
An error occurred while running the simulation and the simulation was terminated
Caused by:
Error reported by S-function ‘sldrtsync’ in ‘ForcesCompensation_vRo_Ce_Be_Ga_v3/Real-Time Synchronization’: Hardware timer cannot be allocated. Real-time kernel cannot run.
Yesterday before the update everything works fine.
I tried to reinstall the following packages:
– Simulink in real time.
– Real-time desktop simulation.
– MATLAB support for the MinGW-w64 C / C ++ compiler.
And reinstall the real-time kernel with "sldrtkernel -install" command.
But the problem was not resolved.
I have the Matlab 2018b and Matlab 2019b and both have the same problem.
Can anyone help me?
Thanks. real-time, windows 10 update, simulink, matlab2018b, matlab2019b MATLAB Answers — New Questions
the neuro fuzzy sistem modify the membership function in input or in output?
Hello,
I wanted to understand what happens to the membership function (in input/output) or rules when I insert in the anfis editor: Sugeno file and a training set.Hello,
I wanted to understand what happens to the membership function (in input/output) or rules when I insert in the anfis editor: Sugeno file and a training set. Hello,
I wanted to understand what happens to the membership function (in input/output) or rules when I insert in the anfis editor: Sugeno file and a training set. sugeno, anfis editor, neuro fuzzy MATLAB Answers — New Questions
Thingspeak – Expired License message & upload stopped working
After login I got sweet message:
Expired License
Your trial license has expired as of September 4, 2019.
In account settings:
License Type: Free
Expiration Date: 04 Dec 2019
Available Remaining
Messages 3 000 000 2 851 627
Channels 4 2
Upload to channels stopped working on september 4th…After login I got sweet message:
Expired License
Your trial license has expired as of September 4, 2019.
In account settings:
License Type: Free
Expiration Date: 04 Dec 2019
Available Remaining
Messages 3 000 000 2 851 627
Channels 4 2
Upload to channels stopped working on september 4th… After login I got sweet message:
Expired License
Your trial license has expired as of September 4, 2019.
In account settings:
License Type: Free
Expiration Date: 04 Dec 2019
Available Remaining
Messages 3 000 000 2 851 627
Channels 4 2
Upload to channels stopped working on september 4th… thingspeak licence expired, thingspeak MATLAB Answers — New Questions
extracting table data from a plot picture question
Hello,I have many plots like this in the data sheet.
there is a java tools which manually allow to extract the data of each plot.
Is the a way in matlab to do it?
Thanks.Hello,I have many plots like this in the data sheet.
there is a java tools which manually allow to extract the data of each plot.
Is the a way in matlab to do it?
Thanks. Hello,I have many plots like this in the data sheet.
there is a java tools which manually allow to extract the data of each plot.
Is the a way in matlab to do it?
Thanks. plot, photo MATLAB Answers — New Questions
Matlab plots step response vs timestep number instead of time in seconds
s = tf(‘s’); %Laplace variable
t = 0:0.01:10; %time vector start, dt , end
K = 1;
KI = 0;
sysT = (K * s + KI) / ( ( s^3 + 3*s^2 + (2+K)*s + KI) );
[y,t] = step(sysT,t);
plot(y);
Above snippet shows issue. The issue is that plot(y); plots the step response vs the number of timesteps instead of vs time in secs. For instance if dt = 0.01, the abcissa is in the 100’s. If dt = 0.001, the abcissa is in the 1000’s. If dt = 0.0001, the abcissa is in the 10000’s. How can I just plot vs time in seconds??s = tf(‘s’); %Laplace variable
t = 0:0.01:10; %time vector start, dt , end
K = 1;
KI = 0;
sysT = (K * s + KI) / ( ( s^3 + 3*s^2 + (2+K)*s + KI) );
[y,t] = step(sysT,t);
plot(y);
Above snippet shows issue. The issue is that plot(y); plots the step response vs the number of timesteps instead of vs time in secs. For instance if dt = 0.01, the abcissa is in the 100’s. If dt = 0.001, the abcissa is in the 1000’s. If dt = 0.0001, the abcissa is in the 10000’s. How can I just plot vs time in seconds?? s = tf(‘s’); %Laplace variable
t = 0:0.01:10; %time vector start, dt , end
K = 1;
KI = 0;
sysT = (K * s + KI) / ( ( s^3 + 3*s^2 + (2+K)*s + KI) );
[y,t] = step(sysT,t);
plot(y);
Above snippet shows issue. The issue is that plot(y); plots the step response vs the number of timesteps instead of vs time in secs. For instance if dt = 0.01, the abcissa is in the 100’s. If dt = 0.001, the abcissa is in the 1000’s. If dt = 0.0001, the abcissa is in the 10000’s. How can I just plot vs time in seconds?? plot vs timestep number MATLAB Answers — New Questions
embedding inset plots in subplots matlab
Hi, I am trying to plots an insets plots in aubplots but only the last subplot and inset plots are shown. Please can someone help with this?
% Define xi_select and slope_select for main and inset plots
xi_select = [1, 10, 11, 12];
slope_select = [1, 3, 4, 5, 7, 9];
% Create a tiled layout with 2 rows and 3 columns of subplots
t = tiledlayout(2, 3, ‘TileSpacing’, ‘compact’, ‘Padding’, ‘compact’);
% Define custom colors (green to red gradient)
num_colors = length(xi_select);
custom_colors = [linspace(0, 1, num_colors)’, linspace(1, 0, num_colors)’, zeros(num_colors, 1)];
custom_linestyles = repmat({‘–‘}, 1, num_colors); % All dashed lines
% Initialize arrays for legend
legend_labels = {}; % Cell array to store legend labels
legend_index = 0; % Initialize legend index
plot_handles = []; % Array for storing plot handles
for j = 1:length(slope_select) % Loop through selected ramp_slope
% Create the main subplot
ax = nexttile; % Move to the next tile for each subplot
hold(ax, ‘on’); % Hold on to plot multiple lines in the same subplot
% Loop through selected xi values for the main plots
for i = 1:length(xi_select)
% Find the switching times for the current xi and ramp_slope
transitions = find(switching(:, xi_select(i), slope_select(j)));
if ~isempty(transitions)
% Plot the uxlt data at the switching times for this xi and ramp_slope
for t_idx = transitions
% Extract the uxlt data for the current time point
uxlt_data = squeeze(uxlt(ym, :, xi_select(i), slope_select(j))); % Dimension: y, xi, ramp_slope
% Proper LaTeX syntax for the legend entry, omitting time
display_name = sprintf(‘$\xi=%.2f$’, xi(xi_select(i)));
% Plot the data with specified color and linestyle
h = plot(ax, tarray, uxlt_data, ‘LineWidth’, 1.5, …
‘Color’, custom_colors(i, :), ‘LineStyle’, custom_linestyles{i});
% Only add the label and handle once to the legend
if ~ismember(display_name, legend_labels)
legend_index = legend_index + 1;
plot_handles(legend_index) = h(1); % Store only the first handle
legend_labels{legend_index} = display_name; % Append label
end
end
end
end
% Add labels and title to each subplot
xlabel(ax, ‘Time (s)’, ‘Interpreter’, ‘latex’);
ylabel(ax, ‘$int u_L , mathrm{dz}$’, ‘Interpreter’, ‘latex’);
xlim(ax, [min(tarray), max(tarray)]);
ylim(ax, [0, 2.5e-04]);
% Add subplot numbering and S_{rf} value
title(ax, sprintf(‘(%c) $S_{rf} = %.2f$’, ‘a’ + j – 1, ramp_slope(slope_select(j))), ‘Interpreter’, ‘latex’);
box(ax, ‘on’); % Place a box around the current subplot
% Add inset plots
inset_pos = ax.Position; % Get the position of the current subplot
if j == 1
% The first inset plot on the top left of the first subplot
inset_pos = [inset_pos(1) + 0.1 * inset_pos(3), inset_pos(2) + 0.65 * inset_pos(4), 0.15, 0.15];
else
% Remaining inset plots on the top right of the respective subplots
inset_pos = [inset_pos(1) + 0.6 * inset_pos(3), inset_pos(2) + 0.65 * inset_pos(4), 0.15, 0.15];
end
% Create new axes for inset plots, without attaching them to the main subplot axes
inset_ax = axes(‘Position’, inset_pos); % Create inset axes with adjusted position
hold(inset_ax, ‘on’); % Hold on inset axes to plot multiple lines
% Loop through selected xi values for the inset plots
for i = 1:length(xi_select)
% Find the switching times for the current xi and ramp_slope
transitions = find(switching(:, xi_select(i), slope_select(j)));
if ~isempty(transitions)
% Plot the uxl data in the inset plot
for t_idx = transitions
% Extract the uxl data for the current time point
uxl_data = squeeze(uxl(:, xi_select(i), slope_select(j))); % Dimension: y, xi, ramp_slope
% Plot the data in the inset with color and linestyle
plot(inset_ax, y, uxl_data, ‘LineWidth’, 1.5, …
‘Color’, custom_colors(i, :), ‘LineStyle’, custom_linestyles{i});
end
end
end
% Add labels to inset
xlabel(inset_ax, ‘$z$’, ‘Interpreter’, ‘latex’);
ylabel(inset_ax, ‘$int u_L , mathrm{dz}$’, ‘Interpreter’, ‘latex’);
xlim(inset_ax, [min(y), max(y)]);
hold(inset_ax, ‘off’); % Release hold on the inset axes
end
% Create a global legend (optional, if needed)
lgd = legend(plot_handles, legend_labels, ‘Interpreter’, ‘latex’, ‘NumColumns’, 2);
% Ensure that the entire figure has a box around it
box on;Hi, I am trying to plots an insets plots in aubplots but only the last subplot and inset plots are shown. Please can someone help with this?
% Define xi_select and slope_select for main and inset plots
xi_select = [1, 10, 11, 12];
slope_select = [1, 3, 4, 5, 7, 9];
% Create a tiled layout with 2 rows and 3 columns of subplots
t = tiledlayout(2, 3, ‘TileSpacing’, ‘compact’, ‘Padding’, ‘compact’);
% Define custom colors (green to red gradient)
num_colors = length(xi_select);
custom_colors = [linspace(0, 1, num_colors)’, linspace(1, 0, num_colors)’, zeros(num_colors, 1)];
custom_linestyles = repmat({‘–‘}, 1, num_colors); % All dashed lines
% Initialize arrays for legend
legend_labels = {}; % Cell array to store legend labels
legend_index = 0; % Initialize legend index
plot_handles = []; % Array for storing plot handles
for j = 1:length(slope_select) % Loop through selected ramp_slope
% Create the main subplot
ax = nexttile; % Move to the next tile for each subplot
hold(ax, ‘on’); % Hold on to plot multiple lines in the same subplot
% Loop through selected xi values for the main plots
for i = 1:length(xi_select)
% Find the switching times for the current xi and ramp_slope
transitions = find(switching(:, xi_select(i), slope_select(j)));
if ~isempty(transitions)
% Plot the uxlt data at the switching times for this xi and ramp_slope
for t_idx = transitions
% Extract the uxlt data for the current time point
uxlt_data = squeeze(uxlt(ym, :, xi_select(i), slope_select(j))); % Dimension: y, xi, ramp_slope
% Proper LaTeX syntax for the legend entry, omitting time
display_name = sprintf(‘$\xi=%.2f$’, xi(xi_select(i)));
% Plot the data with specified color and linestyle
h = plot(ax, tarray, uxlt_data, ‘LineWidth’, 1.5, …
‘Color’, custom_colors(i, :), ‘LineStyle’, custom_linestyles{i});
% Only add the label and handle once to the legend
if ~ismember(display_name, legend_labels)
legend_index = legend_index + 1;
plot_handles(legend_index) = h(1); % Store only the first handle
legend_labels{legend_index} = display_name; % Append label
end
end
end
end
% Add labels and title to each subplot
xlabel(ax, ‘Time (s)’, ‘Interpreter’, ‘latex’);
ylabel(ax, ‘$int u_L , mathrm{dz}$’, ‘Interpreter’, ‘latex’);
xlim(ax, [min(tarray), max(tarray)]);
ylim(ax, [0, 2.5e-04]);
% Add subplot numbering and S_{rf} value
title(ax, sprintf(‘(%c) $S_{rf} = %.2f$’, ‘a’ + j – 1, ramp_slope(slope_select(j))), ‘Interpreter’, ‘latex’);
box(ax, ‘on’); % Place a box around the current subplot
% Add inset plots
inset_pos = ax.Position; % Get the position of the current subplot
if j == 1
% The first inset plot on the top left of the first subplot
inset_pos = [inset_pos(1) + 0.1 * inset_pos(3), inset_pos(2) + 0.65 * inset_pos(4), 0.15, 0.15];
else
% Remaining inset plots on the top right of the respective subplots
inset_pos = [inset_pos(1) + 0.6 * inset_pos(3), inset_pos(2) + 0.65 * inset_pos(4), 0.15, 0.15];
end
% Create new axes for inset plots, without attaching them to the main subplot axes
inset_ax = axes(‘Position’, inset_pos); % Create inset axes with adjusted position
hold(inset_ax, ‘on’); % Hold on inset axes to plot multiple lines
% Loop through selected xi values for the inset plots
for i = 1:length(xi_select)
% Find the switching times for the current xi and ramp_slope
transitions = find(switching(:, xi_select(i), slope_select(j)));
if ~isempty(transitions)
% Plot the uxl data in the inset plot
for t_idx = transitions
% Extract the uxl data for the current time point
uxl_data = squeeze(uxl(:, xi_select(i), slope_select(j))); % Dimension: y, xi, ramp_slope
% Plot the data in the inset with color and linestyle
plot(inset_ax, y, uxl_data, ‘LineWidth’, 1.5, …
‘Color’, custom_colors(i, :), ‘LineStyle’, custom_linestyles{i});
end
end
end
% Add labels to inset
xlabel(inset_ax, ‘$z$’, ‘Interpreter’, ‘latex’);
ylabel(inset_ax, ‘$int u_L , mathrm{dz}$’, ‘Interpreter’, ‘latex’);
xlim(inset_ax, [min(y), max(y)]);
hold(inset_ax, ‘off’); % Release hold on the inset axes
end
% Create a global legend (optional, if needed)
lgd = legend(plot_handles, legend_labels, ‘Interpreter’, ‘latex’, ‘NumColumns’, 2);
% Ensure that the entire figure has a box around it
box on; Hi, I am trying to plots an insets plots in aubplots but only the last subplot and inset plots are shown. Please can someone help with this?
% Define xi_select and slope_select for main and inset plots
xi_select = [1, 10, 11, 12];
slope_select = [1, 3, 4, 5, 7, 9];
% Create a tiled layout with 2 rows and 3 columns of subplots
t = tiledlayout(2, 3, ‘TileSpacing’, ‘compact’, ‘Padding’, ‘compact’);
% Define custom colors (green to red gradient)
num_colors = length(xi_select);
custom_colors = [linspace(0, 1, num_colors)’, linspace(1, 0, num_colors)’, zeros(num_colors, 1)];
custom_linestyles = repmat({‘–‘}, 1, num_colors); % All dashed lines
% Initialize arrays for legend
legend_labels = {}; % Cell array to store legend labels
legend_index = 0; % Initialize legend index
plot_handles = []; % Array for storing plot handles
for j = 1:length(slope_select) % Loop through selected ramp_slope
% Create the main subplot
ax = nexttile; % Move to the next tile for each subplot
hold(ax, ‘on’); % Hold on to plot multiple lines in the same subplot
% Loop through selected xi values for the main plots
for i = 1:length(xi_select)
% Find the switching times for the current xi and ramp_slope
transitions = find(switching(:, xi_select(i), slope_select(j)));
if ~isempty(transitions)
% Plot the uxlt data at the switching times for this xi and ramp_slope
for t_idx = transitions
% Extract the uxlt data for the current time point
uxlt_data = squeeze(uxlt(ym, :, xi_select(i), slope_select(j))); % Dimension: y, xi, ramp_slope
% Proper LaTeX syntax for the legend entry, omitting time
display_name = sprintf(‘$\xi=%.2f$’, xi(xi_select(i)));
% Plot the data with specified color and linestyle
h = plot(ax, tarray, uxlt_data, ‘LineWidth’, 1.5, …
‘Color’, custom_colors(i, :), ‘LineStyle’, custom_linestyles{i});
% Only add the label and handle once to the legend
if ~ismember(display_name, legend_labels)
legend_index = legend_index + 1;
plot_handles(legend_index) = h(1); % Store only the first handle
legend_labels{legend_index} = display_name; % Append label
end
end
end
end
% Add labels and title to each subplot
xlabel(ax, ‘Time (s)’, ‘Interpreter’, ‘latex’);
ylabel(ax, ‘$int u_L , mathrm{dz}$’, ‘Interpreter’, ‘latex’);
xlim(ax, [min(tarray), max(tarray)]);
ylim(ax, [0, 2.5e-04]);
% Add subplot numbering and S_{rf} value
title(ax, sprintf(‘(%c) $S_{rf} = %.2f$’, ‘a’ + j – 1, ramp_slope(slope_select(j))), ‘Interpreter’, ‘latex’);
box(ax, ‘on’); % Place a box around the current subplot
% Add inset plots
inset_pos = ax.Position; % Get the position of the current subplot
if j == 1
% The first inset plot on the top left of the first subplot
inset_pos = [inset_pos(1) + 0.1 * inset_pos(3), inset_pos(2) + 0.65 * inset_pos(4), 0.15, 0.15];
else
% Remaining inset plots on the top right of the respective subplots
inset_pos = [inset_pos(1) + 0.6 * inset_pos(3), inset_pos(2) + 0.65 * inset_pos(4), 0.15, 0.15];
end
% Create new axes for inset plots, without attaching them to the main subplot axes
inset_ax = axes(‘Position’, inset_pos); % Create inset axes with adjusted position
hold(inset_ax, ‘on’); % Hold on inset axes to plot multiple lines
% Loop through selected xi values for the inset plots
for i = 1:length(xi_select)
% Find the switching times for the current xi and ramp_slope
transitions = find(switching(:, xi_select(i), slope_select(j)));
if ~isempty(transitions)
% Plot the uxl data in the inset plot
for t_idx = transitions
% Extract the uxl data for the current time point
uxl_data = squeeze(uxl(:, xi_select(i), slope_select(j))); % Dimension: y, xi, ramp_slope
% Plot the data in the inset with color and linestyle
plot(inset_ax, y, uxl_data, ‘LineWidth’, 1.5, …
‘Color’, custom_colors(i, :), ‘LineStyle’, custom_linestyles{i});
end
end
end
% Add labels to inset
xlabel(inset_ax, ‘$z$’, ‘Interpreter’, ‘latex’);
ylabel(inset_ax, ‘$int u_L , mathrm{dz}$’, ‘Interpreter’, ‘latex’);
xlim(inset_ax, [min(y), max(y)]);
hold(inset_ax, ‘off’); % Release hold on the inset axes
end
% Create a global legend (optional, if needed)
lgd = legend(plot_handles, legend_labels, ‘Interpreter’, ‘latex’, ‘NumColumns’, 2);
% Ensure that the entire figure has a box around it
box on; insets, subplots, figures MATLAB Answers — New Questions
How to write code for repetitive process?
Hello.
Given:
Variable components: species_1 and species_2;
Initial values: species_1=1000 g and species_2=200 g;
Process parameters: timecut=2 hour, timecon=1hour, kf=0.1 1/hour
The components are related to each other by a reaction according to the law of mass action:
species_1 -> species_2: kf*species_1
In the time interval 0<=time<=timecut, the mass of the component species_1 decreases while the mass of the component species_2 increases. At the point time=timecut, the masses of the components return to their initial values. Two sawtooth patterns are formed on the charts: one sawtooth on chart for species_1 and another inverted sawtooth on chart for species_2.
Then, during the timecon, the masses of components retain their original values: "shelves" are formed. Codes in the Simbiology Builder:
Trigger: time>=timecut
Event FCNS:
kf=0
species_1=1000
species_2=200
If time>=timecut+timecon and kf=0.1, the mass of the species_1 component decreases and the mass of the species_2 component increases. No saw teeth and shelves are formed.
How should the code be written in Simbiology so that the "tooth-shelf" process are repeated n times?Hello.
Given:
Variable components: species_1 and species_2;
Initial values: species_1=1000 g and species_2=200 g;
Process parameters: timecut=2 hour, timecon=1hour, kf=0.1 1/hour
The components are related to each other by a reaction according to the law of mass action:
species_1 -> species_2: kf*species_1
In the time interval 0<=time<=timecut, the mass of the component species_1 decreases while the mass of the component species_2 increases. At the point time=timecut, the masses of the components return to their initial values. Two sawtooth patterns are formed on the charts: one sawtooth on chart for species_1 and another inverted sawtooth on chart for species_2.
Then, during the timecon, the masses of components retain their original values: "shelves" are formed. Codes in the Simbiology Builder:
Trigger: time>=timecut
Event FCNS:
kf=0
species_1=1000
species_2=200
If time>=timecut+timecon and kf=0.1, the mass of the species_1 component decreases and the mass of the species_2 component increases. No saw teeth and shelves are formed.
How should the code be written in Simbiology so that the "tooth-shelf" process are repeated n times? Hello.
Given:
Variable components: species_1 and species_2;
Initial values: species_1=1000 g and species_2=200 g;
Process parameters: timecut=2 hour, timecon=1hour, kf=0.1 1/hour
The components are related to each other by a reaction according to the law of mass action:
species_1 -> species_2: kf*species_1
In the time interval 0<=time<=timecut, the mass of the component species_1 decreases while the mass of the component species_2 increases. At the point time=timecut, the masses of the components return to their initial values. Two sawtooth patterns are formed on the charts: one sawtooth on chart for species_1 and another inverted sawtooth on chart for species_2.
Then, during the timecon, the masses of components retain their original values: "shelves" are formed. Codes in the Simbiology Builder:
Trigger: time>=timecut
Event FCNS:
kf=0
species_1=1000
species_2=200
If time>=timecut+timecon and kf=0.1, the mass of the species_1 component decreases and the mass of the species_2 component increases. No saw teeth and shelves are formed.
How should the code be written in Simbiology so that the "tooth-shelf" process are repeated n times? programming, cycle MATLAB Answers — New Questions
Check tcpclient connection status
Hi, I’m currently using tcpclient command to establish tcpip communication with an external device (not tcpip() from instrument toolbox).
Sometimes, the connection is not stable and when I write data it returns error: ‘An existing connection was forcibly closed by the remote host’.
Therefore, I want to implement a method to check the connection before I write / read from the connection. However, I just couldn’t find much information regarding tcpclient.
I have attempted the following:
% connect
t=tcpclient(‘172.1.1.102′,50000,’Timeout’,1,’ConnectTimeout’,3);
Here, before running the I deliberately disconnected Ethernet cable just want to test trigger the error:
% My intention: try a write / read to check if an error returns
try
write(t,0);
read(t);
disp(‘send succesfull’);
catch ME
disp(‘connection lost’);
disp(ME.identifier);
end
For the first run ‘An existing connection was forcibly closed by the remote host’ still appears in the command window and the ‘send successful’ message is printed, catch statement is skipped. However, a second run will jump into catch statement though.
If I run the try-catch step by step, when it reaches ‘write(t,0)’ statement it returns the ”An existing … remote host”, and continue to ‘read(t)’ statement, and jumps into catch statement.
I couldn’t quite understand why this happened.
Thanks for your help very much!Hi, I’m currently using tcpclient command to establish tcpip communication with an external device (not tcpip() from instrument toolbox).
Sometimes, the connection is not stable and when I write data it returns error: ‘An existing connection was forcibly closed by the remote host’.
Therefore, I want to implement a method to check the connection before I write / read from the connection. However, I just couldn’t find much information regarding tcpclient.
I have attempted the following:
% connect
t=tcpclient(‘172.1.1.102′,50000,’Timeout’,1,’ConnectTimeout’,3);
Here, before running the I deliberately disconnected Ethernet cable just want to test trigger the error:
% My intention: try a write / read to check if an error returns
try
write(t,0);
read(t);
disp(‘send succesfull’);
catch ME
disp(‘connection lost’);
disp(ME.identifier);
end
For the first run ‘An existing connection was forcibly closed by the remote host’ still appears in the command window and the ‘send successful’ message is printed, catch statement is skipped. However, a second run will jump into catch statement though.
If I run the try-catch step by step, when it reaches ‘write(t,0)’ statement it returns the ”An existing … remote host”, and continue to ‘read(t)’ statement, and jumps into catch statement.
I couldn’t quite understand why this happened.
Thanks for your help very much! Hi, I’m currently using tcpclient command to establish tcpip communication with an external device (not tcpip() from instrument toolbox).
Sometimes, the connection is not stable and when I write data it returns error: ‘An existing connection was forcibly closed by the remote host’.
Therefore, I want to implement a method to check the connection before I write / read from the connection. However, I just couldn’t find much information regarding tcpclient.
I have attempted the following:
% connect
t=tcpclient(‘172.1.1.102′,50000,’Timeout’,1,’ConnectTimeout’,3);
Here, before running the I deliberately disconnected Ethernet cable just want to test trigger the error:
% My intention: try a write / read to check if an error returns
try
write(t,0);
read(t);
disp(‘send succesfull’);
catch ME
disp(‘connection lost’);
disp(ME.identifier);
end
For the first run ‘An existing connection was forcibly closed by the remote host’ still appears in the command window and the ‘send successful’ message is printed, catch statement is skipped. However, a second run will jump into catch statement though.
If I run the try-catch step by step, when it reaches ‘write(t,0)’ statement it returns the ”An existing … remote host”, and continue to ‘read(t)’ statement, and jumps into catch statement.
I couldn’t quite understand why this happened.
Thanks for your help very much! matlab, tcpip, tcpclient, connection MATLAB Answers — New Questions
How to export 500 images in one file
I have around 500 images which I want to export into one .xls .word or .pdf in 3 collums. I tried putting them all in one figure but then they become extremely small. If I create many separete figures by 3, I don´t know how to export them all into one file. I tried putting all of the images into table but then the table doesn´t generate because I run out of memorry. If I were to guess, it most likely tries to put every single value of the picture into a separated cell.
How do I make pictures in the table to be saved in their pictural form?
clear all; clc; close all;
dir_img_AP=dir(‘**/NUSCH*AP/**/*.jpg’);
dir_img_JS=dir(‘**/NUSCH*JS/**/*.jpg’);
dir_img_LZ=dir(‘**/NUSCH*LZ/**/*.jpg’);
n_img_AP=numel(dir_img_AP);
n_img_JS=numel(dir_img_JS);
n_img_LZ=numel(dir_img_LZ);
n_img=max([n_img_AP,n_img_JS,n_img_LZ]);
T=cell(n_img,1);
for i=1:n_img_AP
file_path_AP=[dir_img_AP(i).folder, ‘/’,dir_img_AP(i).name];
filename_AP = dir_img_AP(i).name;
pic_AP = imread(filename_AP);
T{i,1} = pic_AP;
end
for i=1:n_img_JS
file_path_JS=[dir_img_JS(i).folder, ‘/’,dir_img_JS(i).name];
filename_JS = dir_img_JS(i).name;
pic_JS = imread(filename_JS);
T{i,2} = pic_JS;
end
for i=1:n_img_LZ
file_path_LZ=[dir_img_LZ(i).folder, ‘/’,dir_img_LZ(i).name];
filename_LZ = dir_img_LZ(i).name;
pic_LZ = imread(filename_LZ);
T{i,3} = pic_LZ;
end
table=cell2table(T);
arr = table2array(table);
% imshow(arr);
f_name=’pic.xls’;
% writetable(table,f_name)I have around 500 images which I want to export into one .xls .word or .pdf in 3 collums. I tried putting them all in one figure but then they become extremely small. If I create many separete figures by 3, I don´t know how to export them all into one file. I tried putting all of the images into table but then the table doesn´t generate because I run out of memorry. If I were to guess, it most likely tries to put every single value of the picture into a separated cell.
How do I make pictures in the table to be saved in their pictural form?
clear all; clc; close all;
dir_img_AP=dir(‘**/NUSCH*AP/**/*.jpg’);
dir_img_JS=dir(‘**/NUSCH*JS/**/*.jpg’);
dir_img_LZ=dir(‘**/NUSCH*LZ/**/*.jpg’);
n_img_AP=numel(dir_img_AP);
n_img_JS=numel(dir_img_JS);
n_img_LZ=numel(dir_img_LZ);
n_img=max([n_img_AP,n_img_JS,n_img_LZ]);
T=cell(n_img,1);
for i=1:n_img_AP
file_path_AP=[dir_img_AP(i).folder, ‘/’,dir_img_AP(i).name];
filename_AP = dir_img_AP(i).name;
pic_AP = imread(filename_AP);
T{i,1} = pic_AP;
end
for i=1:n_img_JS
file_path_JS=[dir_img_JS(i).folder, ‘/’,dir_img_JS(i).name];
filename_JS = dir_img_JS(i).name;
pic_JS = imread(filename_JS);
T{i,2} = pic_JS;
end
for i=1:n_img_LZ
file_path_LZ=[dir_img_LZ(i).folder, ‘/’,dir_img_LZ(i).name];
filename_LZ = dir_img_LZ(i).name;
pic_LZ = imread(filename_LZ);
T{i,3} = pic_LZ;
end
table=cell2table(T);
arr = table2array(table);
% imshow(arr);
f_name=’pic.xls’;
% writetable(table,f_name) I have around 500 images which I want to export into one .xls .word or .pdf in 3 collums. I tried putting them all in one figure but then they become extremely small. If I create many separete figures by 3, I don´t know how to export them all into one file. I tried putting all of the images into table but then the table doesn´t generate because I run out of memorry. If I were to guess, it most likely tries to put every single value of the picture into a separated cell.
How do I make pictures in the table to be saved in their pictural form?
clear all; clc; close all;
dir_img_AP=dir(‘**/NUSCH*AP/**/*.jpg’);
dir_img_JS=dir(‘**/NUSCH*JS/**/*.jpg’);
dir_img_LZ=dir(‘**/NUSCH*LZ/**/*.jpg’);
n_img_AP=numel(dir_img_AP);
n_img_JS=numel(dir_img_JS);
n_img_LZ=numel(dir_img_LZ);
n_img=max([n_img_AP,n_img_JS,n_img_LZ]);
T=cell(n_img,1);
for i=1:n_img_AP
file_path_AP=[dir_img_AP(i).folder, ‘/’,dir_img_AP(i).name];
filename_AP = dir_img_AP(i).name;
pic_AP = imread(filename_AP);
T{i,1} = pic_AP;
end
for i=1:n_img_JS
file_path_JS=[dir_img_JS(i).folder, ‘/’,dir_img_JS(i).name];
filename_JS = dir_img_JS(i).name;
pic_JS = imread(filename_JS);
T{i,2} = pic_JS;
end
for i=1:n_img_LZ
file_path_LZ=[dir_img_LZ(i).folder, ‘/’,dir_img_LZ(i).name];
filename_LZ = dir_img_LZ(i).name;
pic_LZ = imread(filename_LZ);
T{i,3} = pic_LZ;
end
table=cell2table(T);
arr = table2array(table);
% imshow(arr);
f_name=’pic.xls’;
% writetable(table,f_name) database, export, image MATLAB Answers — New Questions
store images in a table
Hello,
I have three images and want to store them in a table. I wrote this in command line:
dinfo = dir(‘*.jpg’);
T = table();
for K = 1 : length(dinfo)
filename = dinfo(K).name;
filecontent = imread(filename);
T{filename,1} = filecontent;
end
It gives the error:
To assign to or create a variable in a table, the number of rows must match the height of the table.
Secondly, I want to make my three images equal in size, as we have to make the size of variables in rows equal for tables.
Help needed. Thanks in advance.Hello,
I have three images and want to store them in a table. I wrote this in command line:
dinfo = dir(‘*.jpg’);
T = table();
for K = 1 : length(dinfo)
filename = dinfo(K).name;
filecontent = imread(filename);
T{filename,1} = filecontent;
end
It gives the error:
To assign to or create a variable in a table, the number of rows must match the height of the table.
Secondly, I want to make my three images equal in size, as we have to make the size of variables in rows equal for tables.
Help needed. Thanks in advance. Hello,
I have three images and want to store them in a table. I wrote this in command line:
dinfo = dir(‘*.jpg’);
T = table();
for K = 1 : length(dinfo)
filename = dinfo(K).name;
filecontent = imread(filename);
T{filename,1} = filecontent;
end
It gives the error:
To assign to or create a variable in a table, the number of rows must match the height of the table.
Secondly, I want to make my three images equal in size, as we have to make the size of variables in rows equal for tables.
Help needed. Thanks in advance. matlab tables, table, database MATLAB Answers — New Questions
Cannot run kernel – Simulink Desktop Real-time
When I try to use the Desktop-Real-Time/Stream input in the simulink, and start a simulation, it apears a error message like "cannot acess kernel". Why do this happen? How it can be solved? Thanks!
The error message is: "Hardware time cannot be allocated. Real time kernel cannot run"When I try to use the Desktop-Real-Time/Stream input in the simulink, and start a simulation, it apears a error message like "cannot acess kernel". Why do this happen? How it can be solved? Thanks!
The error message is: "Hardware time cannot be allocated. Real time kernel cannot run" When I try to use the Desktop-Real-Time/Stream input in the simulink, and start a simulation, it apears a error message like "cannot acess kernel". Why do this happen? How it can be solved? Thanks!
The error message is: "Hardware time cannot be allocated. Real time kernel cannot run" simulink, kernel MATLAB Answers — New Questions
problem in simulink (FOPID controller)
Derivative of state ‘1’ in block ‘FOPIDC/Fractional PID controller1/Fractional derivative1/Transfer
Fcn1′ at time 3.2188803386168852 is not finite. The simulation will be stopped. There may be a
singularity in the solution. If not, try reducing the step size (either by reducing the fixed step
size or by tightening the error tolerances)
how can I solve this errorDerivative of state ‘1’ in block ‘FOPIDC/Fractional PID controller1/Fractional derivative1/Transfer
Fcn1′ at time 3.2188803386168852 is not finite. The simulation will be stopped. There may be a
singularity in the solution. If not, try reducing the step size (either by reducing the fixed step
size or by tightening the error tolerances)
how can I solve this error Derivative of state ‘1’ in block ‘FOPIDC/Fractional PID controller1/Fractional derivative1/Transfer
Fcn1′ at time 3.2188803386168852 is not finite. The simulation will be stopped. There may be a
singularity in the solution. If not, try reducing the step size (either by reducing the fixed step
size or by tightening the error tolerances)
how can I solve this error fopid MATLAB Answers — New Questions
How to properly make a circular histogram?
I have data points which are the angle and distance around a central point. I would like to make a histogram of these points so I can visualise their distribution and also perform some analyses on their density etc.
For now, I make a 2D histogram, treating the data points as if they are cartesian X,Y coordinates. I then transform the bin centers into polar coordinates and replot the data, like this:
% create data points
theta = normrnd(0,0.5,1000,1);
rad = 100.*rand(1000,1);
figure
subplot(1,3,1)
polarscatter(theta,rad,10,’k’,’filled’,’o’)
title(‘data points’)
% prepare bins
theta_bins = linspace(-pi,pi,120);
rad_bins = 0:5:100;
% ‘normal’ histogram
f = histcounts2(rad,theta,rad_bins,theta_bins);
subplot(1,3,2)
imagesc(f)
daspect([1 1 1])
title(‘histogram in cartesian coordinates’)
% transform bin coordinates
[theta,rad] = meshgrid(linspace(min(theta_bins),max(theta_bins),length(theta_bins)-1),linspace(min(rad_bins),max(rad_bins),length(rad_bins)-1));
[X,Y] = pol2cart(theta,rad);
subplot(1,3,3)
s = surf(X,Y,f);
s.EdgeColor = ‘none’;
view(0,90);
daspect([1 1 1])
axis xy
title(‘histogram in polar coordinates’)
However, the resulting histogram is not really ideal – the bins are not homogeneous because they get larger as the radius increases. This is due to the fact that I made the histogram in a cartesian reference frame.
I was wondering if there is a better way to go about this? Some sort of circular histogram with circular bands of triangular bins? Or hexagonal bins? Can anyone suggest anything?
Thanks for any help.I have data points which are the angle and distance around a central point. I would like to make a histogram of these points so I can visualise their distribution and also perform some analyses on their density etc.
For now, I make a 2D histogram, treating the data points as if they are cartesian X,Y coordinates. I then transform the bin centers into polar coordinates and replot the data, like this:
% create data points
theta = normrnd(0,0.5,1000,1);
rad = 100.*rand(1000,1);
figure
subplot(1,3,1)
polarscatter(theta,rad,10,’k’,’filled’,’o’)
title(‘data points’)
% prepare bins
theta_bins = linspace(-pi,pi,120);
rad_bins = 0:5:100;
% ‘normal’ histogram
f = histcounts2(rad,theta,rad_bins,theta_bins);
subplot(1,3,2)
imagesc(f)
daspect([1 1 1])
title(‘histogram in cartesian coordinates’)
% transform bin coordinates
[theta,rad] = meshgrid(linspace(min(theta_bins),max(theta_bins),length(theta_bins)-1),linspace(min(rad_bins),max(rad_bins),length(rad_bins)-1));
[X,Y] = pol2cart(theta,rad);
subplot(1,3,3)
s = surf(X,Y,f);
s.EdgeColor = ‘none’;
view(0,90);
daspect([1 1 1])
axis xy
title(‘histogram in polar coordinates’)
However, the resulting histogram is not really ideal – the bins are not homogeneous because they get larger as the radius increases. This is due to the fact that I made the histogram in a cartesian reference frame.
I was wondering if there is a better way to go about this? Some sort of circular histogram with circular bands of triangular bins? Or hexagonal bins? Can anyone suggest anything?
Thanks for any help. I have data points which are the angle and distance around a central point. I would like to make a histogram of these points so I can visualise their distribution and also perform some analyses on their density etc.
For now, I make a 2D histogram, treating the data points as if they are cartesian X,Y coordinates. I then transform the bin centers into polar coordinates and replot the data, like this:
% create data points
theta = normrnd(0,0.5,1000,1);
rad = 100.*rand(1000,1);
figure
subplot(1,3,1)
polarscatter(theta,rad,10,’k’,’filled’,’o’)
title(‘data points’)
% prepare bins
theta_bins = linspace(-pi,pi,120);
rad_bins = 0:5:100;
% ‘normal’ histogram
f = histcounts2(rad,theta,rad_bins,theta_bins);
subplot(1,3,2)
imagesc(f)
daspect([1 1 1])
title(‘histogram in cartesian coordinates’)
% transform bin coordinates
[theta,rad] = meshgrid(linspace(min(theta_bins),max(theta_bins),length(theta_bins)-1),linspace(min(rad_bins),max(rad_bins),length(rad_bins)-1));
[X,Y] = pol2cart(theta,rad);
subplot(1,3,3)
s = surf(X,Y,f);
s.EdgeColor = ‘none’;
view(0,90);
daspect([1 1 1])
axis xy
title(‘histogram in polar coordinates’)
However, the resulting histogram is not really ideal – the bins are not homogeneous because they get larger as the radius increases. This is due to the fact that I made the histogram in a cartesian reference frame.
I was wondering if there is a better way to go about this? Some sort of circular histogram with circular bands of triangular bins? Or hexagonal bins? Can anyone suggest anything?
Thanks for any help. circular, histogram, polar, visualisation MATLAB Answers — New Questions
How to define input parameters for BytesAvailableFcn (tcpclient)
Hy all,
my problem concerns the use of input arguments when I define the BytesAvailableFcn of a tcpclient connection.
I create a tcpclient connection:
t = tcpclient(‘address’, port);
And I send a request to the server (which starts automatically to send data):
write( t, ‘request’ );
I want to have a callback function triggered by a bytes available event:
configureCallback( t, "terminator", @MyCallbackFcn );
MyCallbackFcn is written in a separated MyCallbackFcn.m file. The callback function MyCallbackFcn is triggeredd whenever a terminator is available to be read from the remote host specified by the TCP/IP client.
At the moment, MyCallbackFcn uses global parameters (var1, var2, etc.) defined in the main program:
function MyCallbackFcn( src, ~ )
global var1 var2
…
end
This algorithm works well. But in order to avoid the use of global parameters, I would like to define input parameters for MyCallbackFcn fonction. My problems start here, because I do not find the right form to write:
the definition of the callback function in the main program : configureCallback( t,…
the function MyCallbackFcn in the MyCallbackFcn.m file
Thank you in advance for your help.
RaphaëlHy all,
my problem concerns the use of input arguments when I define the BytesAvailableFcn of a tcpclient connection.
I create a tcpclient connection:
t = tcpclient(‘address’, port);
And I send a request to the server (which starts automatically to send data):
write( t, ‘request’ );
I want to have a callback function triggered by a bytes available event:
configureCallback( t, "terminator", @MyCallbackFcn );
MyCallbackFcn is written in a separated MyCallbackFcn.m file. The callback function MyCallbackFcn is triggeredd whenever a terminator is available to be read from the remote host specified by the TCP/IP client.
At the moment, MyCallbackFcn uses global parameters (var1, var2, etc.) defined in the main program:
function MyCallbackFcn( src, ~ )
global var1 var2
…
end
This algorithm works well. But in order to avoid the use of global parameters, I would like to define input parameters for MyCallbackFcn fonction. My problems start here, because I do not find the right form to write:
the definition of the callback function in the main program : configureCallback( t,…
the function MyCallbackFcn in the MyCallbackFcn.m file
Thank you in advance for your help.
Raphaël Hy all,
my problem concerns the use of input arguments when I define the BytesAvailableFcn of a tcpclient connection.
I create a tcpclient connection:
t = tcpclient(‘address’, port);
And I send a request to the server (which starts automatically to send data):
write( t, ‘request’ );
I want to have a callback function triggered by a bytes available event:
configureCallback( t, "terminator", @MyCallbackFcn );
MyCallbackFcn is written in a separated MyCallbackFcn.m file. The callback function MyCallbackFcn is triggeredd whenever a terminator is available to be read from the remote host specified by the TCP/IP client.
At the moment, MyCallbackFcn uses global parameters (var1, var2, etc.) defined in the main program:
function MyCallbackFcn( src, ~ )
global var1 var2
…
end
This algorithm works well. But in order to avoid the use of global parameters, I would like to define input parameters for MyCallbackFcn fonction. My problems start here, because I do not find the right form to write:
the definition of the callback function in the main program : configureCallback( t,…
the function MyCallbackFcn in the MyCallbackFcn.m file
Thank you in advance for your help.
Raphaël tcpclient, bytesavailablefcn, input parameters MATLAB Answers — New Questions
MATLAB Coder: C Version Much Slower Than Mex Version
I used MATLAB Coder to turn my MATLAB code into C code and expected a great decrease in run time, but instead found that my C code runs much slower than both the MATLAB code and the mex code. Over 5 tests, I get the following:
Tthe MATLAB code took 77.48 seconds on average.
The mex version running in MATLAB took 46.27 seconds on average.
The generated C code took 262.35 seconds on average.
All three versions of the code produces the exact same output, so I am confident that each version is working properly. I am running the MATLAB and mex versions in R2023a and the C version in Debian 11 (bullseye) in a docker container. The cmake command I am running is
cmake -DCMAKE_BUILD_TYPE=Release ..
and my understanding is that this enables the C compiler optimisations, but I’m unsure if there are further optimisations I can enable. Before specifying the build type as release, my C code ran about 90 seconds slower still (~350s), which is horrendous compared to the MATLAB/mex version.
These are the settings I am generating my code with:
The full settings I used are attached in config.mat but they are almost all just the default settings.
My understanding is that MATLAB does some computations in parallel automatically, while the generated C code doesn’t, so I tried turning on automatic parallelisation in the generated code. This only made the code run slower, however. I’m not sure how the automatic paralellisation works, but when I manually tried to parallelise parts of my code, it also did not run faster, so I did not really expect this to improve anything.
I’m just really unsure why the C version runs so much slower than even the mex version, which I expected to be similar or worse than the C version. Are there settings I can tweak in Coder? Are there further optimisations I can enable on the Linux side of things? If this is normal behaviour, what is the explanation for the discrepency between C and mex?I used MATLAB Coder to turn my MATLAB code into C code and expected a great decrease in run time, but instead found that my C code runs much slower than both the MATLAB code and the mex code. Over 5 tests, I get the following:
Tthe MATLAB code took 77.48 seconds on average.
The mex version running in MATLAB took 46.27 seconds on average.
The generated C code took 262.35 seconds on average.
All three versions of the code produces the exact same output, so I am confident that each version is working properly. I am running the MATLAB and mex versions in R2023a and the C version in Debian 11 (bullseye) in a docker container. The cmake command I am running is
cmake -DCMAKE_BUILD_TYPE=Release ..
and my understanding is that this enables the C compiler optimisations, but I’m unsure if there are further optimisations I can enable. Before specifying the build type as release, my C code ran about 90 seconds slower still (~350s), which is horrendous compared to the MATLAB/mex version.
These are the settings I am generating my code with:
The full settings I used are attached in config.mat but they are almost all just the default settings.
My understanding is that MATLAB does some computations in parallel automatically, while the generated C code doesn’t, so I tried turning on automatic parallelisation in the generated code. This only made the code run slower, however. I’m not sure how the automatic paralellisation works, but when I manually tried to parallelise parts of my code, it also did not run faster, so I did not really expect this to improve anything.
I’m just really unsure why the C version runs so much slower than even the mex version, which I expected to be similar or worse than the C version. Are there settings I can tweak in Coder? Are there further optimisations I can enable on the Linux side of things? If this is normal behaviour, what is the explanation for the discrepency between C and mex? I used MATLAB Coder to turn my MATLAB code into C code and expected a great decrease in run time, but instead found that my C code runs much slower than both the MATLAB code and the mex code. Over 5 tests, I get the following:
Tthe MATLAB code took 77.48 seconds on average.
The mex version running in MATLAB took 46.27 seconds on average.
The generated C code took 262.35 seconds on average.
All three versions of the code produces the exact same output, so I am confident that each version is working properly. I am running the MATLAB and mex versions in R2023a and the C version in Debian 11 (bullseye) in a docker container. The cmake command I am running is
cmake -DCMAKE_BUILD_TYPE=Release ..
and my understanding is that this enables the C compiler optimisations, but I’m unsure if there are further optimisations I can enable. Before specifying the build type as release, my C code ran about 90 seconds slower still (~350s), which is horrendous compared to the MATLAB/mex version.
These are the settings I am generating my code with:
The full settings I used are attached in config.mat but they are almost all just the default settings.
My understanding is that MATLAB does some computations in parallel automatically, while the generated C code doesn’t, so I tried turning on automatic parallelisation in the generated code. This only made the code run slower, however. I’m not sure how the automatic paralellisation works, but when I manually tried to parallelise parts of my code, it also did not run faster, so I did not really expect this to improve anything.
I’m just really unsure why the C version runs so much slower than even the mex version, which I expected to be similar or worse than the C version. Are there settings I can tweak in Coder? Are there further optimisations I can enable on the Linux side of things? If this is normal behaviour, what is the explanation for the discrepency between C and mex? gcc, mex, optimisation, optimization, linux, cmake MATLAB Answers — New Questions
Add 3 to just the odd-index elements
I am using this help-yourself
http://www.facstaff.bucknell.edu/maneval/help211/exercises.html
And have a question regarding
2. Let x = [2 5 1 6].
b. Add 3 to just the odd-index elements
They give the answer as
b = x(1:2:end) + 3
but that makes a new matrix with just two numbers in it.
Like so:
"b =
21 20
"
Is the question or the answer wrong?I am using this help-yourself
http://www.facstaff.bucknell.edu/maneval/help211/exercises.html
And have a question regarding
2. Let x = [2 5 1 6].
b. Add 3 to just the odd-index elements
They give the answer as
b = x(1:2:end) + 3
but that makes a new matrix with just two numbers in it.
Like so:
"b =
21 20
"
Is the question or the answer wrong? I am using this help-yourself
http://www.facstaff.bucknell.edu/maneval/help211/exercises.html
And have a question regarding
2. Let x = [2 5 1 6].
b. Add 3 to just the odd-index elements
They give the answer as
b = x(1:2:end) + 3
but that makes a new matrix with just two numbers in it.
Like so:
"b =
21 20
"
Is the question or the answer wrong? odd matrix numbers MATLAB Answers — New Questions
How do I install Statistics and Machine Learning Toolbox into an existing installation of MATLAB?
I have called one function in which random is used but an error comes up ‘random’ requires Statistics and Machine Learning Toolbox. I click on this link and it asks to install it. I click on it and I see this window "Your administrator has restricted your download access to this MathWorks product".I have called one function in which random is used but an error comes up ‘random’ requires Statistics and Machine Learning Toolbox. I click on this link and it asks to install it. I click on it and I see this window "Your administrator has restricted your download access to this MathWorks product". I have called one function in which random is used but an error comes up ‘random’ requires Statistics and Machine Learning Toolbox. I click on this link and it asks to install it. I click on it and I see this window "Your administrator has restricted your download access to this MathWorks product". statistics, machine, learning toolbox MATLAB Answers — New Questions