Category: Matlab
Category Archives: Matlab
How to plot the graph for the given RK 4th order step method
syms t x
g=(13950-x)/18.75
f=@(t,x) eval(g);
x0=560;
t0=0;
t=15;
h=1;
for c=1:15
k1=h*f(t0,x0);
k2=h*f(t0+(h/2),x0+(k1/2));
k3=h*f(t0+(h/2),x0+(k2/2));
k4=h*f(t0+h,x0+k3);
x=x0+(1/6)*(k1+(2*k2)+(2*k3)+k4);
fprintf(‘x= %0.4f n’,x)
t0=t0+h;
x0=x;
endsyms t x
g=(13950-x)/18.75
f=@(t,x) eval(g);
x0=560;
t0=0;
t=15;
h=1;
for c=1:15
k1=h*f(t0,x0);
k2=h*f(t0+(h/2),x0+(k1/2));
k3=h*f(t0+(h/2),x0+(k2/2));
k4=h*f(t0+h,x0+k3);
x=x0+(1/6)*(k1+(2*k2)+(2*k3)+k4);
fprintf(‘x= %0.4f n’,x)
t0=t0+h;
x0=x;
end syms t x
g=(13950-x)/18.75
f=@(t,x) eval(g);
x0=560;
t0=0;
t=15;
h=1;
for c=1:15
k1=h*f(t0,x0);
k2=h*f(t0+(h/2),x0+(k1/2));
k3=h*f(t0+(h/2),x0+(k2/2));
k4=h*f(t0+h,x0+k3);
x=x0+(1/6)*(k1+(2*k2)+(2*k3)+k4);
fprintf(‘x= %0.4f n’,x)
t0=t0+h;
x0=x;
end #rkmethod, for loop, #plot graph MATLAB Answers — New Questions
Supply partially complete Jacobian for fsolve()
Hello,
I was wondering if I could supply an incomplete Jacobian to matlab fsolve. I am able to analytically solve for the gradients of some of the constraint equation, but there are some elements that are highly nonlinear and nontrivial to find.
Because of this, I was wondering if I could just partially supply the Jacobian and let MATLAB use its own numerical methods for the missing ones?Hello,
I was wondering if I could supply an incomplete Jacobian to matlab fsolve. I am able to analytically solve for the gradients of some of the constraint equation, but there are some elements that are highly nonlinear and nontrivial to find.
Because of this, I was wondering if I could just partially supply the Jacobian and let MATLAB use its own numerical methods for the missing ones? Hello,
I was wondering if I could supply an incomplete Jacobian to matlab fsolve. I am able to analytically solve for the gradients of some of the constraint equation, but there are some elements that are highly nonlinear and nontrivial to find.
Because of this, I was wondering if I could just partially supply the Jacobian and let MATLAB use its own numerical methods for the missing ones? fsolve, jacobian MATLAB Answers — New Questions
Error : Unable to use a value of type optim.problemdef.OptimizationVariable as an index.
Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance!Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance! Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance! optimization, solve, error MATLAB Answers — New Questions
How to fix the problem of fetching the simulink block from the customized library in the matlab app designer using matlab app designer code?
Here, we are running all the codes shown below in the matlab app designer.
Initialy, we have taken a simulink block from the existing matlab library using this code, and it run successfully.
open_system(new_system(‘myModel’));
add_block(‘simulink/Commonly Used Blocks/Constant’,’myModel/Constant’);
set_param(‘myModel/Constant’,’position’,[140,80,180,120]);
But, on applying the same code to select the simulink block from our customized library, it shows the following error.
open_system(new_system(‘myModel’));
add_block(‘simulink/mylib/Constant’,’myModel/Constant’);
set_param(‘myModel/Constant’,’position’,[220,80,260,120]);
So, the command window in matlab shows following error message.
Error using app2/MylibraryButtonPushed
There is no block named ‘simulink/mylib/Constant’
Error in matlab.apps.AppBase>@(source,event)executeCallback(ams,app,callback,requiresEventData,event) (line 62)
newCallback = @(source, event)executeCallback(ams, … – Show complete stack trace
Error while evaluating Button PrivateButtonPushedFcn.Here, we are running all the codes shown below in the matlab app designer.
Initialy, we have taken a simulink block from the existing matlab library using this code, and it run successfully.
open_system(new_system(‘myModel’));
add_block(‘simulink/Commonly Used Blocks/Constant’,’myModel/Constant’);
set_param(‘myModel/Constant’,’position’,[140,80,180,120]);
But, on applying the same code to select the simulink block from our customized library, it shows the following error.
open_system(new_system(‘myModel’));
add_block(‘simulink/mylib/Constant’,’myModel/Constant’);
set_param(‘myModel/Constant’,’position’,[220,80,260,120]);
So, the command window in matlab shows following error message.
Error using app2/MylibraryButtonPushed
There is no block named ‘simulink/mylib/Constant’
Error in matlab.apps.AppBase>@(source,event)executeCallback(ams,app,callback,requiresEventData,event) (line 62)
newCallback = @(source, event)executeCallback(ams, … – Show complete stack trace
Error while evaluating Button PrivateButtonPushedFcn. Here, we are running all the codes shown below in the matlab app designer.
Initialy, we have taken a simulink block from the existing matlab library using this code, and it run successfully.
open_system(new_system(‘myModel’));
add_block(‘simulink/Commonly Used Blocks/Constant’,’myModel/Constant’);
set_param(‘myModel/Constant’,’position’,[140,80,180,120]);
But, on applying the same code to select the simulink block from our customized library, it shows the following error.
open_system(new_system(‘myModel’));
add_block(‘simulink/mylib/Constant’,’myModel/Constant’);
set_param(‘myModel/Constant’,’position’,[220,80,260,120]);
So, the command window in matlab shows following error message.
Error using app2/MylibraryButtonPushed
There is no block named ‘simulink/mylib/Constant’
Error in matlab.apps.AppBase>@(source,event)executeCallback(ams,app,callback,requiresEventData,event) (line 62)
newCallback = @(source, event)executeCallback(ams, … – Show complete stack trace
Error while evaluating Button PrivateButtonPushedFcn. matlab code, matlab, simulink, app designer, matlab gui MATLAB Answers — New Questions
Sum of following elements in array
Is there a faster way to do the following
s = rand(1, 10);
sum_following = zeros(length(s), 1);
for i = 1:length(s)-1
sum_following(i) = sum(s(i+1:end), ‘all’);
end
without doing
sum_following = sum(s,"all") – cumsum(s);
?Is there a faster way to do the following
s = rand(1, 10);
sum_following = zeros(length(s), 1);
for i = 1:length(s)-1
sum_following(i) = sum(s(i+1:end), ‘all’);
end
without doing
sum_following = sum(s,"all") – cumsum(s);
? Is there a faster way to do the following
s = rand(1, 10);
sum_following = zeros(length(s), 1);
for i = 1:length(s)-1
sum_following(i) = sum(s(i+1:end), ‘all’);
end
without doing
sum_following = sum(s,"all") – cumsum(s);
? arrays, sum, cumsum MATLAB Answers — New Questions
CIC decimation output is strange (Output word length and negative fractional length)
I’m implementing fixed point CIC decimation filter with following requirements —
Decimation factor: 20
Number of CIC stages: 4
Input and output bit width of the CIC: Signed 12-bit
Based on the above requirement, I created a CIC filter
cicDecimOut = dsp.CICDecimator(DecimationFactor=20,…
NumSections=4,…
FixedPointDataType="Specify word lengths",…
SectionWordLengths=12,…
OutputWordLength=12);
As an input, 12-bit signed data generated as follow.
x = randi([-2048 2047], 100000, 1);
in = fi(x,1,12);
Now the singned 12-bit input data plug-in to the CIC decimation filter.
out = cicDecimOut(in)
However, checking the out shows the following at the end,
Two questions I have —
I was expecting signed 12-bit output as I set the OutputWordLength=12. However, out is much larger than 12-bit range. Why this happened. Not sure I was missing something. How could I fix this?
FractionLength is a negative value (-18). Can this be 0 as I wanted to see signed 12-bit? How could I compare this out with the values from the real RTL implementation?I’m implementing fixed point CIC decimation filter with following requirements —
Decimation factor: 20
Number of CIC stages: 4
Input and output bit width of the CIC: Signed 12-bit
Based on the above requirement, I created a CIC filter
cicDecimOut = dsp.CICDecimator(DecimationFactor=20,…
NumSections=4,…
FixedPointDataType="Specify word lengths",…
SectionWordLengths=12,…
OutputWordLength=12);
As an input, 12-bit signed data generated as follow.
x = randi([-2048 2047], 100000, 1);
in = fi(x,1,12);
Now the singned 12-bit input data plug-in to the CIC decimation filter.
out = cicDecimOut(in)
However, checking the out shows the following at the end,
Two questions I have —
I was expecting signed 12-bit output as I set the OutputWordLength=12. However, out is much larger than 12-bit range. Why this happened. Not sure I was missing something. How could I fix this?
FractionLength is a negative value (-18). Can this be 0 as I wanted to see signed 12-bit? How could I compare this out with the values from the real RTL implementation? I’m implementing fixed point CIC decimation filter with following requirements —
Decimation factor: 20
Number of CIC stages: 4
Input and output bit width of the CIC: Signed 12-bit
Based on the above requirement, I created a CIC filter
cicDecimOut = dsp.CICDecimator(DecimationFactor=20,…
NumSections=4,…
FixedPointDataType="Specify word lengths",…
SectionWordLengths=12,…
OutputWordLength=12);
As an input, 12-bit signed data generated as follow.
x = randi([-2048 2047], 100000, 1);
in = fi(x,1,12);
Now the singned 12-bit input data plug-in to the CIC decimation filter.
out = cicDecimOut(in)
However, checking the out shows the following at the end,
Two questions I have —
I was expecting signed 12-bit output as I set the OutputWordLength=12. However, out is much larger than 12-bit range. Why this happened. Not sure I was missing something. How could I fix this?
FractionLength is a negative value (-18). Can this be 0 as I wanted to see signed 12-bit? How could I compare this out with the values from the real RTL implementation? cic, output word length, fractional word length, fixed-point MATLAB Answers — New Questions
Why are my variables saving only Nan entries?
Cal = struct;
Cal.data = readtable(‘Lab_4_Data.txt’);
Cal.data_uE1 = Cal.data.Var3;
Cal.data_uE2 = Cal.data.Var4;
Cal.data_uE3 = Cal.data.Var5;
Cal.data_E1 = Cal.data_uE1 * 1000000;
Cal.data_E2 = Cal.data_uE2 * 1000000;
Cal.data_E3 = Cal.data_uE3 * 1000000;
masses = [0 50 100 200 300 500]; % grams
xN = (masses ./ 1000) * 9.81; % in newtons
% Calculate shear strain (𝛾xy)
Cal.data_gamma_xy = 2 * Cal.data_E2 – (Cal.data_E1 + Cal.data_E3);
% Calculate principal strains (Ɛ1, Ɛ2, Ɛ3)
Cal.data_epsilon_1 = Cal.data_E1;
Cal.data_epsilon_2 = 0.5 * Cal.data_gamma_xy;
Cal.data_epsilon_3 = Cal.data_E3;
% Calculate Poisson’s ratio (v)
Cal.data_nu = abs(Cal.data_epsilon_2) ./ Cal.data_epsilon_1;
% Calculate angle of rotation (𝜃𝜃p)
Cal.data_theta_p = atand(Cal.data_gamma_xy ./ (Cal.data_epsilon_1 – Cal.data_epsilon_3));
% Calculate principal stresses (Txx, Tyy)
E = 69000; % Young’s Modulus for aluminum in MPa
Cal.data_Txx = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_1 + Cal.data_nu .* Cal.data_epsilon_2);
Cal.data_Tyy = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_2 + Cal.data_nu .* Cal.data_epsilon_1);
% Calculate longitudinal stress from the beam flexure equation
P = xN; % applied load in Newtons
L = 0.241; % length of the beam in meters (replace with your actual value)
b = 0.025; % width of the beam in meters (replace with your actual value)
h = 0.00379; % thickness of the beam in meters (replace with your actual value)
c = h / 2;
% distance between gage’s mounting line and dent at the end of the beam in meters
L_adjusted = 0.051;
I = (b * h^3) / 12;
Cal.data_sigma_L = (6 * P * L_adjusted) / (b * h^2);
% Calculate load cell calibration factor
Calibration_Factor = max(abs(Cal.data_epsilon_1)) / max(P);
% Plot 1: Principal Strains vs. Applied Load
figure;
plot(xN, Cal.data_epsilon_1(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ1’);
hold on;
plot(xN, Cal.data_epsilon_2(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ2’);
plot(xN, Cal.data_epsilon_3(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ3’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Strains (muepsilon)’);
title(‘Principal Strains vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 2: Principal Stresses vs. Applied Load
figure;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Txx’);
hold on;
plot(xN, Cal.data_Tyy(1:6), ‘-o’, ‘DisplayName’, ‘Tyy’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Stresses (MPa)’);
title(‘Principal Stresses vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 3: Comparison of Measured and Theoretical Longitudinal Stress
figure;
plot(xN, Cal.data_sigma_L(1:6), ‘-o’, ‘DisplayName’, ‘Measured Longitudinal Stress’);
hold on;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Theoretical Longitudinal Stress’);
xlabel(‘Applied Load (N)’);
ylabel(‘Stress (MPa)’);
title(‘Comparison of Measured and Theoretical Longitudinal Stress’);
legend(‘Location’, ‘Best’);
grid on;
% Display Load Cell Calibration Factor
disp(‘Load Cell Calibration Factor (N/Ɛ):’);
disp(Calibration_Factor);
The .txt file is attached.
This code runs, however the variables data_nu, data_theta_p, data_Txx, and data_Tyy within the Cal struct all have Nan values. All other created variables contain the correct data pulled from the .txt file. Why is this happening?Cal = struct;
Cal.data = readtable(‘Lab_4_Data.txt’);
Cal.data_uE1 = Cal.data.Var3;
Cal.data_uE2 = Cal.data.Var4;
Cal.data_uE3 = Cal.data.Var5;
Cal.data_E1 = Cal.data_uE1 * 1000000;
Cal.data_E2 = Cal.data_uE2 * 1000000;
Cal.data_E3 = Cal.data_uE3 * 1000000;
masses = [0 50 100 200 300 500]; % grams
xN = (masses ./ 1000) * 9.81; % in newtons
% Calculate shear strain (𝛾xy)
Cal.data_gamma_xy = 2 * Cal.data_E2 – (Cal.data_E1 + Cal.data_E3);
% Calculate principal strains (Ɛ1, Ɛ2, Ɛ3)
Cal.data_epsilon_1 = Cal.data_E1;
Cal.data_epsilon_2 = 0.5 * Cal.data_gamma_xy;
Cal.data_epsilon_3 = Cal.data_E3;
% Calculate Poisson’s ratio (v)
Cal.data_nu = abs(Cal.data_epsilon_2) ./ Cal.data_epsilon_1;
% Calculate angle of rotation (𝜃𝜃p)
Cal.data_theta_p = atand(Cal.data_gamma_xy ./ (Cal.data_epsilon_1 – Cal.data_epsilon_3));
% Calculate principal stresses (Txx, Tyy)
E = 69000; % Young’s Modulus for aluminum in MPa
Cal.data_Txx = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_1 + Cal.data_nu .* Cal.data_epsilon_2);
Cal.data_Tyy = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_2 + Cal.data_nu .* Cal.data_epsilon_1);
% Calculate longitudinal stress from the beam flexure equation
P = xN; % applied load in Newtons
L = 0.241; % length of the beam in meters (replace with your actual value)
b = 0.025; % width of the beam in meters (replace with your actual value)
h = 0.00379; % thickness of the beam in meters (replace with your actual value)
c = h / 2;
% distance between gage’s mounting line and dent at the end of the beam in meters
L_adjusted = 0.051;
I = (b * h^3) / 12;
Cal.data_sigma_L = (6 * P * L_adjusted) / (b * h^2);
% Calculate load cell calibration factor
Calibration_Factor = max(abs(Cal.data_epsilon_1)) / max(P);
% Plot 1: Principal Strains vs. Applied Load
figure;
plot(xN, Cal.data_epsilon_1(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ1’);
hold on;
plot(xN, Cal.data_epsilon_2(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ2’);
plot(xN, Cal.data_epsilon_3(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ3’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Strains (muepsilon)’);
title(‘Principal Strains vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 2: Principal Stresses vs. Applied Load
figure;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Txx’);
hold on;
plot(xN, Cal.data_Tyy(1:6), ‘-o’, ‘DisplayName’, ‘Tyy’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Stresses (MPa)’);
title(‘Principal Stresses vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 3: Comparison of Measured and Theoretical Longitudinal Stress
figure;
plot(xN, Cal.data_sigma_L(1:6), ‘-o’, ‘DisplayName’, ‘Measured Longitudinal Stress’);
hold on;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Theoretical Longitudinal Stress’);
xlabel(‘Applied Load (N)’);
ylabel(‘Stress (MPa)’);
title(‘Comparison of Measured and Theoretical Longitudinal Stress’);
legend(‘Location’, ‘Best’);
grid on;
% Display Load Cell Calibration Factor
disp(‘Load Cell Calibration Factor (N/Ɛ):’);
disp(Calibration_Factor);
The .txt file is attached.
This code runs, however the variables data_nu, data_theta_p, data_Txx, and data_Tyy within the Cal struct all have Nan values. All other created variables contain the correct data pulled from the .txt file. Why is this happening? Cal = struct;
Cal.data = readtable(‘Lab_4_Data.txt’);
Cal.data_uE1 = Cal.data.Var3;
Cal.data_uE2 = Cal.data.Var4;
Cal.data_uE3 = Cal.data.Var5;
Cal.data_E1 = Cal.data_uE1 * 1000000;
Cal.data_E2 = Cal.data_uE2 * 1000000;
Cal.data_E3 = Cal.data_uE3 * 1000000;
masses = [0 50 100 200 300 500]; % grams
xN = (masses ./ 1000) * 9.81; % in newtons
% Calculate shear strain (𝛾xy)
Cal.data_gamma_xy = 2 * Cal.data_E2 – (Cal.data_E1 + Cal.data_E3);
% Calculate principal strains (Ɛ1, Ɛ2, Ɛ3)
Cal.data_epsilon_1 = Cal.data_E1;
Cal.data_epsilon_2 = 0.5 * Cal.data_gamma_xy;
Cal.data_epsilon_3 = Cal.data_E3;
% Calculate Poisson’s ratio (v)
Cal.data_nu = abs(Cal.data_epsilon_2) ./ Cal.data_epsilon_1;
% Calculate angle of rotation (𝜃𝜃p)
Cal.data_theta_p = atand(Cal.data_gamma_xy ./ (Cal.data_epsilon_1 – Cal.data_epsilon_3));
% Calculate principal stresses (Txx, Tyy)
E = 69000; % Young’s Modulus for aluminum in MPa
Cal.data_Txx = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_1 + Cal.data_nu .* Cal.data_epsilon_2);
Cal.data_Tyy = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_2 + Cal.data_nu .* Cal.data_epsilon_1);
% Calculate longitudinal stress from the beam flexure equation
P = xN; % applied load in Newtons
L = 0.241; % length of the beam in meters (replace with your actual value)
b = 0.025; % width of the beam in meters (replace with your actual value)
h = 0.00379; % thickness of the beam in meters (replace with your actual value)
c = h / 2;
% distance between gage’s mounting line and dent at the end of the beam in meters
L_adjusted = 0.051;
I = (b * h^3) / 12;
Cal.data_sigma_L = (6 * P * L_adjusted) / (b * h^2);
% Calculate load cell calibration factor
Calibration_Factor = max(abs(Cal.data_epsilon_1)) / max(P);
% Plot 1: Principal Strains vs. Applied Load
figure;
plot(xN, Cal.data_epsilon_1(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ1’);
hold on;
plot(xN, Cal.data_epsilon_2(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ2’);
plot(xN, Cal.data_epsilon_3(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ3’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Strains (muepsilon)’);
title(‘Principal Strains vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 2: Principal Stresses vs. Applied Load
figure;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Txx’);
hold on;
plot(xN, Cal.data_Tyy(1:6), ‘-o’, ‘DisplayName’, ‘Tyy’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Stresses (MPa)’);
title(‘Principal Stresses vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 3: Comparison of Measured and Theoretical Longitudinal Stress
figure;
plot(xN, Cal.data_sigma_L(1:6), ‘-o’, ‘DisplayName’, ‘Measured Longitudinal Stress’);
hold on;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Theoretical Longitudinal Stress’);
xlabel(‘Applied Load (N)’);
ylabel(‘Stress (MPa)’);
title(‘Comparison of Measured and Theoretical Longitudinal Stress’);
legend(‘Location’, ‘Best’);
grid on;
% Display Load Cell Calibration Factor
disp(‘Load Cell Calibration Factor (N/Ɛ):’);
disp(Calibration_Factor);
The .txt file is attached.
This code runs, however the variables data_nu, data_theta_p, data_Txx, and data_Tyy within the Cal struct all have Nan values. All other created variables contain the correct data pulled from the .txt file. Why is this happening? nan data, .txt MATLAB Answers — New Questions
Why are my variables saving only Nan entries?
Cal = struct;
Cal.data = readtable(‘Lab_4_Data.txt’);
Cal.data_uE1 = Cal.data.Var3;
Cal.data_uE2 = Cal.data.Var4;
Cal.data_uE3 = Cal.data.Var5;
Cal.data_E1 = Cal.data_uE1 * 1000000;
Cal.data_E2 = Cal.data_uE2 * 1000000;
Cal.data_E3 = Cal.data_uE3 * 1000000;
masses = [0 50 100 200 300 500]; % grams
xN = (masses ./ 1000) * 9.81; % in newtons
% Calculate shear strain (𝛾xy)
Cal.data_gamma_xy = 2 * Cal.data_E2 – (Cal.data_E1 + Cal.data_E3);
% Calculate principal strains (Ɛ1, Ɛ2, Ɛ3)
Cal.data_epsilon_1 = Cal.data_E1;
Cal.data_epsilon_2 = 0.5 * Cal.data_gamma_xy;
Cal.data_epsilon_3 = Cal.data_E3;
% Calculate Poisson’s ratio (v)
Cal.data_nu = abs(Cal.data_epsilon_2) ./ Cal.data_epsilon_1;
% Calculate angle of rotation (𝜃𝜃p)
Cal.data_theta_p = atand(Cal.data_gamma_xy ./ (Cal.data_epsilon_1 – Cal.data_epsilon_3));
% Calculate principal stresses (Txx, Tyy)
E = 69000; % Young’s Modulus for aluminum in MPa
Cal.data_Txx = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_1 + Cal.data_nu .* Cal.data_epsilon_2);
Cal.data_Tyy = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_2 + Cal.data_nu .* Cal.data_epsilon_1);
% Calculate longitudinal stress from the beam flexure equation
P = xN; % applied load in Newtons
L = 0.241; % length of the beam in meters (replace with your actual value)
b = 0.025; % width of the beam in meters (replace with your actual value)
h = 0.00379; % thickness of the beam in meters (replace with your actual value)
c = h / 2;
% distance between gage’s mounting line and dent at the end of the beam in meters
L_adjusted = 0.051;
I = (b * h^3) / 12;
Cal.data_sigma_L = (6 * P * L_adjusted) / (b * h^2);
% Calculate load cell calibration factor
Calibration_Factor = max(abs(Cal.data_epsilon_1)) / max(P);
% Plot 1: Principal Strains vs. Applied Load
figure;
plot(xN, Cal.data_epsilon_1(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ1’);
hold on;
plot(xN, Cal.data_epsilon_2(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ2’);
plot(xN, Cal.data_epsilon_3(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ3’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Strains (muepsilon)’);
title(‘Principal Strains vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 2: Principal Stresses vs. Applied Load
figure;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Txx’);
hold on;
plot(xN, Cal.data_Tyy(1:6), ‘-o’, ‘DisplayName’, ‘Tyy’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Stresses (MPa)’);
title(‘Principal Stresses vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 3: Comparison of Measured and Theoretical Longitudinal Stress
figure;
plot(xN, Cal.data_sigma_L(1:6), ‘-o’, ‘DisplayName’, ‘Measured Longitudinal Stress’);
hold on;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Theoretical Longitudinal Stress’);
xlabel(‘Applied Load (N)’);
ylabel(‘Stress (MPa)’);
title(‘Comparison of Measured and Theoretical Longitudinal Stress’);
legend(‘Location’, ‘Best’);
grid on;
% Display Load Cell Calibration Factor
disp(‘Load Cell Calibration Factor (N/Ɛ):’);
disp(Calibration_Factor);
The .txt file is attached.
This code runs, however the variables data_nu, data_theta_p, data_Txx, and data_Tyy within the Cal struct all have Nan values. All other created variables contain the correct data pulled from the .txt file. Why is this happening?Cal = struct;
Cal.data = readtable(‘Lab_4_Data.txt’);
Cal.data_uE1 = Cal.data.Var3;
Cal.data_uE2 = Cal.data.Var4;
Cal.data_uE3 = Cal.data.Var5;
Cal.data_E1 = Cal.data_uE1 * 1000000;
Cal.data_E2 = Cal.data_uE2 * 1000000;
Cal.data_E3 = Cal.data_uE3 * 1000000;
masses = [0 50 100 200 300 500]; % grams
xN = (masses ./ 1000) * 9.81; % in newtons
% Calculate shear strain (𝛾xy)
Cal.data_gamma_xy = 2 * Cal.data_E2 – (Cal.data_E1 + Cal.data_E3);
% Calculate principal strains (Ɛ1, Ɛ2, Ɛ3)
Cal.data_epsilon_1 = Cal.data_E1;
Cal.data_epsilon_2 = 0.5 * Cal.data_gamma_xy;
Cal.data_epsilon_3 = Cal.data_E3;
% Calculate Poisson’s ratio (v)
Cal.data_nu = abs(Cal.data_epsilon_2) ./ Cal.data_epsilon_1;
% Calculate angle of rotation (𝜃𝜃p)
Cal.data_theta_p = atand(Cal.data_gamma_xy ./ (Cal.data_epsilon_1 – Cal.data_epsilon_3));
% Calculate principal stresses (Txx, Tyy)
E = 69000; % Young’s Modulus for aluminum in MPa
Cal.data_Txx = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_1 + Cal.data_nu .* Cal.data_epsilon_2);
Cal.data_Tyy = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_2 + Cal.data_nu .* Cal.data_epsilon_1);
% Calculate longitudinal stress from the beam flexure equation
P = xN; % applied load in Newtons
L = 0.241; % length of the beam in meters (replace with your actual value)
b = 0.025; % width of the beam in meters (replace with your actual value)
h = 0.00379; % thickness of the beam in meters (replace with your actual value)
c = h / 2;
% distance between gage’s mounting line and dent at the end of the beam in meters
L_adjusted = 0.051;
I = (b * h^3) / 12;
Cal.data_sigma_L = (6 * P * L_adjusted) / (b * h^2);
% Calculate load cell calibration factor
Calibration_Factor = max(abs(Cal.data_epsilon_1)) / max(P);
% Plot 1: Principal Strains vs. Applied Load
figure;
plot(xN, Cal.data_epsilon_1(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ1’);
hold on;
plot(xN, Cal.data_epsilon_2(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ2’);
plot(xN, Cal.data_epsilon_3(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ3’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Strains (muepsilon)’);
title(‘Principal Strains vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 2: Principal Stresses vs. Applied Load
figure;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Txx’);
hold on;
plot(xN, Cal.data_Tyy(1:6), ‘-o’, ‘DisplayName’, ‘Tyy’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Stresses (MPa)’);
title(‘Principal Stresses vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 3: Comparison of Measured and Theoretical Longitudinal Stress
figure;
plot(xN, Cal.data_sigma_L(1:6), ‘-o’, ‘DisplayName’, ‘Measured Longitudinal Stress’);
hold on;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Theoretical Longitudinal Stress’);
xlabel(‘Applied Load (N)’);
ylabel(‘Stress (MPa)’);
title(‘Comparison of Measured and Theoretical Longitudinal Stress’);
legend(‘Location’, ‘Best’);
grid on;
% Display Load Cell Calibration Factor
disp(‘Load Cell Calibration Factor (N/Ɛ):’);
disp(Calibration_Factor);
The .txt file is attached.
This code runs, however the variables data_nu, data_theta_p, data_Txx, and data_Tyy within the Cal struct all have Nan values. All other created variables contain the correct data pulled from the .txt file. Why is this happening? Cal = struct;
Cal.data = readtable(‘Lab_4_Data.txt’);
Cal.data_uE1 = Cal.data.Var3;
Cal.data_uE2 = Cal.data.Var4;
Cal.data_uE3 = Cal.data.Var5;
Cal.data_E1 = Cal.data_uE1 * 1000000;
Cal.data_E2 = Cal.data_uE2 * 1000000;
Cal.data_E3 = Cal.data_uE3 * 1000000;
masses = [0 50 100 200 300 500]; % grams
xN = (masses ./ 1000) * 9.81; % in newtons
% Calculate shear strain (𝛾xy)
Cal.data_gamma_xy = 2 * Cal.data_E2 – (Cal.data_E1 + Cal.data_E3);
% Calculate principal strains (Ɛ1, Ɛ2, Ɛ3)
Cal.data_epsilon_1 = Cal.data_E1;
Cal.data_epsilon_2 = 0.5 * Cal.data_gamma_xy;
Cal.data_epsilon_3 = Cal.data_E3;
% Calculate Poisson’s ratio (v)
Cal.data_nu = abs(Cal.data_epsilon_2) ./ Cal.data_epsilon_1;
% Calculate angle of rotation (𝜃𝜃p)
Cal.data_theta_p = atand(Cal.data_gamma_xy ./ (Cal.data_epsilon_1 – Cal.data_epsilon_3));
% Calculate principal stresses (Txx, Tyy)
E = 69000; % Young’s Modulus for aluminum in MPa
Cal.data_Txx = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_1 + Cal.data_nu .* Cal.data_epsilon_2);
Cal.data_Tyy = ((E) / (1 – Cal.data_nu.^2)) .* (Cal.data_epsilon_2 + Cal.data_nu .* Cal.data_epsilon_1);
% Calculate longitudinal stress from the beam flexure equation
P = xN; % applied load in Newtons
L = 0.241; % length of the beam in meters (replace with your actual value)
b = 0.025; % width of the beam in meters (replace with your actual value)
h = 0.00379; % thickness of the beam in meters (replace with your actual value)
c = h / 2;
% distance between gage’s mounting line and dent at the end of the beam in meters
L_adjusted = 0.051;
I = (b * h^3) / 12;
Cal.data_sigma_L = (6 * P * L_adjusted) / (b * h^2);
% Calculate load cell calibration factor
Calibration_Factor = max(abs(Cal.data_epsilon_1)) / max(P);
% Plot 1: Principal Strains vs. Applied Load
figure;
plot(xN, Cal.data_epsilon_1(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ1’);
hold on;
plot(xN, Cal.data_epsilon_2(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ2’);
plot(xN, Cal.data_epsilon_3(1:6), ‘-o’, ‘DisplayName’, ‘Ɛ3’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Strains (muepsilon)’);
title(‘Principal Strains vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 2: Principal Stresses vs. Applied Load
figure;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Txx’);
hold on;
plot(xN, Cal.data_Tyy(1:6), ‘-o’, ‘DisplayName’, ‘Tyy’);
xlabel(‘Applied Load (N)’);
ylabel(‘Principal Stresses (MPa)’);
title(‘Principal Stresses vs. Applied Load’);
legend(‘Location’, ‘Best’);
grid on;
% Plot 3: Comparison of Measured and Theoretical Longitudinal Stress
figure;
plot(xN, Cal.data_sigma_L(1:6), ‘-o’, ‘DisplayName’, ‘Measured Longitudinal Stress’);
hold on;
plot(xN, Cal.data_Txx(1:6), ‘-o’, ‘DisplayName’, ‘Theoretical Longitudinal Stress’);
xlabel(‘Applied Load (N)’);
ylabel(‘Stress (MPa)’);
title(‘Comparison of Measured and Theoretical Longitudinal Stress’);
legend(‘Location’, ‘Best’);
grid on;
% Display Load Cell Calibration Factor
disp(‘Load Cell Calibration Factor (N/Ɛ):’);
disp(Calibration_Factor);
The .txt file is attached.
This code runs, however the variables data_nu, data_theta_p, data_Txx, and data_Tyy within the Cal struct all have Nan values. All other created variables contain the correct data pulled from the .txt file. Why is this happening? nan data, .txt MATLAB Answers — New Questions
How to perform fuzzy c means clustering using custom initializations (initial fuzzy membership metric, datapoints, cluster centers.. etc)?
% Define the data points as coordinates (X, Y)
Data = [
1, 3;
8, 2;
1, 2;
3, 1
];
% Defining total number of clusters
NumOfClusters = 2;
% Create the initial fuzzy partition matrix (U0)
U0 = [
1, 1, 0, 0;
0, 0, 1, 1
]; % Provided initial partition matrix
% Define initial cluster center values
initial_centers = [
2.0, 2.35;
2.15, 1.9
];
% Fuzzy c-means options
fuzzy_options = [2.0];
% Perform Fuzzy C-Means clustering with initializations
[~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
% Displaying the updated partition matrix
disp(‘Updated Partition Matrix (Membership):’);
disp(membership);
% Plotting the clustered data with different colors for each cluster
colors = distinguishable_colors(NumOfClusters); % Generate distinct colors for clusters
figure;
for i = 1:NumOfClusters
idx = find(membership(i, 🙂 == max(membership));
scatter(Data(idx, 1), Data(idx, 2), 100, colors(i, :), ‘filled’);
hold on;
end
plot(cluster_centers(:, 1), cluster_centers(:, 2), ‘kx’, ‘MarkerSize’, 15, ‘LineWidth’, 2); % Plot cluster centers
hold off;
% Creating a legend dynamically based on the number of clusters
legend_strings = cell(1, NumOfClusters);
for i = 1:NumOfClusters
legend_strings{i} = [‘Cluster ‘ num2str(i)];
end
legend_strings{NumOfClusters + 1} = ‘Cluster Centers’;
legend(legend_strings);
title(‘Fuzzy C-Means Clustering with Initializations’);
I want to initialize the datapoints, initial fuzzy partition matrix U0, initial_cluster centers but i am getting the following error:
Error using fcm Too many input arguments. Error in (line 28) [~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
When i remove the initial fuzzy partition matrix U0 and initial cluster centers the code works.% Define the data points as coordinates (X, Y)
Data = [
1, 3;
8, 2;
1, 2;
3, 1
];
% Defining total number of clusters
NumOfClusters = 2;
% Create the initial fuzzy partition matrix (U0)
U0 = [
1, 1, 0, 0;
0, 0, 1, 1
]; % Provided initial partition matrix
% Define initial cluster center values
initial_centers = [
2.0, 2.35;
2.15, 1.9
];
% Fuzzy c-means options
fuzzy_options = [2.0];
% Perform Fuzzy C-Means clustering with initializations
[~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
% Displaying the updated partition matrix
disp(‘Updated Partition Matrix (Membership):’);
disp(membership);
% Plotting the clustered data with different colors for each cluster
colors = distinguishable_colors(NumOfClusters); % Generate distinct colors for clusters
figure;
for i = 1:NumOfClusters
idx = find(membership(i, 🙂 == max(membership));
scatter(Data(idx, 1), Data(idx, 2), 100, colors(i, :), ‘filled’);
hold on;
end
plot(cluster_centers(:, 1), cluster_centers(:, 2), ‘kx’, ‘MarkerSize’, 15, ‘LineWidth’, 2); % Plot cluster centers
hold off;
% Creating a legend dynamically based on the number of clusters
legend_strings = cell(1, NumOfClusters);
for i = 1:NumOfClusters
legend_strings{i} = [‘Cluster ‘ num2str(i)];
end
legend_strings{NumOfClusters + 1} = ‘Cluster Centers’;
legend(legend_strings);
title(‘Fuzzy C-Means Clustering with Initializations’);
I want to initialize the datapoints, initial fuzzy partition matrix U0, initial_cluster centers but i am getting the following error:
Error using fcm Too many input arguments. Error in (line 28) [~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
When i remove the initial fuzzy partition matrix U0 and initial cluster centers the code works. % Define the data points as coordinates (X, Y)
Data = [
1, 3;
8, 2;
1, 2;
3, 1
];
% Defining total number of clusters
NumOfClusters = 2;
% Create the initial fuzzy partition matrix (U0)
U0 = [
1, 1, 0, 0;
0, 0, 1, 1
]; % Provided initial partition matrix
% Define initial cluster center values
initial_centers = [
2.0, 2.35;
2.15, 1.9
];
% Fuzzy c-means options
fuzzy_options = [2.0];
% Perform Fuzzy C-Means clustering with initializations
[~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
% Displaying the updated partition matrix
disp(‘Updated Partition Matrix (Membership):’);
disp(membership);
% Plotting the clustered data with different colors for each cluster
colors = distinguishable_colors(NumOfClusters); % Generate distinct colors for clusters
figure;
for i = 1:NumOfClusters
idx = find(membership(i, 🙂 == max(membership));
scatter(Data(idx, 1), Data(idx, 2), 100, colors(i, :), ‘filled’);
hold on;
end
plot(cluster_centers(:, 1), cluster_centers(:, 2), ‘kx’, ‘MarkerSize’, 15, ‘LineWidth’, 2); % Plot cluster centers
hold off;
% Creating a legend dynamically based on the number of clusters
legend_strings = cell(1, NumOfClusters);
for i = 1:NumOfClusters
legend_strings{i} = [‘Cluster ‘ num2str(i)];
end
legend_strings{NumOfClusters + 1} = ‘Cluster Centers’;
legend(legend_strings);
title(‘Fuzzy C-Means Clustering with Initializations’);
I want to initialize the datapoints, initial fuzzy partition matrix U0, initial_cluster centers but i am getting the following error:
Error using fcm Too many input arguments. Error in (line 28) [~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
When i remove the initial fuzzy partition matrix U0 and initial cluster centers the code works. fuzzy clustering, fuzzy c means MATLAB Answers — New Questions
How to perform fuzzy c means clustering using custom initializations (initial fuzzy membership metric, datapoints, cluster centers.. etc)?
% Define the data points as coordinates (X, Y)
Data = [
1, 3;
8, 2;
1, 2;
3, 1
];
% Defining total number of clusters
NumOfClusters = 2;
% Create the initial fuzzy partition matrix (U0)
U0 = [
1, 1, 0, 0;
0, 0, 1, 1
]; % Provided initial partition matrix
% Define initial cluster center values
initial_centers = [
2.0, 2.35;
2.15, 1.9
];
% Fuzzy c-means options
fuzzy_options = [2.0];
% Perform Fuzzy C-Means clustering with initializations
[~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
% Displaying the updated partition matrix
disp(‘Updated Partition Matrix (Membership):’);
disp(membership);
% Plotting the clustered data with different colors for each cluster
colors = distinguishable_colors(NumOfClusters); % Generate distinct colors for clusters
figure;
for i = 1:NumOfClusters
idx = find(membership(i, 🙂 == max(membership));
scatter(Data(idx, 1), Data(idx, 2), 100, colors(i, :), ‘filled’);
hold on;
end
plot(cluster_centers(:, 1), cluster_centers(:, 2), ‘kx’, ‘MarkerSize’, 15, ‘LineWidth’, 2); % Plot cluster centers
hold off;
% Creating a legend dynamically based on the number of clusters
legend_strings = cell(1, NumOfClusters);
for i = 1:NumOfClusters
legend_strings{i} = [‘Cluster ‘ num2str(i)];
end
legend_strings{NumOfClusters + 1} = ‘Cluster Centers’;
legend(legend_strings);
title(‘Fuzzy C-Means Clustering with Initializations’);
I want to initialize the datapoints, initial fuzzy partition matrix U0, initial_cluster centers but i am getting the following error:
Error using fcm Too many input arguments. Error in (line 28) [~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
When i remove the initial fuzzy partition matrix U0 and initial cluster centers the code works.% Define the data points as coordinates (X, Y)
Data = [
1, 3;
8, 2;
1, 2;
3, 1
];
% Defining total number of clusters
NumOfClusters = 2;
% Create the initial fuzzy partition matrix (U0)
U0 = [
1, 1, 0, 0;
0, 0, 1, 1
]; % Provided initial partition matrix
% Define initial cluster center values
initial_centers = [
2.0, 2.35;
2.15, 1.9
];
% Fuzzy c-means options
fuzzy_options = [2.0];
% Perform Fuzzy C-Means clustering with initializations
[~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
% Displaying the updated partition matrix
disp(‘Updated Partition Matrix (Membership):’);
disp(membership);
% Plotting the clustered data with different colors for each cluster
colors = distinguishable_colors(NumOfClusters); % Generate distinct colors for clusters
figure;
for i = 1:NumOfClusters
idx = find(membership(i, 🙂 == max(membership));
scatter(Data(idx, 1), Data(idx, 2), 100, colors(i, :), ‘filled’);
hold on;
end
plot(cluster_centers(:, 1), cluster_centers(:, 2), ‘kx’, ‘MarkerSize’, 15, ‘LineWidth’, 2); % Plot cluster centers
hold off;
% Creating a legend dynamically based on the number of clusters
legend_strings = cell(1, NumOfClusters);
for i = 1:NumOfClusters
legend_strings{i} = [‘Cluster ‘ num2str(i)];
end
legend_strings{NumOfClusters + 1} = ‘Cluster Centers’;
legend(legend_strings);
title(‘Fuzzy C-Means Clustering with Initializations’);
I want to initialize the datapoints, initial fuzzy partition matrix U0, initial_cluster centers but i am getting the following error:
Error using fcm Too many input arguments. Error in (line 28) [~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
When i remove the initial fuzzy partition matrix U0 and initial cluster centers the code works. % Define the data points as coordinates (X, Y)
Data = [
1, 3;
8, 2;
1, 2;
3, 1
];
% Defining total number of clusters
NumOfClusters = 2;
% Create the initial fuzzy partition matrix (U0)
U0 = [
1, 1, 0, 0;
0, 0, 1, 1
]; % Provided initial partition matrix
% Define initial cluster center values
initial_centers = [
2.0, 2.35;
2.15, 1.9
];
% Fuzzy c-means options
fuzzy_options = [2.0];
% Perform Fuzzy C-Means clustering with initializations
[~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
% Displaying the updated partition matrix
disp(‘Updated Partition Matrix (Membership):’);
disp(membership);
% Plotting the clustered data with different colors for each cluster
colors = distinguishable_colors(NumOfClusters); % Generate distinct colors for clusters
figure;
for i = 1:NumOfClusters
idx = find(membership(i, 🙂 == max(membership));
scatter(Data(idx, 1), Data(idx, 2), 100, colors(i, :), ‘filled’);
hold on;
end
plot(cluster_centers(:, 1), cluster_centers(:, 2), ‘kx’, ‘MarkerSize’, 15, ‘LineWidth’, 2); % Plot cluster centers
hold off;
% Creating a legend dynamically based on the number of clusters
legend_strings = cell(1, NumOfClusters);
for i = 1:NumOfClusters
legend_strings{i} = [‘Cluster ‘ num2str(i)];
end
legend_strings{NumOfClusters + 1} = ‘Cluster Centers’;
legend(legend_strings);
title(‘Fuzzy C-Means Clustering with Initializations’);
I want to initialize the datapoints, initial fuzzy partition matrix U0, initial_cluster centers but i am getting the following error:
Error using fcm Too many input arguments. Error in (line 28) [~, cluster_centers, membership] = fcm(Data’, NumOfClusters, fuzzy_options, U0, [], initial_centers);
When i remove the initial fuzzy partition matrix U0 and initial cluster centers the code works. fuzzy clustering, fuzzy c means MATLAB Answers — New Questions
How to find root locus of a polynomial
I need to find the root locus of a polynomial.
m_s = 1; % Mass of the spring
m_r = 68; % Mass of the rotor
k_r = 5.45e5; % Spring constant of the rotor
c_s = 663; % Damping coefficient of the spring
c_r = 900; % Damping coefficient of the rotor
k_s = 15000; % Spring constant of the spring
% Frequency range in rad/s
omega = 0:100:60000;
% Initialize arrays to store roots
roots_real = zeros(length(omega), 5);
roots_imag = zeros(length(omega), 5);
% Initialize array to store crossing points
crossing_omega = zeros(1, 5);
crossing_from_real_to_imag = zeros(1, 5);
% Calculate and store roots for each angular frequency
for i = 1:length(omega)
a4_omega = c_s./m_s + k_r./c_r – 1i.*omega(i);
a3_omega = k_r./m_r + k_r./m_s + k_s./m_s + c_s./m_s*(k_r./c_r – 1i.*omega(i));
a2_omega = (k_r.*c_s) ./ (m_r.*m_s) + (k_r.*k_s) ./ (m_s.*c_r) – (k_r./m_r + k_r./m_s + k_r./m_s).*1i.*omega(i);
a1_omega = k_r ./m_r * (k_s./m_s – 1i.*omega(i).*c_s./m_s);
a0_omega = -1i.*omega(i).*k_s.*k_r ./(m_s.*m_r);
a = [1, a4_omega, a3_omega, a2_omega, a1_omega, a0_omega];
% Calculate roots
system_roots = roots(a);
% Store real and imaginary parts of the roots
roots_real(i, 🙂 = real(system_roots);
roots_imag(i, 🙂 = imag(system_roots);
I would like to plot the root locus for this system as ω varies. Could you please assist me in implementing this in MATLAB? Specifically, I am looking for guidance on expressing the characteristic equation in terms of s and ω, and how to use MATLAB functions to generate the root locus plotI need to find the root locus of a polynomial.
m_s = 1; % Mass of the spring
m_r = 68; % Mass of the rotor
k_r = 5.45e5; % Spring constant of the rotor
c_s = 663; % Damping coefficient of the spring
c_r = 900; % Damping coefficient of the rotor
k_s = 15000; % Spring constant of the spring
% Frequency range in rad/s
omega = 0:100:60000;
% Initialize arrays to store roots
roots_real = zeros(length(omega), 5);
roots_imag = zeros(length(omega), 5);
% Initialize array to store crossing points
crossing_omega = zeros(1, 5);
crossing_from_real_to_imag = zeros(1, 5);
% Calculate and store roots for each angular frequency
for i = 1:length(omega)
a4_omega = c_s./m_s + k_r./c_r – 1i.*omega(i);
a3_omega = k_r./m_r + k_r./m_s + k_s./m_s + c_s./m_s*(k_r./c_r – 1i.*omega(i));
a2_omega = (k_r.*c_s) ./ (m_r.*m_s) + (k_r.*k_s) ./ (m_s.*c_r) – (k_r./m_r + k_r./m_s + k_r./m_s).*1i.*omega(i);
a1_omega = k_r ./m_r * (k_s./m_s – 1i.*omega(i).*c_s./m_s);
a0_omega = -1i.*omega(i).*k_s.*k_r ./(m_s.*m_r);
a = [1, a4_omega, a3_omega, a2_omega, a1_omega, a0_omega];
% Calculate roots
system_roots = roots(a);
% Store real and imaginary parts of the roots
roots_real(i, 🙂 = real(system_roots);
roots_imag(i, 🙂 = imag(system_roots);
I would like to plot the root locus for this system as ω varies. Could you please assist me in implementing this in MATLAB? Specifically, I am looking for guidance on expressing the characteristic equation in terms of s and ω, and how to use MATLAB functions to generate the root locus plot I need to find the root locus of a polynomial.
m_s = 1; % Mass of the spring
m_r = 68; % Mass of the rotor
k_r = 5.45e5; % Spring constant of the rotor
c_s = 663; % Damping coefficient of the spring
c_r = 900; % Damping coefficient of the rotor
k_s = 15000; % Spring constant of the spring
% Frequency range in rad/s
omega = 0:100:60000;
% Initialize arrays to store roots
roots_real = zeros(length(omega), 5);
roots_imag = zeros(length(omega), 5);
% Initialize array to store crossing points
crossing_omega = zeros(1, 5);
crossing_from_real_to_imag = zeros(1, 5);
% Calculate and store roots for each angular frequency
for i = 1:length(omega)
a4_omega = c_s./m_s + k_r./c_r – 1i.*omega(i);
a3_omega = k_r./m_r + k_r./m_s + k_s./m_s + c_s./m_s*(k_r./c_r – 1i.*omega(i));
a2_omega = (k_r.*c_s) ./ (m_r.*m_s) + (k_r.*k_s) ./ (m_s.*c_r) – (k_r./m_r + k_r./m_s + k_r./m_s).*1i.*omega(i);
a1_omega = k_r ./m_r * (k_s./m_s – 1i.*omega(i).*c_s./m_s);
a0_omega = -1i.*omega(i).*k_s.*k_r ./(m_s.*m_r);
a = [1, a4_omega, a3_omega, a2_omega, a1_omega, a0_omega];
% Calculate roots
system_roots = roots(a);
% Store real and imaginary parts of the roots
roots_real(i, 🙂 = real(system_roots);
roots_imag(i, 🙂 = imag(system_roots);
I would like to plot the root locus for this system as ω varies. Could you please assist me in implementing this in MATLAB? Specifically, I am looking for guidance on expressing the characteristic equation in terms of s and ω, and how to use MATLAB functions to generate the root locus plot rootlocus MATLAB Answers — New Questions
What does this error mean: “Assigning to 3 elements using a simple assignment statement is not supported. Consider using comma-separated list assignment.” How to remove?
I am trying to create a clustered bar graph from this data.
times = [5,20,40,60,120];
ravgdm =
35.3689 34.2453 31.9268 29.3701 33.5380
30.4708 32.3411 28.3500 27.8087 28.9000
19.7406 21.9029 20.6332 18.9298 20.4248
My code looks like this.
figure()
times = [5,20,40,60,120];
bcv = bar(times,ravgdm)
bcv.FaceColor = ‘flat’;
bcv.CData(1,:) = [0.9290, 0.6940, 0.1250];
bcv.CData(2,:) = [0.4940, 0.1840, 0.5560];
bcv.CData(3,:) = [0.9, 0.1, 0.1];
set(gca, ‘XTickLabel’, {‘5′,’20’,’40’,’60’, ‘120’})
xlabel (‘Time (min)’)
ylabel (‘Average Diameter (pixels)’)
title (‘Average Diameter (pixels) at Each Time Point’)
However, I keep getting theses errors, and I dont know why.
Assigning to 3 elements using a simple assignment statement is not supported. Consider using
comma-separated list assignment.
Error in csize (line 64)
bcv.FaceColor = ‘flat’;
Some insight on why this is occuring would be great! Thank you!I am trying to create a clustered bar graph from this data.
times = [5,20,40,60,120];
ravgdm =
35.3689 34.2453 31.9268 29.3701 33.5380
30.4708 32.3411 28.3500 27.8087 28.9000
19.7406 21.9029 20.6332 18.9298 20.4248
My code looks like this.
figure()
times = [5,20,40,60,120];
bcv = bar(times,ravgdm)
bcv.FaceColor = ‘flat’;
bcv.CData(1,:) = [0.9290, 0.6940, 0.1250];
bcv.CData(2,:) = [0.4940, 0.1840, 0.5560];
bcv.CData(3,:) = [0.9, 0.1, 0.1];
set(gca, ‘XTickLabel’, {‘5′,’20’,’40’,’60’, ‘120’})
xlabel (‘Time (min)’)
ylabel (‘Average Diameter (pixels)’)
title (‘Average Diameter (pixels) at Each Time Point’)
However, I keep getting theses errors, and I dont know why.
Assigning to 3 elements using a simple assignment statement is not supported. Consider using
comma-separated list assignment.
Error in csize (line 64)
bcv.FaceColor = ‘flat’;
Some insight on why this is occuring would be great! Thank you! I am trying to create a clustered bar graph from this data.
times = [5,20,40,60,120];
ravgdm =
35.3689 34.2453 31.9268 29.3701 33.5380
30.4708 32.3411 28.3500 27.8087 28.9000
19.7406 21.9029 20.6332 18.9298 20.4248
My code looks like this.
figure()
times = [5,20,40,60,120];
bcv = bar(times,ravgdm)
bcv.FaceColor = ‘flat’;
bcv.CData(1,:) = [0.9290, 0.6940, 0.1250];
bcv.CData(2,:) = [0.4940, 0.1840, 0.5560];
bcv.CData(3,:) = [0.9, 0.1, 0.1];
set(gca, ‘XTickLabel’, {‘5′,’20’,’40’,’60’, ‘120’})
xlabel (‘Time (min)’)
ylabel (‘Average Diameter (pixels)’)
title (‘Average Diameter (pixels) at Each Time Point’)
However, I keep getting theses errors, and I dont know why.
Assigning to 3 elements using a simple assignment statement is not supported. Consider using
comma-separated list assignment.
Error in csize (line 64)
bcv.FaceColor = ‘flat’;
Some insight on why this is occuring would be great! Thank you! bar, bar graph, statistics, lists, arrays MATLAB Answers — New Questions
How to adapt code to apply a sine wave input instead
i am trying to turn the following code from step input into sine wave and dont know where to start. any help would be greatly appreciated.
t = 0:0.01:500;
u = ones(size(t));
u(1:100) = zeros(1,100);
y = eval_system(u, t);
figure
plot(sin*t, u,’linewidth’,2)
hold on
plot(sin*t, y, ‘linewidth’,2)
grid oni am trying to turn the following code from step input into sine wave and dont know where to start. any help would be greatly appreciated.
t = 0:0.01:500;
u = ones(size(t));
u(1:100) = zeros(1,100);
y = eval_system(u, t);
figure
plot(sin*t, u,’linewidth’,2)
hold on
plot(sin*t, y, ‘linewidth’,2)
grid on i am trying to turn the following code from step input into sine wave and dont know where to start. any help would be greatly appreciated.
t = 0:0.01:500;
u = ones(size(t));
u(1:100) = zeros(1,100);
y = eval_system(u, t);
figure
plot(sin*t, u,’linewidth’,2)
hold on
plot(sin*t, y, ‘linewidth’,2)
grid on array MATLAB Answers — New Questions
Unable to meet integration tolerances without reducing the step size
Nx = 50; % Number of grid points
L = 5000; % Length of the spatial domain
dx = L / (Nx-1); % Spatial step size
x = linspace(0, L, Nx); % Spatial points
A=0.1963;
f = 0.008;
D = 500e-3;
rho=1.2;
c = 348.5;
P_atm = 1.013e5; % Atmospheric pressure in Pa
tspan = [0, 3600]; % Time span
% Initial conditions
P0 = 5e6*ones(Nx,1); % Initial condition for pressure (P)
m0 = zeros(Nx, 1); % Initial condition for mass flow rate (m)
% Initial conditions vector
u0 = [P0; m0];
options = odeset(‘RelTol’, 1e-6, ‘AbsTol’, 1e-6);
% Solve the system of ODEs using ode15s
[t, u] = ode15s(@(t, u) MyODEs(t, u, Nx, dx, f, c, D), tspan, u0,options);
% Extract the solutions for P and m
P_solution = u(:, 1:Nx);
m_solution = u(:, Nx + 1:end);
%% when m =kg/s*m^2
Q_n= (m_solution./rho);
Q=(Q_n .*A);
% nodes_to_plot = 1:7:Nx;
%
% % Plotting P_solution for selected nodes with transparency
% figure;
% hold on;
% colors = rand(length(nodes_to_plot), 3);
% for idx = 1:length(nodes_to_plot)
% i = nodes_to_plot(idx);
% plot(t, P_solution(:, i), ‘LineWidth’, 0.5, ‘DisplayName’, [‘Node ‘ num2str(i)], ‘Color’, colors(idx,:), ‘LineStyle’, ‘-‘);
% end
% hold off;
% xlabel(‘Time (t)’);
% ylabel(‘Pressure (P)’);
% title(‘Pressure (P) at Selected Nodes over Time’);
% legend(‘show’);
% % Choose Node 1 (x = 1) for plotting
node1_idx = 25;
% % Extract the pressure and Q values at Node 1
Q_node1 = Q(:, node1_idx);
figure;
plot(t, Q_node1 , ‘LineWidth’, 2);
xlabel(‘Time (t)’);
ylabel(‘Q at Node 1’);
title(‘Q at Node 1 over Time with covective term’);
% Set up the system of ODEs including the boundary condition ODEs
function dudt = MyODEs(t, u, Nx, dx, f, c, D)
P = u(1:Nx);
m = u(Nx + 1:end);
dPdt = zeros(Nx, 1);
dmdt = zeros(Nx, 1);
% Boundary Condition
P(1) = 5e6; % P(1) boundary condition
% Nozzle at i=25 (Algebraic relationships)
p_hst = 503.51e3; % p_hst = rho * g * d (where d = 40m)
Cd = 0.55;
gamma = 1.4;
rho1 = 1.2;
% Mass flowrate of nozzle
m_nz = Cd * sqrt((2 * gamma / (gamma – 1)) * P(25) * rho1 * (1 – (P(25) / p_hst)^((gamma – 1) / gamma)) * (P(25) / p_hst)^(2 / gamma));
% Equation
dPdt(25) =-c^2 * (3*m(25) – 4*m(24) + m(23)) / (2*dx); % Backward discretization of dP/dt at i=25
dmdt(25) =-(2*m(25)*c^2/P(25)*((- 3*m(25)+4*m(26)-m(27)) / (2 * dx)))+(c^2*m(25)^2/P(25)^2)*((- 3*P(25)+ 4*P(26)-P(27)) / (2*dx)) – ((-3*P(25)+4*P(26)-P(27)) / (2*dx)) – (f * m(25) * abs(m(25)) * c^2) / (2 *D* (P(25))); % Forward discretization for dm/dt at i=26
dmdt(1) =-(2*m(1)*c^2/P(1)*((- 3*m(1)+4*m(2)-m(3)) / (2 * dx)))+(c^2*m(1)^2/P(1)^2)*((- 3*P(1)+ 4*P(2)-P(3)) / (2*dx)) – ((-3*P(1)+4*P(2)-P(3)) / (2*dx)) – (f * m(1) * abs(m(1)) * c^2) / (2 *D* (P(1))); % Forward discretization for dm/dt at i=1
% Update m(Nx) based on the time t and the specified conditions
for i = 1:length(t)
if t(i) < 600
m(Nx) = 0;
elseif t(i) < 1800
m(Nx) = 509.28; %509.28 kg/s*m^2;
else
m(Nx) = 0;
end
end
% Equations
dPdt(Nx) =-c^2 * (3*m(Nx) – 4*m(Nx – 1) + m(Nx-2)) / (2*dx); % Backward discretization of dP/dt at i=Nx
% Central discretization for in-between grid points (i=2 to 49)
for i = 2:49
if i == 25
% Skip the calculation for dPdt(25) since it’s already calculated outside the loop
% dPdt(25) = …;
% dmdt(25) =…..;
elseif i == 24
m(i)= m(25)+m_nz;% Two mass flow rate enter m(25) and m_nz
else
% Calculate dP/dt and dm/dt for in-between grid points using central discretization
dPdt(i) = -c^2 * (m(i+1) – m(i-1)) / (2 * dx); % Central discretization of dP/dt
dmdt(i) =-2*m(i)*c^2/P(i)*((m(i + 1) – m(i – 1)) / (2 * dx))+(c^2*m(i)^2/P(i)^2)*(P(i+1) – P(i-1)) / (2*dx) – (P(i+1) – P(i-1)) / (2*dx) – (f * m(i) * abs(m(i))* c^2 ) /( 2*D*P(i)); % Central discretization of dm/dt
end
end
% Combine dPdt and dmdt into a single vector
dudt = [dPdt; dmdt];
end
%% Due to this condition ,i am getting warning that integration tolerance cannot be meet
% The logic mass flowrate entering at node 24 , is summation of m(25)+ m_nz
elseif i == 24
m(i)= m(25)+m_nz;% Two mass flow rate enter m(25) and m_nzNx = 50; % Number of grid points
L = 5000; % Length of the spatial domain
dx = L / (Nx-1); % Spatial step size
x = linspace(0, L, Nx); % Spatial points
A=0.1963;
f = 0.008;
D = 500e-3;
rho=1.2;
c = 348.5;
P_atm = 1.013e5; % Atmospheric pressure in Pa
tspan = [0, 3600]; % Time span
% Initial conditions
P0 = 5e6*ones(Nx,1); % Initial condition for pressure (P)
m0 = zeros(Nx, 1); % Initial condition for mass flow rate (m)
% Initial conditions vector
u0 = [P0; m0];
options = odeset(‘RelTol’, 1e-6, ‘AbsTol’, 1e-6);
% Solve the system of ODEs using ode15s
[t, u] = ode15s(@(t, u) MyODEs(t, u, Nx, dx, f, c, D), tspan, u0,options);
% Extract the solutions for P and m
P_solution = u(:, 1:Nx);
m_solution = u(:, Nx + 1:end);
%% when m =kg/s*m^2
Q_n= (m_solution./rho);
Q=(Q_n .*A);
% nodes_to_plot = 1:7:Nx;
%
% % Plotting P_solution for selected nodes with transparency
% figure;
% hold on;
% colors = rand(length(nodes_to_plot), 3);
% for idx = 1:length(nodes_to_plot)
% i = nodes_to_plot(idx);
% plot(t, P_solution(:, i), ‘LineWidth’, 0.5, ‘DisplayName’, [‘Node ‘ num2str(i)], ‘Color’, colors(idx,:), ‘LineStyle’, ‘-‘);
% end
% hold off;
% xlabel(‘Time (t)’);
% ylabel(‘Pressure (P)’);
% title(‘Pressure (P) at Selected Nodes over Time’);
% legend(‘show’);
% % Choose Node 1 (x = 1) for plotting
node1_idx = 25;
% % Extract the pressure and Q values at Node 1
Q_node1 = Q(:, node1_idx);
figure;
plot(t, Q_node1 , ‘LineWidth’, 2);
xlabel(‘Time (t)’);
ylabel(‘Q at Node 1’);
title(‘Q at Node 1 over Time with covective term’);
% Set up the system of ODEs including the boundary condition ODEs
function dudt = MyODEs(t, u, Nx, dx, f, c, D)
P = u(1:Nx);
m = u(Nx + 1:end);
dPdt = zeros(Nx, 1);
dmdt = zeros(Nx, 1);
% Boundary Condition
P(1) = 5e6; % P(1) boundary condition
% Nozzle at i=25 (Algebraic relationships)
p_hst = 503.51e3; % p_hst = rho * g * d (where d = 40m)
Cd = 0.55;
gamma = 1.4;
rho1 = 1.2;
% Mass flowrate of nozzle
m_nz = Cd * sqrt((2 * gamma / (gamma – 1)) * P(25) * rho1 * (1 – (P(25) / p_hst)^((gamma – 1) / gamma)) * (P(25) / p_hst)^(2 / gamma));
% Equation
dPdt(25) =-c^2 * (3*m(25) – 4*m(24) + m(23)) / (2*dx); % Backward discretization of dP/dt at i=25
dmdt(25) =-(2*m(25)*c^2/P(25)*((- 3*m(25)+4*m(26)-m(27)) / (2 * dx)))+(c^2*m(25)^2/P(25)^2)*((- 3*P(25)+ 4*P(26)-P(27)) / (2*dx)) – ((-3*P(25)+4*P(26)-P(27)) / (2*dx)) – (f * m(25) * abs(m(25)) * c^2) / (2 *D* (P(25))); % Forward discretization for dm/dt at i=26
dmdt(1) =-(2*m(1)*c^2/P(1)*((- 3*m(1)+4*m(2)-m(3)) / (2 * dx)))+(c^2*m(1)^2/P(1)^2)*((- 3*P(1)+ 4*P(2)-P(3)) / (2*dx)) – ((-3*P(1)+4*P(2)-P(3)) / (2*dx)) – (f * m(1) * abs(m(1)) * c^2) / (2 *D* (P(1))); % Forward discretization for dm/dt at i=1
% Update m(Nx) based on the time t and the specified conditions
for i = 1:length(t)
if t(i) < 600
m(Nx) = 0;
elseif t(i) < 1800
m(Nx) = 509.28; %509.28 kg/s*m^2;
else
m(Nx) = 0;
end
end
% Equations
dPdt(Nx) =-c^2 * (3*m(Nx) – 4*m(Nx – 1) + m(Nx-2)) / (2*dx); % Backward discretization of dP/dt at i=Nx
% Central discretization for in-between grid points (i=2 to 49)
for i = 2:49
if i == 25
% Skip the calculation for dPdt(25) since it’s already calculated outside the loop
% dPdt(25) = …;
% dmdt(25) =…..;
elseif i == 24
m(i)= m(25)+m_nz;% Two mass flow rate enter m(25) and m_nz
else
% Calculate dP/dt and dm/dt for in-between grid points using central discretization
dPdt(i) = -c^2 * (m(i+1) – m(i-1)) / (2 * dx); % Central discretization of dP/dt
dmdt(i) =-2*m(i)*c^2/P(i)*((m(i + 1) – m(i – 1)) / (2 * dx))+(c^2*m(i)^2/P(i)^2)*(P(i+1) – P(i-1)) / (2*dx) – (P(i+1) – P(i-1)) / (2*dx) – (f * m(i) * abs(m(i))* c^2 ) /( 2*D*P(i)); % Central discretization of dm/dt
end
end
% Combine dPdt and dmdt into a single vector
dudt = [dPdt; dmdt];
end
%% Due to this condition ,i am getting warning that integration tolerance cannot be meet
% The logic mass flowrate entering at node 24 , is summation of m(25)+ m_nz
elseif i == 24
m(i)= m(25)+m_nz;% Two mass flow rate enter m(25) and m_nz Nx = 50; % Number of grid points
L = 5000; % Length of the spatial domain
dx = L / (Nx-1); % Spatial step size
x = linspace(0, L, Nx); % Spatial points
A=0.1963;
f = 0.008;
D = 500e-3;
rho=1.2;
c = 348.5;
P_atm = 1.013e5; % Atmospheric pressure in Pa
tspan = [0, 3600]; % Time span
% Initial conditions
P0 = 5e6*ones(Nx,1); % Initial condition for pressure (P)
m0 = zeros(Nx, 1); % Initial condition for mass flow rate (m)
% Initial conditions vector
u0 = [P0; m0];
options = odeset(‘RelTol’, 1e-6, ‘AbsTol’, 1e-6);
% Solve the system of ODEs using ode15s
[t, u] = ode15s(@(t, u) MyODEs(t, u, Nx, dx, f, c, D), tspan, u0,options);
% Extract the solutions for P and m
P_solution = u(:, 1:Nx);
m_solution = u(:, Nx + 1:end);
%% when m =kg/s*m^2
Q_n= (m_solution./rho);
Q=(Q_n .*A);
% nodes_to_plot = 1:7:Nx;
%
% % Plotting P_solution for selected nodes with transparency
% figure;
% hold on;
% colors = rand(length(nodes_to_plot), 3);
% for idx = 1:length(nodes_to_plot)
% i = nodes_to_plot(idx);
% plot(t, P_solution(:, i), ‘LineWidth’, 0.5, ‘DisplayName’, [‘Node ‘ num2str(i)], ‘Color’, colors(idx,:), ‘LineStyle’, ‘-‘);
% end
% hold off;
% xlabel(‘Time (t)’);
% ylabel(‘Pressure (P)’);
% title(‘Pressure (P) at Selected Nodes over Time’);
% legend(‘show’);
% % Choose Node 1 (x = 1) for plotting
node1_idx = 25;
% % Extract the pressure and Q values at Node 1
Q_node1 = Q(:, node1_idx);
figure;
plot(t, Q_node1 , ‘LineWidth’, 2);
xlabel(‘Time (t)’);
ylabel(‘Q at Node 1’);
title(‘Q at Node 1 over Time with covective term’);
% Set up the system of ODEs including the boundary condition ODEs
function dudt = MyODEs(t, u, Nx, dx, f, c, D)
P = u(1:Nx);
m = u(Nx + 1:end);
dPdt = zeros(Nx, 1);
dmdt = zeros(Nx, 1);
% Boundary Condition
P(1) = 5e6; % P(1) boundary condition
% Nozzle at i=25 (Algebraic relationships)
p_hst = 503.51e3; % p_hst = rho * g * d (where d = 40m)
Cd = 0.55;
gamma = 1.4;
rho1 = 1.2;
% Mass flowrate of nozzle
m_nz = Cd * sqrt((2 * gamma / (gamma – 1)) * P(25) * rho1 * (1 – (P(25) / p_hst)^((gamma – 1) / gamma)) * (P(25) / p_hst)^(2 / gamma));
% Equation
dPdt(25) =-c^2 * (3*m(25) – 4*m(24) + m(23)) / (2*dx); % Backward discretization of dP/dt at i=25
dmdt(25) =-(2*m(25)*c^2/P(25)*((- 3*m(25)+4*m(26)-m(27)) / (2 * dx)))+(c^2*m(25)^2/P(25)^2)*((- 3*P(25)+ 4*P(26)-P(27)) / (2*dx)) – ((-3*P(25)+4*P(26)-P(27)) / (2*dx)) – (f * m(25) * abs(m(25)) * c^2) / (2 *D* (P(25))); % Forward discretization for dm/dt at i=26
dmdt(1) =-(2*m(1)*c^2/P(1)*((- 3*m(1)+4*m(2)-m(3)) / (2 * dx)))+(c^2*m(1)^2/P(1)^2)*((- 3*P(1)+ 4*P(2)-P(3)) / (2*dx)) – ((-3*P(1)+4*P(2)-P(3)) / (2*dx)) – (f * m(1) * abs(m(1)) * c^2) / (2 *D* (P(1))); % Forward discretization for dm/dt at i=1
% Update m(Nx) based on the time t and the specified conditions
for i = 1:length(t)
if t(i) < 600
m(Nx) = 0;
elseif t(i) < 1800
m(Nx) = 509.28; %509.28 kg/s*m^2;
else
m(Nx) = 0;
end
end
% Equations
dPdt(Nx) =-c^2 * (3*m(Nx) – 4*m(Nx – 1) + m(Nx-2)) / (2*dx); % Backward discretization of dP/dt at i=Nx
% Central discretization for in-between grid points (i=2 to 49)
for i = 2:49
if i == 25
% Skip the calculation for dPdt(25) since it’s already calculated outside the loop
% dPdt(25) = …;
% dmdt(25) =…..;
elseif i == 24
m(i)= m(25)+m_nz;% Two mass flow rate enter m(25) and m_nz
else
% Calculate dP/dt and dm/dt for in-between grid points using central discretization
dPdt(i) = -c^2 * (m(i+1) – m(i-1)) / (2 * dx); % Central discretization of dP/dt
dmdt(i) =-2*m(i)*c^2/P(i)*((m(i + 1) – m(i – 1)) / (2 * dx))+(c^2*m(i)^2/P(i)^2)*(P(i+1) – P(i-1)) / (2*dx) – (P(i+1) – P(i-1)) / (2*dx) – (f * m(i) * abs(m(i))* c^2 ) /( 2*D*P(i)); % Central discretization of dm/dt
end
end
% Combine dPdt and dmdt into a single vector
dudt = [dPdt; dmdt];
end
%% Due to this condition ,i am getting warning that integration tolerance cannot be meet
% The logic mass flowrate entering at node 24 , is summation of m(25)+ m_nz
elseif i == 24
m(i)= m(25)+m_nz;% Two mass flow rate enter m(25) and m_nz ode15s MATLAB Answers — New Questions
How to save Matlab Figure without a trasparent background?
Good evening,
how can I save matlab figure without a trasparent background?
I need to save a figure without the white background to insert it on PowerPoint, do you have any suggestions? I just tried with "exportgraphics" by setting trasparent but it doesn’t seem to work.
Thank you all in advanceGood evening,
how can I save matlab figure without a trasparent background?
I need to save a figure without the white background to insert it on PowerPoint, do you have any suggestions? I just tried with "exportgraphics" by setting trasparent but it doesn’t seem to work.
Thank you all in advance Good evening,
how can I save matlab figure without a trasparent background?
I need to save a figure without the white background to insert it on PowerPoint, do you have any suggestions? I just tried with "exportgraphics" by setting trasparent but it doesn’t seem to work.
Thank you all in advance matlab, figure, plotting, plot MATLAB Answers — New Questions
Is there any documentation on how to build a transformer encoder from scratch in matlab?
I am building a transformer encoder, and I came accross the following exchange: https://www.mathworks.com/matlabcentral/fileexchange/107375-transformer-models
However, in the exchange there are examples on how to use a pretrained transformer model. I just need an example on how to build a model. Something to give a general idea so I can build on it. I have studied the basics of transformers but I am having some difficulty building the model from scratch.
Thank you in advance.I am building a transformer encoder, and I came accross the following exchange: https://www.mathworks.com/matlabcentral/fileexchange/107375-transformer-models
However, in the exchange there are examples on how to use a pretrained transformer model. I just need an example on how to build a model. Something to give a general idea so I can build on it. I have studied the basics of transformers but I am having some difficulty building the model from scratch.
Thank you in advance. I am building a transformer encoder, and I came accross the following exchange: https://www.mathworks.com/matlabcentral/fileexchange/107375-transformer-models
However, in the exchange there are examples on how to use a pretrained transformer model. I just need an example on how to build a model. Something to give a general idea so I can build on it. I have studied the basics of transformers but I am having some difficulty building the model from scratch.
Thank you in advance. neural networks, transformers MATLAB Answers — New Questions
Yolox dlnetwork error (Dot indexing is not supported for variables of this type.)
Hello,
When I was trying to run "Pretrained-YOLOX-Network-For-Object-Detection" downloaded from https://github.com/matlab-deep-learning/Pretrained-YOLOX-Network-For-Object-Detection, the follwong code raised an error message as follows:
model = helper.downloadPretrainedYoloX(‘yolox_s’);
net = model.net;
——————————————–
net =
Dot indexing is not supported for variables of this type.
Error in dlnetwork/isQuantized (line 1417)
b = this.PrivateNetwork.isQuantized();
Error in deep.internal.quantization.QuantizedNetworkDisplay/mixinQuantizedNetworkHeader (line 23)
strategy = net.getStrategy(isQuantized(net));
Error in dlnetwork/getHeader (line 1427)
header = this.mixinQuantizedNetworkHeader(header, className);
——————————————
I am using R2023b. Could you help me?
Thanks in advance.Hello,
When I was trying to run "Pretrained-YOLOX-Network-For-Object-Detection" downloaded from https://github.com/matlab-deep-learning/Pretrained-YOLOX-Network-For-Object-Detection, the follwong code raised an error message as follows:
model = helper.downloadPretrainedYoloX(‘yolox_s’);
net = model.net;
——————————————–
net =
Dot indexing is not supported for variables of this type.
Error in dlnetwork/isQuantized (line 1417)
b = this.PrivateNetwork.isQuantized();
Error in deep.internal.quantization.QuantizedNetworkDisplay/mixinQuantizedNetworkHeader (line 23)
strategy = net.getStrategy(isQuantized(net));
Error in dlnetwork/getHeader (line 1427)
header = this.mixinQuantizedNetworkHeader(header, className);
——————————————
I am using R2023b. Could you help me?
Thanks in advance. Hello,
When I was trying to run "Pretrained-YOLOX-Network-For-Object-Detection" downloaded from https://github.com/matlab-deep-learning/Pretrained-YOLOX-Network-For-Object-Detection, the follwong code raised an error message as follows:
model = helper.downloadPretrainedYoloX(‘yolox_s’);
net = model.net;
——————————————–
net =
Dot indexing is not supported for variables of this type.
Error in dlnetwork/isQuantized (line 1417)
b = this.PrivateNetwork.isQuantized();
Error in deep.internal.quantization.QuantizedNetworkDisplay/mixinQuantizedNetworkHeader (line 23)
strategy = net.getStrategy(isQuantized(net));
Error in dlnetwork/getHeader (line 1427)
header = this.mixinQuantizedNetworkHeader(header, className);
——————————————
I am using R2023b. Could you help me?
Thanks in advance. dlnetwork yolox MATLAB Answers — New Questions
Replication of a colorbar in MatLab
Hello everyone
I am trying to impement this colorbar:
My attempt has been the following:
colorA=[192 148 92]./255;
colorB=[1 1 1];
colorC=[82 107 120]./255;
cmap3=vertcat(interp1([0 1],[colorA;colorB],linspace(0,1,numcolors/2),’linear’),interp1([0 1],[colorB;colorC],linspace(0,1,numcolors/2+1),’linear’));
cmap3(numcolors/2+1,:)=[];
cmap3=flip(cmap3,1);
clear colorA colorB color C numcolors
which I have done trying to pick the extremal colors at each side of the aforementioned colorbar. However, I obtain something like this:
without that nice blue color evolution on the right side of it. Any suggestions on how to get closer to the reference image?Hello everyone
I am trying to impement this colorbar:
My attempt has been the following:
colorA=[192 148 92]./255;
colorB=[1 1 1];
colorC=[82 107 120]./255;
cmap3=vertcat(interp1([0 1],[colorA;colorB],linspace(0,1,numcolors/2),’linear’),interp1([0 1],[colorB;colorC],linspace(0,1,numcolors/2+1),’linear’));
cmap3(numcolors/2+1,:)=[];
cmap3=flip(cmap3,1);
clear colorA colorB color C numcolors
which I have done trying to pick the extremal colors at each side of the aforementioned colorbar. However, I obtain something like this:
without that nice blue color evolution on the right side of it. Any suggestions on how to get closer to the reference image? Hello everyone
I am trying to impement this colorbar:
My attempt has been the following:
colorA=[192 148 92]./255;
colorB=[1 1 1];
colorC=[82 107 120]./255;
cmap3=vertcat(interp1([0 1],[colorA;colorB],linspace(0,1,numcolors/2),’linear’),interp1([0 1],[colorB;colorC],linspace(0,1,numcolors/2+1),’linear’));
cmap3(numcolors/2+1,:)=[];
cmap3=flip(cmap3,1);
clear colorA colorB color C numcolors
which I have done trying to pick the extremal colors at each side of the aforementioned colorbar. However, I obtain something like this:
without that nice blue color evolution on the right side of it. Any suggestions on how to get closer to the reference image? customized colormap MATLAB Answers — New Questions
Plotting Multiple Shaded Uncertainties
Hi, I am relatively new to coding and having an issue plotting my data. I get files with element concentrations and uncertainties and I’d like to plot many of them on one figure with their corresponding figures shaded. I’ve gotten this code to work for shading the uncertainty for a single element, but I’m not sure this is accurate and the legend is offset (counting the shading as entries). Ideally I won’t need a string of code for each element (I have 11 in my code currently but we measure 140). Thanks for any input!
X = Xactdata.Date(Data); % dates & times from instrument
Elements = [Xactdata.SULPHUR(Data),Xactdata.CHLORINE(Data),Xactdata.POTASSIUM(Data),Xactdata.CALCIUM(Data),Xactdata.TITANIUM(Data),Xactdata.IRON(Data),Xactdata.COPPER(Data),Xactdata.ZINC(Data),Xactdata.ARSENIC(Data),Xactdata.BROMINE(Data),Xactdata.BARIUM(Data)]; %element concentration
E_err = [Xactdata.S_U(Data),Xactdata.Cl_U(Data),Xactdata.K_U(Data),Xactdata.Ca_U(Data),Xactdata.Ti_U(Data),Xactdata.Fe_U(Data),Xactdata.Cu_U(Data),Xactdata.Zn_U(Data),Xactdata.As_U(Data),Xactdata.Br_U(Data),Xactdata.Ba_U(Data)]; %element uncertainty
E_Labels = {"S","Cl","K","Ca","Ti","Fe","Cu","Zn","As","Br","Ba"};
figure
for i = 1:11 %number of elements plotted
plot(X, Elements(:,i))
hold on
patch([x; flip(x)], [Elements(:,i)-E_err(:,i); flip(Elements(:,i)+E_err(:,i))], ‘b’, ‘FaceAlpha’,0.25, ‘EdgeColor’,’none’)
end
legend(E_Labels)
title(‘Element Concentrations’)
ylabel(‘Concentration (ng/m^3)’)
xlabel(‘Date (UTC)’)Hi, I am relatively new to coding and having an issue plotting my data. I get files with element concentrations and uncertainties and I’d like to plot many of them on one figure with their corresponding figures shaded. I’ve gotten this code to work for shading the uncertainty for a single element, but I’m not sure this is accurate and the legend is offset (counting the shading as entries). Ideally I won’t need a string of code for each element (I have 11 in my code currently but we measure 140). Thanks for any input!
X = Xactdata.Date(Data); % dates & times from instrument
Elements = [Xactdata.SULPHUR(Data),Xactdata.CHLORINE(Data),Xactdata.POTASSIUM(Data),Xactdata.CALCIUM(Data),Xactdata.TITANIUM(Data),Xactdata.IRON(Data),Xactdata.COPPER(Data),Xactdata.ZINC(Data),Xactdata.ARSENIC(Data),Xactdata.BROMINE(Data),Xactdata.BARIUM(Data)]; %element concentration
E_err = [Xactdata.S_U(Data),Xactdata.Cl_U(Data),Xactdata.K_U(Data),Xactdata.Ca_U(Data),Xactdata.Ti_U(Data),Xactdata.Fe_U(Data),Xactdata.Cu_U(Data),Xactdata.Zn_U(Data),Xactdata.As_U(Data),Xactdata.Br_U(Data),Xactdata.Ba_U(Data)]; %element uncertainty
E_Labels = {"S","Cl","K","Ca","Ti","Fe","Cu","Zn","As","Br","Ba"};
figure
for i = 1:11 %number of elements plotted
plot(X, Elements(:,i))
hold on
patch([x; flip(x)], [Elements(:,i)-E_err(:,i); flip(Elements(:,i)+E_err(:,i))], ‘b’, ‘FaceAlpha’,0.25, ‘EdgeColor’,’none’)
end
legend(E_Labels)
title(‘Element Concentrations’)
ylabel(‘Concentration (ng/m^3)’)
xlabel(‘Date (UTC)’) Hi, I am relatively new to coding and having an issue plotting my data. I get files with element concentrations and uncertainties and I’d like to plot many of them on one figure with their corresponding figures shaded. I’ve gotten this code to work for shading the uncertainty for a single element, but I’m not sure this is accurate and the legend is offset (counting the shading as entries). Ideally I won’t need a string of code for each element (I have 11 in my code currently but we measure 140). Thanks for any input!
X = Xactdata.Date(Data); % dates & times from instrument
Elements = [Xactdata.SULPHUR(Data),Xactdata.CHLORINE(Data),Xactdata.POTASSIUM(Data),Xactdata.CALCIUM(Data),Xactdata.TITANIUM(Data),Xactdata.IRON(Data),Xactdata.COPPER(Data),Xactdata.ZINC(Data),Xactdata.ARSENIC(Data),Xactdata.BROMINE(Data),Xactdata.BARIUM(Data)]; %element concentration
E_err = [Xactdata.S_U(Data),Xactdata.Cl_U(Data),Xactdata.K_U(Data),Xactdata.Ca_U(Data),Xactdata.Ti_U(Data),Xactdata.Fe_U(Data),Xactdata.Cu_U(Data),Xactdata.Zn_U(Data),Xactdata.As_U(Data),Xactdata.Br_U(Data),Xactdata.Ba_U(Data)]; %element uncertainty
E_Labels = {"S","Cl","K","Ca","Ti","Fe","Cu","Zn","As","Br","Ba"};
figure
for i = 1:11 %number of elements plotted
plot(X, Elements(:,i))
hold on
patch([x; flip(x)], [Elements(:,i)-E_err(:,i); flip(Elements(:,i)+E_err(:,i))], ‘b’, ‘FaceAlpha’,0.25, ‘EdgeColor’,’none’)
end
legend(E_Labels)
title(‘Element Concentrations’)
ylabel(‘Concentration (ng/m^3)’)
xlabel(‘Date (UTC)’) plotting, data, uncertainty, std, data import, figure MATLAB Answers — New Questions
Split array into groups of close numbers
Greetings,
Is there a built-in function in MATLAB to split an 1D array into groups of close numbers?
For example, I have an array
a = [1 2 3 10 11]
and want to split it into N = 2 groups. I expect to see something like
result{1} = [1 2 3]
result{2} = [10 11]Greetings,
Is there a built-in function in MATLAB to split an 1D array into groups of close numbers?
For example, I have an array
a = [1 2 3 10 11]
and want to split it into N = 2 groups. I expect to see something like
result{1} = [1 2 3]
result{2} = [10 11] Greetings,
Is there a built-in function in MATLAB to split an 1D array into groups of close numbers?
For example, I have an array
a = [1 2 3 10 11]
and want to split it into N = 2 groups. I expect to see something like
result{1} = [1 2 3]
result{2} = [10 11] array MATLAB Answers — New Questions