Category: Matlab
Category Archives: Matlab
second trial license won’t load
I have a trial license set to expire in 2 days, so I have received a new trial license for another month. Trying install it says I already have the items so can’t load them. Do I have to wait for the current one to expire? Or do I have to unload the old ones first?I have a trial license set to expire in 2 days, so I have received a new trial license for another month. Trying install it says I already have the items so can’t load them. Do I have to wait for the current one to expire? Or do I have to unload the old ones first? I have a trial license set to expire in 2 days, so I have received a new trial license for another month. Trying install it says I already have the items so can’t load them. Do I have to wait for the current one to expire? Or do I have to unload the old ones first? trial license MATLAB Answers — New Questions
Does struct manipulation work in place when using arrayfun on an array of structs?
I would like to better understand how arrays of structured data are handled when they are manipulated using arrayfun. I’ve created a minimal example below to show the kind of situation I’m looking at. In this example, I’m applying a function to each struct in an array of structs using arrayfun to manipulate the structures by adding an additional field. Does this code work "in place" on the structs in the array, only allocating new memory for the new field? If this will copy the structures (or the entire array) as the fields are added, then it seems better to use a loop than arrayfun. I’d appreciate any insight into how the memory is managed during this kind of operation.
s = struct("x", {1, 2, 3});
s = arrayfun(@update, s);
function s = update(s)
s.y = s.x^2;
endI would like to better understand how arrays of structured data are handled when they are manipulated using arrayfun. I’ve created a minimal example below to show the kind of situation I’m looking at. In this example, I’m applying a function to each struct in an array of structs using arrayfun to manipulate the structures by adding an additional field. Does this code work "in place" on the structs in the array, only allocating new memory for the new field? If this will copy the structures (or the entire array) as the fields are added, then it seems better to use a loop than arrayfun. I’d appreciate any insight into how the memory is managed during this kind of operation.
s = struct("x", {1, 2, 3});
s = arrayfun(@update, s);
function s = update(s)
s.y = s.x^2;
end I would like to better understand how arrays of structured data are handled when they are manipulated using arrayfun. I’ve created a minimal example below to show the kind of situation I’m looking at. In this example, I’m applying a function to each struct in an array of structs using arrayfun to manipulate the structures by adding an additional field. Does this code work "in place" on the structs in the array, only allocating new memory for the new field? If this will copy the structures (or the entire array) as the fields are added, then it seems better to use a loop than arrayfun. I’d appreciate any insight into how the memory is managed during this kind of operation.
s = struct("x", {1, 2, 3});
s = arrayfun(@update, s);
function s = update(s)
s.y = s.x^2;
end struct, arrayfun, struct arrays, memory, speed, performance MATLAB Answers — New Questions
Using fmincon to solve objective function in integral form.
Hello, I’m attempting to solve an optimal control problem using the fmincon function however I have very little experience with it. I’m wondering if there is some fundamental flaw to my code or if there is a more obscure mistake like using the trapz function for integration. My current batch of code is no longer spitting out errors so trying to troubleshoot my way to a solution has slowed down.
The problem is as follows:
And here is the code:
%% Optimization
clear all
close all
clc
%Initialize constants
global U tspan N div
tspan = 10;
div = 10;
N = tspan*div;
control_ic = [linspace(0, 10, 1/5*N), linspace(10, 0, 4/5*N)]; %Control profile guess
%% Routine
u_t = fmincon(@fun, control_ic, [], [],[],[], [], [], [], optimoptions(‘fmincon’, ‘MaxFunctionEvaluations’, 1e5))
function [J] = fun(u) %Objective function
global U tspan div
U = u;
dynamic_ic = [2;2]; %Initial Conditions
[t, X] = ode45(@dynamics, [0 tspan], dynamic_ic); %Find x, xd using u
x = X(:, 1);
xd = X(:, 2);
x_cost = trapz(tspan/length(t), 2*x.^2 + 2*xd.^2); %Calculate objective function
finalx_cost = x(length(x))^2;
control_cost = trapz(div^(-1), .1*u.^2);
J = x_cost + finalx_cost + control_cost;
end
%System Dynamics
function [X] = dynamics(t, x)
global U tspan N
xd = x(2);
vd = -.2*x(2) – 3*x(1) + interp1(linspace(0, tspan, N), U, t);
X = [xd; vd];
endHello, I’m attempting to solve an optimal control problem using the fmincon function however I have very little experience with it. I’m wondering if there is some fundamental flaw to my code or if there is a more obscure mistake like using the trapz function for integration. My current batch of code is no longer spitting out errors so trying to troubleshoot my way to a solution has slowed down.
The problem is as follows:
And here is the code:
%% Optimization
clear all
close all
clc
%Initialize constants
global U tspan N div
tspan = 10;
div = 10;
N = tspan*div;
control_ic = [linspace(0, 10, 1/5*N), linspace(10, 0, 4/5*N)]; %Control profile guess
%% Routine
u_t = fmincon(@fun, control_ic, [], [],[],[], [], [], [], optimoptions(‘fmincon’, ‘MaxFunctionEvaluations’, 1e5))
function [J] = fun(u) %Objective function
global U tspan div
U = u;
dynamic_ic = [2;2]; %Initial Conditions
[t, X] = ode45(@dynamics, [0 tspan], dynamic_ic); %Find x, xd using u
x = X(:, 1);
xd = X(:, 2);
x_cost = trapz(tspan/length(t), 2*x.^2 + 2*xd.^2); %Calculate objective function
finalx_cost = x(length(x))^2;
control_cost = trapz(div^(-1), .1*u.^2);
J = x_cost + finalx_cost + control_cost;
end
%System Dynamics
function [X] = dynamics(t, x)
global U tspan N
xd = x(2);
vd = -.2*x(2) – 3*x(1) + interp1(linspace(0, tspan, N), U, t);
X = [xd; vd];
end Hello, I’m attempting to solve an optimal control problem using the fmincon function however I have very little experience with it. I’m wondering if there is some fundamental flaw to my code or if there is a more obscure mistake like using the trapz function for integration. My current batch of code is no longer spitting out errors so trying to troubleshoot my way to a solution has slowed down.
The problem is as follows:
And here is the code:
%% Optimization
clear all
close all
clc
%Initialize constants
global U tspan N div
tspan = 10;
div = 10;
N = tspan*div;
control_ic = [linspace(0, 10, 1/5*N), linspace(10, 0, 4/5*N)]; %Control profile guess
%% Routine
u_t = fmincon(@fun, control_ic, [], [],[],[], [], [], [], optimoptions(‘fmincon’, ‘MaxFunctionEvaluations’, 1e5))
function [J] = fun(u) %Objective function
global U tspan div
U = u;
dynamic_ic = [2;2]; %Initial Conditions
[t, X] = ode45(@dynamics, [0 tspan], dynamic_ic); %Find x, xd using u
x = X(:, 1);
xd = X(:, 2);
x_cost = trapz(tspan/length(t), 2*x.^2 + 2*xd.^2); %Calculate objective function
finalx_cost = x(length(x))^2;
control_cost = trapz(div^(-1), .1*u.^2);
J = x_cost + finalx_cost + control_cost;
end
%System Dynamics
function [X] = dynamics(t, x)
global U tspan N
xd = x(2);
vd = -.2*x(2) – 3*x(1) + interp1(linspace(0, tspan, N), U, t);
X = [xd; vd];
end optimization, fmincon, ode45 MATLAB Answers — New Questions
Find State Space Representation of Linearized non-linear System to find State Space Representation in Canonical form MATLAB
I have the following non-linear system and accompanying ODE:
I have the following ODE45 solution:
fun = @(t,X)odefun(X,K,C,M,F(t),resSize);
[t_ode,X_answer] = ode45(fun,tspan,X_0);
The input matrices are stiffness K(X), damping C mass M, and force F. resSize is the total number of masses in the system. To find the solution indirectly I introduced a change of variables to reduce the non-linear ODE to a first order linear ODE.
I would like to find the state space (SS) representation of my linearized non-linear system and corresponding ODE. More specifically, I would like to find the SS matrices A,B,C,D. I did not explicitly perform the change of variables. Rather, MATLAB did it for me. The ultimate goal of finding the SS representation (matrices A,B,C,D) is to then be able to find the canonical form of the non-linear ODE. I’m not sure if this can be done with a transfer function estimate of my ODE45 solution or some other MATLAB tool.I have the following non-linear system and accompanying ODE:
I have the following ODE45 solution:
fun = @(t,X)odefun(X,K,C,M,F(t),resSize);
[t_ode,X_answer] = ode45(fun,tspan,X_0);
The input matrices are stiffness K(X), damping C mass M, and force F. resSize is the total number of masses in the system. To find the solution indirectly I introduced a change of variables to reduce the non-linear ODE to a first order linear ODE.
I would like to find the state space (SS) representation of my linearized non-linear system and corresponding ODE. More specifically, I would like to find the SS matrices A,B,C,D. I did not explicitly perform the change of variables. Rather, MATLAB did it for me. The ultimate goal of finding the SS representation (matrices A,B,C,D) is to then be able to find the canonical form of the non-linear ODE. I’m not sure if this can be done with a transfer function estimate of my ODE45 solution or some other MATLAB tool. I have the following non-linear system and accompanying ODE:
I have the following ODE45 solution:
fun = @(t,X)odefun(X,K,C,M,F(t),resSize);
[t_ode,X_answer] = ode45(fun,tspan,X_0);
The input matrices are stiffness K(X), damping C mass M, and force F. resSize is the total number of masses in the system. To find the solution indirectly I introduced a change of variables to reduce the non-linear ODE to a first order linear ODE.
I would like to find the state space (SS) representation of my linearized non-linear system and corresponding ODE. More specifically, I would like to find the SS matrices A,B,C,D. I did not explicitly perform the change of variables. Rather, MATLAB did it for me. The ultimate goal of finding the SS representation (matrices A,B,C,D) is to then be able to find the canonical form of the non-linear ODE. I’m not sure if this can be done with a transfer function estimate of my ODE45 solution or some other MATLAB tool. transfer function, nonlinear, ode45, ode, matlab function, system, model MATLAB Answers — New Questions
How to apply PCA for my dataset
Hi,
I am trying to apply pca on my dataset but I am not able to get bioplot. I just need bioplot for my data. Please help me. I am very new to Matlab.
I have attached by dataset
ThanksHi,
I am trying to apply pca on my dataset but I am not able to get bioplot. I just need bioplot for my data. Please help me. I am very new to Matlab.
I have attached by dataset
Thanks Hi,
I am trying to apply pca on my dataset but I am not able to get bioplot. I just need bioplot for my data. Please help me. I am very new to Matlab.
I have attached by dataset
Thanks pca MATLAB Answers — New Questions
using if else statements to assign a value to a variable based on the value of a specific element in a matrix
I’ve created a matrix and I’m trying to write a for loop and within the for loop, and I have a variable, p, that I want to change based on a specific element within a matrix that changes with every loop
Here’s what I have:
if M(j,k)>0
p(j,k)=0.9;
elseif M(j,k)<0
p(j,k)=0.1;
elseif M(j,k)==0
p(j,k)=0.5;
end
However, when I try to run it, it just creates p as equalling 0.5 and I get an "index in position 2 exceeds array bounds"
Here’s an example of how I’m trying to run it
p(y(j),z1(k))*(n1*Fd(xp(i),zp(j),y(k),tt+1)
So what I’m trying to say here is that if we have value j, modified by y, and value k, modified by z1, looking at that placement in matrix M, if its above 0, then p = 0.9I’ve created a matrix and I’m trying to write a for loop and within the for loop, and I have a variable, p, that I want to change based on a specific element within a matrix that changes with every loop
Here’s what I have:
if M(j,k)>0
p(j,k)=0.9;
elseif M(j,k)<0
p(j,k)=0.1;
elseif M(j,k)==0
p(j,k)=0.5;
end
However, when I try to run it, it just creates p as equalling 0.5 and I get an "index in position 2 exceeds array bounds"
Here’s an example of how I’m trying to run it
p(y(j),z1(k))*(n1*Fd(xp(i),zp(j),y(k),tt+1)
So what I’m trying to say here is that if we have value j, modified by y, and value k, modified by z1, looking at that placement in matrix M, if its above 0, then p = 0.9 I’ve created a matrix and I’m trying to write a for loop and within the for loop, and I have a variable, p, that I want to change based on a specific element within a matrix that changes with every loop
Here’s what I have:
if M(j,k)>0
p(j,k)=0.9;
elseif M(j,k)<0
p(j,k)=0.1;
elseif M(j,k)==0
p(j,k)=0.5;
end
However, when I try to run it, it just creates p as equalling 0.5 and I get an "index in position 2 exceeds array bounds"
Here’s an example of how I’m trying to run it
p(y(j),z1(k))*(n1*Fd(xp(i),zp(j),y(k),tt+1)
So what I’m trying to say here is that if we have value j, modified by y, and value k, modified by z1, looking at that placement in matrix M, if its above 0, then p = 0.9 matrix array, if statement, for loop MATLAB Answers — New Questions
Why can I not generate a shareable link for my self-paced training that I completed in an older release of MATLAB?
I completed the R2022a version for MATLAB Onramp but I cannot generate a shareable link. Since my school does not does not allow PDF as proof of certification, I need a shareable link. How can I get a shareable link for my self-paced training that I completed using an older release of MATLAB?I completed the R2022a version for MATLAB Onramp but I cannot generate a shareable link. Since my school does not does not allow PDF as proof of certification, I need a shareable link. How can I get a shareable link for my self-paced training that I completed using an older release of MATLAB? I completed the R2022a version for MATLAB Onramp but I cannot generate a shareable link. Since my school does not does not allow PDF as proof of certification, I need a shareable link. How can I get a shareable link for my self-paced training that I completed using an older release of MATLAB? certificate MATLAB Answers — New Questions
I am trying to form a conditional loop that shows the growth of money, I put in $1000 every year and it grows by 85 for ten years but keep returning one value
I am trying to make it add $1000 every year and have an 8% return over 10 years but don’t know how to access my previous value in my loop
money=1000;
supersaver=1000;
y=zeros(1,10);
for i=1:10
y(i)=(money+supersaver)*1.08
endI am trying to make it add $1000 every year and have an 8% return over 10 years but don’t know how to access my previous value in my loop
money=1000;
supersaver=1000;
y=zeros(1,10);
for i=1:10
y(i)=(money+supersaver)*1.08
end I am trying to make it add $1000 every year and have an 8% return over 10 years but don’t know how to access my previous value in my loop
money=1000;
supersaver=1000;
y=zeros(1,10);
for i=1:10
y(i)=(money+supersaver)*1.08
end for loop MATLAB Answers — New Questions
Error using sym/matlabFunction>getOptions “Invalid Values”
I’m trying to write a script to solve an ODE using Symbolic Math Toolbox as well as some other numerical solutions. However, when I attempt to convert the solution of the ODE into a function so that I can use it with these numerical methods I encounter an error.
close all; clc; clear;
% Constants
t0 = 1; % initial time
tf = 2; % final time
stepSize = 0.5; % step size for numerical methods
syms t y(t) % Define symbolic variables
% MATLAB Symbolic Math Toolbox
% Define the ODE
ode = t^2*diff(y,t,2) – 2*t*diff(y,t) + 2*y == 0;
% THE ISSUE ARISES HERE
odeFunction = matlabFunction(rhs(ode), ‘Vars’, {t, y});
% Solve the ODE symbolically
sol = dsolve(ode);
% Display the solution
disp(sol);
% Euler’s Method
[t_euler, y_euler] = Euler(odeFunction, 4, tf, stepSize);
fprintf(‘n’);
% Improved Euler’s Method
[t_improved, y_improved] = EulersImproved(odeFunction, 4, tf, stepSize);
% Euler’s function implementation.
function [t, y] = Euler(odeFunction, initialValue, targetValue, stepSize)
% Initialize arrays to store time and solution values
t = 1:stepSize:targetValue;
y = zeros(size(t));
% Set initial value
y(1) = initialValue;
% Euler method to solve the ODE
for i = 1:length(t) – 1
% Compute the next value using Euler’s method
y(i + 1) = y(i) + stepSize * odeFunction(t(i), y(i));
end
% Display the final result at the target value
fprintf(‘The value of the equation, using Eulers Method, at x = %.2f is %.4fn’, targetValue, y(end));
end
% Improved Euler’s function implementation.
function [t, y] = EulersImproved(odeFunction, initialValue, targetValue, stepSize)
% Initialize arrays to store time and solution values
t = 1:stepSize:targetValue;
y = zeros(size(t));
% Set initial value
y(1) = initialValue;
% Improved Euler’s method to solve the ODE
for i = 1:length(t) – 1
% Predictor step
y_pred = y(i) + stepSize * odeFunction(t(i), y(i));
% Corrector step
y(i + 1) = y(i) + 0.5 * stepSize * (odeFunction(t(i), y(i)) + odeFunction(t(i + 1), y_pred));
end
% Display the final result at the target value
fprintf(‘The value of the equation, using the Improved Eulers Method, at x = %.2f is %.4fn’, targetValue, y(end));
end
And it gives the error:
The value of ‘Vars’ is invalid.
‘Vars’ value must be a character
vector, a 1-dimensional cell array of
character vectors, a 1-dimensional
cell array of symbolic variables or
arrays of symbolic variables, or an
array of symbolic variables.
Any help would be greatly appreciated!I’m trying to write a script to solve an ODE using Symbolic Math Toolbox as well as some other numerical solutions. However, when I attempt to convert the solution of the ODE into a function so that I can use it with these numerical methods I encounter an error.
close all; clc; clear;
% Constants
t0 = 1; % initial time
tf = 2; % final time
stepSize = 0.5; % step size for numerical methods
syms t y(t) % Define symbolic variables
% MATLAB Symbolic Math Toolbox
% Define the ODE
ode = t^2*diff(y,t,2) – 2*t*diff(y,t) + 2*y == 0;
% THE ISSUE ARISES HERE
odeFunction = matlabFunction(rhs(ode), ‘Vars’, {t, y});
% Solve the ODE symbolically
sol = dsolve(ode);
% Display the solution
disp(sol);
% Euler’s Method
[t_euler, y_euler] = Euler(odeFunction, 4, tf, stepSize);
fprintf(‘n’);
% Improved Euler’s Method
[t_improved, y_improved] = EulersImproved(odeFunction, 4, tf, stepSize);
% Euler’s function implementation.
function [t, y] = Euler(odeFunction, initialValue, targetValue, stepSize)
% Initialize arrays to store time and solution values
t = 1:stepSize:targetValue;
y = zeros(size(t));
% Set initial value
y(1) = initialValue;
% Euler method to solve the ODE
for i = 1:length(t) – 1
% Compute the next value using Euler’s method
y(i + 1) = y(i) + stepSize * odeFunction(t(i), y(i));
end
% Display the final result at the target value
fprintf(‘The value of the equation, using Eulers Method, at x = %.2f is %.4fn’, targetValue, y(end));
end
% Improved Euler’s function implementation.
function [t, y] = EulersImproved(odeFunction, initialValue, targetValue, stepSize)
% Initialize arrays to store time and solution values
t = 1:stepSize:targetValue;
y = zeros(size(t));
% Set initial value
y(1) = initialValue;
% Improved Euler’s method to solve the ODE
for i = 1:length(t) – 1
% Predictor step
y_pred = y(i) + stepSize * odeFunction(t(i), y(i));
% Corrector step
y(i + 1) = y(i) + 0.5 * stepSize * (odeFunction(t(i), y(i)) + odeFunction(t(i + 1), y_pred));
end
% Display the final result at the target value
fprintf(‘The value of the equation, using the Improved Eulers Method, at x = %.2f is %.4fn’, targetValue, y(end));
end
And it gives the error:
The value of ‘Vars’ is invalid.
‘Vars’ value must be a character
vector, a 1-dimensional cell array of
character vectors, a 1-dimensional
cell array of symbolic variables or
arrays of symbolic variables, or an
array of symbolic variables.
Any help would be greatly appreciated! I’m trying to write a script to solve an ODE using Symbolic Math Toolbox as well as some other numerical solutions. However, when I attempt to convert the solution of the ODE into a function so that I can use it with these numerical methods I encounter an error.
close all; clc; clear;
% Constants
t0 = 1; % initial time
tf = 2; % final time
stepSize = 0.5; % step size for numerical methods
syms t y(t) % Define symbolic variables
% MATLAB Symbolic Math Toolbox
% Define the ODE
ode = t^2*diff(y,t,2) – 2*t*diff(y,t) + 2*y == 0;
% THE ISSUE ARISES HERE
odeFunction = matlabFunction(rhs(ode), ‘Vars’, {t, y});
% Solve the ODE symbolically
sol = dsolve(ode);
% Display the solution
disp(sol);
% Euler’s Method
[t_euler, y_euler] = Euler(odeFunction, 4, tf, stepSize);
fprintf(‘n’);
% Improved Euler’s Method
[t_improved, y_improved] = EulersImproved(odeFunction, 4, tf, stepSize);
% Euler’s function implementation.
function [t, y] = Euler(odeFunction, initialValue, targetValue, stepSize)
% Initialize arrays to store time and solution values
t = 1:stepSize:targetValue;
y = zeros(size(t));
% Set initial value
y(1) = initialValue;
% Euler method to solve the ODE
for i = 1:length(t) – 1
% Compute the next value using Euler’s method
y(i + 1) = y(i) + stepSize * odeFunction(t(i), y(i));
end
% Display the final result at the target value
fprintf(‘The value of the equation, using Eulers Method, at x = %.2f is %.4fn’, targetValue, y(end));
end
% Improved Euler’s function implementation.
function [t, y] = EulersImproved(odeFunction, initialValue, targetValue, stepSize)
% Initialize arrays to store time and solution values
t = 1:stepSize:targetValue;
y = zeros(size(t));
% Set initial value
y(1) = initialValue;
% Improved Euler’s method to solve the ODE
for i = 1:length(t) – 1
% Predictor step
y_pred = y(i) + stepSize * odeFunction(t(i), y(i));
% Corrector step
y(i + 1) = y(i) + 0.5 * stepSize * (odeFunction(t(i), y(i)) + odeFunction(t(i + 1), y_pred));
end
% Display the final result at the target value
fprintf(‘The value of the equation, using the Improved Eulers Method, at x = %.2f is %.4fn’, targetValue, y(end));
end
And it gives the error:
The value of ‘Vars’ is invalid.
‘Vars’ value must be a character
vector, a 1-dimensional cell array of
character vectors, a 1-dimensional
cell array of symbolic variables or
arrays of symbolic variables, or an
array of symbolic variables.
Any help would be greatly appreciated! vars, error MATLAB Answers — New Questions
Square wave with randomly varying frequency
This is the code of a square wave with 200 khz frequency.. The frequency should be varied randomly… The variation in the frequency range is between 266.6 khz to 133.3 khz. This is my condition.. while trying this code the square wave is not coming properly it seems like a traiangle wave.. i need a proper square.
min_freq = 133333;
max_freq = 266666;
duty_cycle = 50;
t = 0: 0.0000025:1;
Amplitude = 1;
% Generate a random frequency within the specified range
frequency = min_freq + rand(1, length(t)) .* (max_freq – min_freq);
% Generate a square wave with the random frequency and duty cycle
square_wave = Amplitude*square(2 * pi * frequency .* t, duty_cycle);
% Plot the square wave
plot(t, square_wave);
axis([0 0.005 -2 2 ]);
grid on;This is the code of a square wave with 200 khz frequency.. The frequency should be varied randomly… The variation in the frequency range is between 266.6 khz to 133.3 khz. This is my condition.. while trying this code the square wave is not coming properly it seems like a traiangle wave.. i need a proper square.
min_freq = 133333;
max_freq = 266666;
duty_cycle = 50;
t = 0: 0.0000025:1;
Amplitude = 1;
% Generate a random frequency within the specified range
frequency = min_freq + rand(1, length(t)) .* (max_freq – min_freq);
% Generate a square wave with the random frequency and duty cycle
square_wave = Amplitude*square(2 * pi * frequency .* t, duty_cycle);
% Plot the square wave
plot(t, square_wave);
axis([0 0.005 -2 2 ]);
grid on; This is the code of a square wave with 200 khz frequency.. The frequency should be varied randomly… The variation in the frequency range is between 266.6 khz to 133.3 khz. This is my condition.. while trying this code the square wave is not coming properly it seems like a traiangle wave.. i need a proper square.
min_freq = 133333;
max_freq = 266666;
duty_cycle = 50;
t = 0: 0.0000025:1;
Amplitude = 1;
% Generate a random frequency within the specified range
frequency = min_freq + rand(1, length(t)) .* (max_freq – min_freq);
% Generate a square wave with the random frequency and duty cycle
square_wave = Amplitude*square(2 * pi * frequency .* t, duty_cycle);
% Plot the square wave
plot(t, square_wave);
axis([0 0.005 -2 2 ]);
grid on; random square wave MATLAB Answers — New Questions
I don’t understand busy modes of a timer object
TL;DR: What is the difference between timers using the BusyMode options drop and queue, and the ExecutionMode options fixedDelay and fixedRate? Different parts of the documentation seem to say different things.
I am trying to understand the details of how the timer object works, but am having trouble. I am using the timer help page, and the more detailed article "Handling Timer Queuing Conflicts".
https://www.mathworks.com/help/releases/R2022b/matlab/ref/timer.html
https://www.mathworks.com/help/releases/R2022b/matlab/matlab_prog/handling-timer-queuing-conflicts.html
I understand that ExecutionMode="fixedSpacing" effectively adds the execution time of the timer callback to the timer period*, which also means that the callback can never be called while the callback is running. I also understand that when ExecutionMode="fixedRate", I need to use BusyMode to prevent callbacks colliding, and that I can use BusyMode="error" to throw an error (or take another action) if that would happen.
However, I am confused by the other two BusyModes, drop and queue, and how they compare to ExecutionMode="fixedDelay".
The timer help page says that BusyMode="drop" will "drop" the new task "when a timer has to execute TimerFcn before the completion of previous execution of the TimerFcn" and that "skipping of TimerFcn calls" is possible. To me, this suggests that an instance of TimerFcn will be skipped and that the timer period immediately begins afresh.
In contrast, BusyMode="queue" will "wait for [the execution] queue to clear, and then enter task in queue", and "adjusts Period property to manage tasks in execution queue". To me, this suggests that the new TimerFcn will start as soon as the old one finishes, and that it will increase its period (perhaps hidden from the user) to avoid having too many instances of TimerFcn in the queue.
When I look at the "Handling Timer Queuing Conflicts" article for more information, however, it gives an example where drop and queue behave identically! Both examples set a timer to run five times, with period 1s and a timer function that takes 1.6s to run. What I expect: when BusyMode="queue", the timer callback occurs every 1.6s; when BusyMode="drop", the timer callback occurs every 2s (the odd-numbered tasks being dropped, because the callback is running). What actually happens: in both cases, the timer callback occurs every 1.6s. This isn’t just a bug in my version of Matlab – the actual article has a table describing what should happen, and although a few of the internal details are different, it clearly shows TimerFcn being started every 1.6s (+ queue lag). The description of what happens within the timer doesn’t help all that much, since there are some details that I am sure must be mistakes (e.g. for drop, the 4th and 5th calls of the timer function are dropped twice each).
About ExecutionMode="fixedDelay", the timer help page says that the timer period starts "when the timer function callback restarts execution after a time lag due to delays in the MATLAB execution queue" (contrasting with "immediately after the timer callback function is added to the MATLAB execution queue" for ExecutionMode="fixedRate"). I would take this description to mean that fixedDelay works much like fixedRate, except that the timing is less precise because fixedDelay includes an unknown amount of queue delay. However, in the BusyMode section, the page also says, "for other values of ExecutionMode [other than fixedRate], there cannot be overlapping attempts to execute the timer callback function because the delay between executions is always relative to the completion of the previous execution". I don’t see how this can be true unless Matlab deliberately adjusts the queue lag to make this happen. Even more confusingly, the diagram actually shows fixedDelay’s timer function starting just before the previous call finishing (although it is so close that I’m sure that wasn’t intentional). When I test fixedDelay, it seems to operate identically to the fixedRate tests described above (within a few milliseconds for the queue lag). I have attached those demos to this file (run testTimers.m to demonstrate them, first with a period less than the timer function time; then with a period greater than the timer function time).
I may just have completely missed something completely obvious, but I would very much welcome enlightenment!
*Although some aspects of fixedSpacing do still puzzle me!TL;DR: What is the difference between timers using the BusyMode options drop and queue, and the ExecutionMode options fixedDelay and fixedRate? Different parts of the documentation seem to say different things.
I am trying to understand the details of how the timer object works, but am having trouble. I am using the timer help page, and the more detailed article "Handling Timer Queuing Conflicts".
https://www.mathworks.com/help/releases/R2022b/matlab/ref/timer.html
https://www.mathworks.com/help/releases/R2022b/matlab/matlab_prog/handling-timer-queuing-conflicts.html
I understand that ExecutionMode="fixedSpacing" effectively adds the execution time of the timer callback to the timer period*, which also means that the callback can never be called while the callback is running. I also understand that when ExecutionMode="fixedRate", I need to use BusyMode to prevent callbacks colliding, and that I can use BusyMode="error" to throw an error (or take another action) if that would happen.
However, I am confused by the other two BusyModes, drop and queue, and how they compare to ExecutionMode="fixedDelay".
The timer help page says that BusyMode="drop" will "drop" the new task "when a timer has to execute TimerFcn before the completion of previous execution of the TimerFcn" and that "skipping of TimerFcn calls" is possible. To me, this suggests that an instance of TimerFcn will be skipped and that the timer period immediately begins afresh.
In contrast, BusyMode="queue" will "wait for [the execution] queue to clear, and then enter task in queue", and "adjusts Period property to manage tasks in execution queue". To me, this suggests that the new TimerFcn will start as soon as the old one finishes, and that it will increase its period (perhaps hidden from the user) to avoid having too many instances of TimerFcn in the queue.
When I look at the "Handling Timer Queuing Conflicts" article for more information, however, it gives an example where drop and queue behave identically! Both examples set a timer to run five times, with period 1s and a timer function that takes 1.6s to run. What I expect: when BusyMode="queue", the timer callback occurs every 1.6s; when BusyMode="drop", the timer callback occurs every 2s (the odd-numbered tasks being dropped, because the callback is running). What actually happens: in both cases, the timer callback occurs every 1.6s. This isn’t just a bug in my version of Matlab – the actual article has a table describing what should happen, and although a few of the internal details are different, it clearly shows TimerFcn being started every 1.6s (+ queue lag). The description of what happens within the timer doesn’t help all that much, since there are some details that I am sure must be mistakes (e.g. for drop, the 4th and 5th calls of the timer function are dropped twice each).
About ExecutionMode="fixedDelay", the timer help page says that the timer period starts "when the timer function callback restarts execution after a time lag due to delays in the MATLAB execution queue" (contrasting with "immediately after the timer callback function is added to the MATLAB execution queue" for ExecutionMode="fixedRate"). I would take this description to mean that fixedDelay works much like fixedRate, except that the timing is less precise because fixedDelay includes an unknown amount of queue delay. However, in the BusyMode section, the page also says, "for other values of ExecutionMode [other than fixedRate], there cannot be overlapping attempts to execute the timer callback function because the delay between executions is always relative to the completion of the previous execution". I don’t see how this can be true unless Matlab deliberately adjusts the queue lag to make this happen. Even more confusingly, the diagram actually shows fixedDelay’s timer function starting just before the previous call finishing (although it is so close that I’m sure that wasn’t intentional). When I test fixedDelay, it seems to operate identically to the fixedRate tests described above (within a few milliseconds for the queue lag). I have attached those demos to this file (run testTimers.m to demonstrate them, first with a period less than the timer function time; then with a period greater than the timer function time).
I may just have completely missed something completely obvious, but I would very much welcome enlightenment!
*Although some aspects of fixedSpacing do still puzzle me! TL;DR: What is the difference between timers using the BusyMode options drop and queue, and the ExecutionMode options fixedDelay and fixedRate? Different parts of the documentation seem to say different things.
I am trying to understand the details of how the timer object works, but am having trouble. I am using the timer help page, and the more detailed article "Handling Timer Queuing Conflicts".
https://www.mathworks.com/help/releases/R2022b/matlab/ref/timer.html
https://www.mathworks.com/help/releases/R2022b/matlab/matlab_prog/handling-timer-queuing-conflicts.html
I understand that ExecutionMode="fixedSpacing" effectively adds the execution time of the timer callback to the timer period*, which also means that the callback can never be called while the callback is running. I also understand that when ExecutionMode="fixedRate", I need to use BusyMode to prevent callbacks colliding, and that I can use BusyMode="error" to throw an error (or take another action) if that would happen.
However, I am confused by the other two BusyModes, drop and queue, and how they compare to ExecutionMode="fixedDelay".
The timer help page says that BusyMode="drop" will "drop" the new task "when a timer has to execute TimerFcn before the completion of previous execution of the TimerFcn" and that "skipping of TimerFcn calls" is possible. To me, this suggests that an instance of TimerFcn will be skipped and that the timer period immediately begins afresh.
In contrast, BusyMode="queue" will "wait for [the execution] queue to clear, and then enter task in queue", and "adjusts Period property to manage tasks in execution queue". To me, this suggests that the new TimerFcn will start as soon as the old one finishes, and that it will increase its period (perhaps hidden from the user) to avoid having too many instances of TimerFcn in the queue.
When I look at the "Handling Timer Queuing Conflicts" article for more information, however, it gives an example where drop and queue behave identically! Both examples set a timer to run five times, with period 1s and a timer function that takes 1.6s to run. What I expect: when BusyMode="queue", the timer callback occurs every 1.6s; when BusyMode="drop", the timer callback occurs every 2s (the odd-numbered tasks being dropped, because the callback is running). What actually happens: in both cases, the timer callback occurs every 1.6s. This isn’t just a bug in my version of Matlab – the actual article has a table describing what should happen, and although a few of the internal details are different, it clearly shows TimerFcn being started every 1.6s (+ queue lag). The description of what happens within the timer doesn’t help all that much, since there are some details that I am sure must be mistakes (e.g. for drop, the 4th and 5th calls of the timer function are dropped twice each).
About ExecutionMode="fixedDelay", the timer help page says that the timer period starts "when the timer function callback restarts execution after a time lag due to delays in the MATLAB execution queue" (contrasting with "immediately after the timer callback function is added to the MATLAB execution queue" for ExecutionMode="fixedRate"). I would take this description to mean that fixedDelay works much like fixedRate, except that the timing is less precise because fixedDelay includes an unknown amount of queue delay. However, in the BusyMode section, the page also says, "for other values of ExecutionMode [other than fixedRate], there cannot be overlapping attempts to execute the timer callback function because the delay between executions is always relative to the completion of the previous execution". I don’t see how this can be true unless Matlab deliberately adjusts the queue lag to make this happen. Even more confusingly, the diagram actually shows fixedDelay’s timer function starting just before the previous call finishing (although it is so close that I’m sure that wasn’t intentional). When I test fixedDelay, it seems to operate identically to the fixedRate tests described above (within a few milliseconds for the queue lag). I have attached those demos to this file (run testTimers.m to demonstrate them, first with a period less than the timer function time; then with a period greater than the timer function time).
I may just have completely missed something completely obvious, but I would very much welcome enlightenment!
*Although some aspects of fixedSpacing do still puzzle me! timer, executionmode, busymode MATLAB Answers — New Questions
MATLAB does not print vector file even with renderer specified
Hello,
I am currently using Matlab 2023b, but the same issue pertains also to Matlab 2021b, which I still have installed. I used to export my figures (for example, contour plots etc.) with no problem via
print(‘-painters’,’a1.eps’,’-depsc’)
in 2023b I changed it obviosuly to
print(‘-vector’,’a1.eps’,’-depsc’)
It worked fine, and I could always import it into vector graphics editing software and edit there. But that is no longer true for some unknown reason. If I do it like this, part of the figure (e.g., axes, tickes, labels etc.) will be exported correctly as a vector graphics, but the plot itself is exported as a bitmap. Setting renderer explicitly to Painters, RendererMode to manual does not help. Saving as a pdf does not help either. ALso saving via save rather than print also does not help. All lead to the same result.
Any ideas on how to fix this?
I suspect the issue might be related to the Qt plugin error that I get when trying to launch some applications (even though my Python runs fine). But in principle MATLAB should not use that plugin at all, should it?
Thanks a lot in advance!
UPDATE: this is not an issue for simple plots (e.g., using plot function or even contourf function), but if I use surf function for example, then the graph is a bitmap. It used to be vector even for surf function generated plots…Hello,
I am currently using Matlab 2023b, but the same issue pertains also to Matlab 2021b, which I still have installed. I used to export my figures (for example, contour plots etc.) with no problem via
print(‘-painters’,’a1.eps’,’-depsc’)
in 2023b I changed it obviosuly to
print(‘-vector’,’a1.eps’,’-depsc’)
It worked fine, and I could always import it into vector graphics editing software and edit there. But that is no longer true for some unknown reason. If I do it like this, part of the figure (e.g., axes, tickes, labels etc.) will be exported correctly as a vector graphics, but the plot itself is exported as a bitmap. Setting renderer explicitly to Painters, RendererMode to manual does not help. Saving as a pdf does not help either. ALso saving via save rather than print also does not help. All lead to the same result.
Any ideas on how to fix this?
I suspect the issue might be related to the Qt plugin error that I get when trying to launch some applications (even though my Python runs fine). But in principle MATLAB should not use that plugin at all, should it?
Thanks a lot in advance!
UPDATE: this is not an issue for simple plots (e.g., using plot function or even contourf function), but if I use surf function for example, then the graph is a bitmap. It used to be vector even for surf function generated plots… Hello,
I am currently using Matlab 2023b, but the same issue pertains also to Matlab 2021b, which I still have installed. I used to export my figures (for example, contour plots etc.) with no problem via
print(‘-painters’,’a1.eps’,’-depsc’)
in 2023b I changed it obviosuly to
print(‘-vector’,’a1.eps’,’-depsc’)
It worked fine, and I could always import it into vector graphics editing software and edit there. But that is no longer true for some unknown reason. If I do it like this, part of the figure (e.g., axes, tickes, labels etc.) will be exported correctly as a vector graphics, but the plot itself is exported as a bitmap. Setting renderer explicitly to Painters, RendererMode to manual does not help. Saving as a pdf does not help either. ALso saving via save rather than print also does not help. All lead to the same result.
Any ideas on how to fix this?
I suspect the issue might be related to the Qt plugin error that I get when trying to launch some applications (even though my Python runs fine). But in principle MATLAB should not use that plugin at all, should it?
Thanks a lot in advance!
UPDATE: this is not an issue for simple plots (e.g., using plot function or even contourf function), but if I use surf function for example, then the graph is a bitmap. It used to be vector even for surf function generated plots… vector graphics, saving issue, renderer issue MATLAB Answers — New Questions
Image segmentation using thresholding
I have raw image of rocks like the one on the right, I want a code to get the result on the leftI have raw image of rocks like the one on the right, I want a code to get the result on the left I have raw image of rocks like the one on the right, I want a code to get the result on the left image segmentation MATLAB Answers — New Questions
Why is Run button not visible ?
Look at the snapshot attached
Does anyone know why the run button is not visible this way?Look at the snapshot attached
Does anyone know why the run button is not visible this way? Look at the snapshot attached
Does anyone know why the run button is not visible this way? run MATLAB Answers — New Questions
How I cant Plot the Spectrum of Lyapunov exponents of system versus the parameter c∈ [0, 200], with a = 10, b = 28 ?
Greetings, all. I trust you’re doing well. My intention is to generate a spectrum depicting the Lyapunov exponents of the system concerning the parameter c within the range of ( [0, 200] ), given ( a = 10 ) and ( b = 28 ). Fig(11.png).The system equations are as follows:
x’= -a * x + b * y – y * z;
y’ = x + z * x;
z’ = -c * z + y^2;
I’m employing specific codes to calculate the Lyapunov exponents for c = 2 Fig(22.png).
codes :
%%%%%%%%% system_equations %%%%%%%%%%%%%%%%%%%
% Define the system equations
function f = system_equations(t, X)
% Define the parameters
a = 10;
b = 28;
c = 2;
% Extract variables
x = X(1);
y = X(2);
z = X(3);
% Extract the Jacobian matrix Y from the extended state vector X
Y = [X(4), X(7), X(10);
X(5), X(8), X(11);
X(6), X(9), X(12)];
% Initialize the output vector
f = zeros(9, 1);
% System equations
f(1) = -a * x + b * y – y * z;
f(2) = x + z * x;
f(3) = -c * z + y^2;
% Jacobian matrix
Jac = [-a, b – z, -y;
1 + z, 0, x;
0, 2 * y, -c];
% Variational equation
f(4:12) = Jac*Y;
end
%%%%%%%%% systemequations_Lyapunov %%%%%%%%%%%%%%%%%%%
function [Texp, Lexp] = systemequations_Lyapunov(n, rhs_ext_fcn, fcn_integrator, tstart, stept, tend, ystart, ioutp)
clc;
close all;
n = 3;
rhs_ext_fcn = @system_equations;
fcn_integrator = @ode45;
tstart = 0;
stept = 0.1;
tend = 1000;
ystart = [7.2 7.8 2.3];
ioutp = 10;
n1 = n;
n2 = n1*(n1 + 1);
% Number of steps.
nits = round((tend – tstart)/stept);
% Memory allocation.
y = zeros(n2, 1);
cum = zeros(n1, 1);
y0 = y;
gsc = cum;
znorm = cum;
% Initial values.
y(1:n) = ystart(:);
for i = 1:n1
y((n1 + 1)*i) = 1.0;
end
t = tstart;
% Main loop.
for iterlya = 1:nits
% Solutuion of extended ODE system.
[T, Y] = feval(fcn_integrator, rhs_ext_fcn, [t t + stept], y);
t = t + stept;
y = Y(size(Y, 1),:);
for i = 1:n1
for j = 1:n1
y0(n1*i + j) = y(n1*j + i);
end
end
% Construct new orthonormal basis by Gram-Schmidt.
znorm(1) = 0.0;
for j = 1:n1
znorm(1) = znorm(1) + y0(n1*j+1)^2;
end
znorm(1) = sqrt(znorm(1));
for j = 1:n1
y0(n1*j + 1) = y0(n1*j + 1)/znorm(1);
end
for j = 2:n1
for k = 1:(j – 1)
gsc(k) = 0.0;
for l = 1:n1
gsc(k) = gsc(k) + y0(n1*l + j)*y0(n1*l + k);
end
end
for k = 1:n1
for l = 1:(j – 1)
y0(n1*k + j) = y0(n1*k + j) – gsc(l)*y0(n1*k + l);
end
end
znorm(j) = 0.0;
for k = 1:n1
znorm(j) = znorm(j) + y0(n1*k+j)^2;
end
znorm(j)=sqrt(znorm(j));
for k = 1:n1
y0(n1*k + j) = y0(n1*k + j)/znorm(j);
end
end
% Update running vector magnitudes.
for k = 1:n1
cum(k) = cum(k) + log(znorm(k));
end
% Normalize exponent.
for k = 1:n1
lp(k) = cum(k)/(t – tstart);
end
% Output modification.
if iterlya == 1
Lexp = lp;
Texp = t;
else
Lexp = [Lexp; lp];
Texp = [Texp; t];
end
for i = 1:n1
for j = 1:n1
y(n1*j + i) = y0(n1*i + j);
end
end
end
% Show the Lyapunov exponent values on the graph.
str1 = num2str(Lexp(nits, 1));
str2 = num2str(Lexp(nits, 2));
str3 = num2str(Lexp(nits, 3));
pl = plot(Texp, Lexp,’LineWidth’,2);
pl(1).Color = ‘b’;
pl(2).Color = ‘g’;
pl(3).Color = ‘r’;
legend(‘lambda_1’, ‘lambda_2′,’lambda_3’)
legend(‘Location’,’northeast’)
title(‘Dynamics of Lyapunov Exponents’);
text(205, 1.5, ‘lambda_1 = ‘,’Fontsize’,20);
text(220, 1.68, str1,’Fontsize’,20);
text(205, -1, ‘lambda_2 = ‘,’Fontsize’,20);
text(220, -0.73, str2,’Fontsize’,20);
text(205, -13.8, ‘lambda_3 = ‘,’Fontsize’,20);
text(220, -13.5, str3,’Fontsize’,20);
xlabel(‘Time’);
ylabel(‘Lyapunov Exponents’);
axis([-1,300, -16,6]);
set(gca,’FontSize’,20)
end
% End of plotGreetings, all. I trust you’re doing well. My intention is to generate a spectrum depicting the Lyapunov exponents of the system concerning the parameter c within the range of ( [0, 200] ), given ( a = 10 ) and ( b = 28 ). Fig(11.png).The system equations are as follows:
x’= -a * x + b * y – y * z;
y’ = x + z * x;
z’ = -c * z + y^2;
I’m employing specific codes to calculate the Lyapunov exponents for c = 2 Fig(22.png).
codes :
%%%%%%%%% system_equations %%%%%%%%%%%%%%%%%%%
% Define the system equations
function f = system_equations(t, X)
% Define the parameters
a = 10;
b = 28;
c = 2;
% Extract variables
x = X(1);
y = X(2);
z = X(3);
% Extract the Jacobian matrix Y from the extended state vector X
Y = [X(4), X(7), X(10);
X(5), X(8), X(11);
X(6), X(9), X(12)];
% Initialize the output vector
f = zeros(9, 1);
% System equations
f(1) = -a * x + b * y – y * z;
f(2) = x + z * x;
f(3) = -c * z + y^2;
% Jacobian matrix
Jac = [-a, b – z, -y;
1 + z, 0, x;
0, 2 * y, -c];
% Variational equation
f(4:12) = Jac*Y;
end
%%%%%%%%% systemequations_Lyapunov %%%%%%%%%%%%%%%%%%%
function [Texp, Lexp] = systemequations_Lyapunov(n, rhs_ext_fcn, fcn_integrator, tstart, stept, tend, ystart, ioutp)
clc;
close all;
n = 3;
rhs_ext_fcn = @system_equations;
fcn_integrator = @ode45;
tstart = 0;
stept = 0.1;
tend = 1000;
ystart = [7.2 7.8 2.3];
ioutp = 10;
n1 = n;
n2 = n1*(n1 + 1);
% Number of steps.
nits = round((tend – tstart)/stept);
% Memory allocation.
y = zeros(n2, 1);
cum = zeros(n1, 1);
y0 = y;
gsc = cum;
znorm = cum;
% Initial values.
y(1:n) = ystart(:);
for i = 1:n1
y((n1 + 1)*i) = 1.0;
end
t = tstart;
% Main loop.
for iterlya = 1:nits
% Solutuion of extended ODE system.
[T, Y] = feval(fcn_integrator, rhs_ext_fcn, [t t + stept], y);
t = t + stept;
y = Y(size(Y, 1),:);
for i = 1:n1
for j = 1:n1
y0(n1*i + j) = y(n1*j + i);
end
end
% Construct new orthonormal basis by Gram-Schmidt.
znorm(1) = 0.0;
for j = 1:n1
znorm(1) = znorm(1) + y0(n1*j+1)^2;
end
znorm(1) = sqrt(znorm(1));
for j = 1:n1
y0(n1*j + 1) = y0(n1*j + 1)/znorm(1);
end
for j = 2:n1
for k = 1:(j – 1)
gsc(k) = 0.0;
for l = 1:n1
gsc(k) = gsc(k) + y0(n1*l + j)*y0(n1*l + k);
end
end
for k = 1:n1
for l = 1:(j – 1)
y0(n1*k + j) = y0(n1*k + j) – gsc(l)*y0(n1*k + l);
end
end
znorm(j) = 0.0;
for k = 1:n1
znorm(j) = znorm(j) + y0(n1*k+j)^2;
end
znorm(j)=sqrt(znorm(j));
for k = 1:n1
y0(n1*k + j) = y0(n1*k + j)/znorm(j);
end
end
% Update running vector magnitudes.
for k = 1:n1
cum(k) = cum(k) + log(znorm(k));
end
% Normalize exponent.
for k = 1:n1
lp(k) = cum(k)/(t – tstart);
end
% Output modification.
if iterlya == 1
Lexp = lp;
Texp = t;
else
Lexp = [Lexp; lp];
Texp = [Texp; t];
end
for i = 1:n1
for j = 1:n1
y(n1*j + i) = y0(n1*i + j);
end
end
end
% Show the Lyapunov exponent values on the graph.
str1 = num2str(Lexp(nits, 1));
str2 = num2str(Lexp(nits, 2));
str3 = num2str(Lexp(nits, 3));
pl = plot(Texp, Lexp,’LineWidth’,2);
pl(1).Color = ‘b’;
pl(2).Color = ‘g’;
pl(3).Color = ‘r’;
legend(‘lambda_1’, ‘lambda_2′,’lambda_3’)
legend(‘Location’,’northeast’)
title(‘Dynamics of Lyapunov Exponents’);
text(205, 1.5, ‘lambda_1 = ‘,’Fontsize’,20);
text(220, 1.68, str1,’Fontsize’,20);
text(205, -1, ‘lambda_2 = ‘,’Fontsize’,20);
text(220, -0.73, str2,’Fontsize’,20);
text(205, -13.8, ‘lambda_3 = ‘,’Fontsize’,20);
text(220, -13.5, str3,’Fontsize’,20);
xlabel(‘Time’);
ylabel(‘Lyapunov Exponents’);
axis([-1,300, -16,6]);
set(gca,’FontSize’,20)
end
% End of plot Greetings, all. I trust you’re doing well. My intention is to generate a spectrum depicting the Lyapunov exponents of the system concerning the parameter c within the range of ( [0, 200] ), given ( a = 10 ) and ( b = 28 ). Fig(11.png).The system equations are as follows:
x’= -a * x + b * y – y * z;
y’ = x + z * x;
z’ = -c * z + y^2;
I’m employing specific codes to calculate the Lyapunov exponents for c = 2 Fig(22.png).
codes :
%%%%%%%%% system_equations %%%%%%%%%%%%%%%%%%%
% Define the system equations
function f = system_equations(t, X)
% Define the parameters
a = 10;
b = 28;
c = 2;
% Extract variables
x = X(1);
y = X(2);
z = X(3);
% Extract the Jacobian matrix Y from the extended state vector X
Y = [X(4), X(7), X(10);
X(5), X(8), X(11);
X(6), X(9), X(12)];
% Initialize the output vector
f = zeros(9, 1);
% System equations
f(1) = -a * x + b * y – y * z;
f(2) = x + z * x;
f(3) = -c * z + y^2;
% Jacobian matrix
Jac = [-a, b – z, -y;
1 + z, 0, x;
0, 2 * y, -c];
% Variational equation
f(4:12) = Jac*Y;
end
%%%%%%%%% systemequations_Lyapunov %%%%%%%%%%%%%%%%%%%
function [Texp, Lexp] = systemequations_Lyapunov(n, rhs_ext_fcn, fcn_integrator, tstart, stept, tend, ystart, ioutp)
clc;
close all;
n = 3;
rhs_ext_fcn = @system_equations;
fcn_integrator = @ode45;
tstart = 0;
stept = 0.1;
tend = 1000;
ystart = [7.2 7.8 2.3];
ioutp = 10;
n1 = n;
n2 = n1*(n1 + 1);
% Number of steps.
nits = round((tend – tstart)/stept);
% Memory allocation.
y = zeros(n2, 1);
cum = zeros(n1, 1);
y0 = y;
gsc = cum;
znorm = cum;
% Initial values.
y(1:n) = ystart(:);
for i = 1:n1
y((n1 + 1)*i) = 1.0;
end
t = tstart;
% Main loop.
for iterlya = 1:nits
% Solutuion of extended ODE system.
[T, Y] = feval(fcn_integrator, rhs_ext_fcn, [t t + stept], y);
t = t + stept;
y = Y(size(Y, 1),:);
for i = 1:n1
for j = 1:n1
y0(n1*i + j) = y(n1*j + i);
end
end
% Construct new orthonormal basis by Gram-Schmidt.
znorm(1) = 0.0;
for j = 1:n1
znorm(1) = znorm(1) + y0(n1*j+1)^2;
end
znorm(1) = sqrt(znorm(1));
for j = 1:n1
y0(n1*j + 1) = y0(n1*j + 1)/znorm(1);
end
for j = 2:n1
for k = 1:(j – 1)
gsc(k) = 0.0;
for l = 1:n1
gsc(k) = gsc(k) + y0(n1*l + j)*y0(n1*l + k);
end
end
for k = 1:n1
for l = 1:(j – 1)
y0(n1*k + j) = y0(n1*k + j) – gsc(l)*y0(n1*k + l);
end
end
znorm(j) = 0.0;
for k = 1:n1
znorm(j) = znorm(j) + y0(n1*k+j)^2;
end
znorm(j)=sqrt(znorm(j));
for k = 1:n1
y0(n1*k + j) = y0(n1*k + j)/znorm(j);
end
end
% Update running vector magnitudes.
for k = 1:n1
cum(k) = cum(k) + log(znorm(k));
end
% Normalize exponent.
for k = 1:n1
lp(k) = cum(k)/(t – tstart);
end
% Output modification.
if iterlya == 1
Lexp = lp;
Texp = t;
else
Lexp = [Lexp; lp];
Texp = [Texp; t];
end
for i = 1:n1
for j = 1:n1
y(n1*j + i) = y0(n1*i + j);
end
end
end
% Show the Lyapunov exponent values on the graph.
str1 = num2str(Lexp(nits, 1));
str2 = num2str(Lexp(nits, 2));
str3 = num2str(Lexp(nits, 3));
pl = plot(Texp, Lexp,’LineWidth’,2);
pl(1).Color = ‘b’;
pl(2).Color = ‘g’;
pl(3).Color = ‘r’;
legend(‘lambda_1’, ‘lambda_2′,’lambda_3’)
legend(‘Location’,’northeast’)
title(‘Dynamics of Lyapunov Exponents’);
text(205, 1.5, ‘lambda_1 = ‘,’Fontsize’,20);
text(220, 1.68, str1,’Fontsize’,20);
text(205, -1, ‘lambda_2 = ‘,’Fontsize’,20);
text(220, -0.73, str2,’Fontsize’,20);
text(205, -13.8, ‘lambda_3 = ‘,’Fontsize’,20);
text(220, -13.5, str3,’Fontsize’,20);
xlabel(‘Time’);
ylabel(‘Lyapunov Exponents’);
axis([-1,300, -16,6]);
set(gca,’FontSize’,20)
end
% End of plot spectrum of lyapunov exponents, bifurcations, nonlinear odes, stability analisys MATLAB Answers — New Questions
How can I get more divisions in x- and y- axes scaling when plotting with imagesc to have a clear picture and introduce the proper scaling along x- & y- axes?
clc;
[x,y] = meshgrid(linspace(-0.6, 0.6), linspace(-0.6, 0.6));
[phi,r] = cart2pol(x,y);
% Omega_r -vortex beam specification
l = 2;
p = 2;
w0 = 0.2;
R = sqrt(2).*r./w0;
RR = r./w0;
Omega01 = exp(-RR.^2);
Lpl = 0;
for m = 0:p;
Lpl = Lpl + (((-1).^m)./factorial(m)).*nchoosek(p+l,p-m).*(R.^(2.*m));
end;
Omega_r = Omega01.*(RR.^(abs(l))).*Lpl.*exp(-i.*l.*phi);
figure;
imagesc(angle(Omega_r));
colormap jet
colorbarclc;
[x,y] = meshgrid(linspace(-0.6, 0.6), linspace(-0.6, 0.6));
[phi,r] = cart2pol(x,y);
% Omega_r -vortex beam specification
l = 2;
p = 2;
w0 = 0.2;
R = sqrt(2).*r./w0;
RR = r./w0;
Omega01 = exp(-RR.^2);
Lpl = 0;
for m = 0:p;
Lpl = Lpl + (((-1).^m)./factorial(m)).*nchoosek(p+l,p-m).*(R.^(2.*m));
end;
Omega_r = Omega01.*(RR.^(abs(l))).*Lpl.*exp(-i.*l.*phi);
figure;
imagesc(angle(Omega_r));
colormap jet
colorbar clc;
[x,y] = meshgrid(linspace(-0.6, 0.6), linspace(-0.6, 0.6));
[phi,r] = cart2pol(x,y);
% Omega_r -vortex beam specification
l = 2;
p = 2;
w0 = 0.2;
R = sqrt(2).*r./w0;
RR = r./w0;
Omega01 = exp(-RR.^2);
Lpl = 0;
for m = 0:p;
Lpl = Lpl + (((-1).^m)./factorial(m)).*nchoosek(p+l,p-m).*(R.^(2.*m));
end;
Omega_r = Omega01.*(RR.^(abs(l))).*Lpl.*exp(-i.*l.*phi);
figure;
imagesc(angle(Omega_r));
colormap jet
colorbar linspace div control, axis scaling with imagesc MATLAB Answers — New Questions
Like to know if there are high schools
Like to know if there are high schools out there using Mathworks and Simulink in STEM and/or Aerospace contexts. I would like my stem classes to get more into simulation in particular rovers and drones. Anyone doing any work in this area? Also, is it too complex for, say, 14 year olds? I was looking at Arduino programming with simulink and the zumo robot but it seemed quite complex.Like to know if there are high schools out there using Mathworks and Simulink in STEM and/or Aerospace contexts. I would like my stem classes to get more into simulation in particular rovers and drones. Anyone doing any work in this area? Also, is it too complex for, say, 14 year olds? I was looking at Arduino programming with simulink and the zumo robot but it seemed quite complex. Like to know if there are high schools out there using Mathworks and Simulink in STEM and/or Aerospace contexts. I would like my stem classes to get more into simulation in particular rovers and drones. Anyone doing any work in this area? Also, is it too complex for, say, 14 year olds? I was looking at Arduino programming with simulink and the zumo robot but it seemed quite complex. simulink, drone, drones, zumo, robot, aerospace, aviation, high school, school MATLAB Answers — New Questions
Why are some of my functions ‘Undefined’ in my standalone executable compiled from MATLAB source and pcode files?
I have a MATLAB standalone app compiled from many different source code files. Some of the dependencies for this app are sensitive IP so I identified all required files using requiredFilesAndProducts and I obfuscated those sensitive dependencies (since source code is to be delivered as part of this project). Some of those dependencies use functions from other dependencies so I recursively called requiredFilesAndProducts to get a complete list of all required files. From that list, I then ran pcode against the sensitive IP and gathered all the pcode files into one location.
When I compile the standalone executable, I add the path to the pcode folder addpath(genpath(‘C:pathtopcodefolder’)) as well as the safe to distribute MATLAB source code files and compile compiler.build.standaloneApplication(‘MATLAB_SOURCE_CODE_FILE_Y.m’).
When I run the standalone app, some of the functions from the pcode will yield Undefined function ‘Some_Function’ for input arguments of type ‘char’. Error in PCODE_FILE_X Error in MATLAB_SOURCE_CODE_FILE_Y (line 85) despite the fact that Some_Function has a corresponding pcode file in the pcode folder.
I tried listing at the bottom of the main function for the standalone app all the pcode files as other threads suggest but that doesn’t solve the problem for pcode files referencing functions from other pcode files. Any ideas?I have a MATLAB standalone app compiled from many different source code files. Some of the dependencies for this app are sensitive IP so I identified all required files using requiredFilesAndProducts and I obfuscated those sensitive dependencies (since source code is to be delivered as part of this project). Some of those dependencies use functions from other dependencies so I recursively called requiredFilesAndProducts to get a complete list of all required files. From that list, I then ran pcode against the sensitive IP and gathered all the pcode files into one location.
When I compile the standalone executable, I add the path to the pcode folder addpath(genpath(‘C:pathtopcodefolder’)) as well as the safe to distribute MATLAB source code files and compile compiler.build.standaloneApplication(‘MATLAB_SOURCE_CODE_FILE_Y.m’).
When I run the standalone app, some of the functions from the pcode will yield Undefined function ‘Some_Function’ for input arguments of type ‘char’. Error in PCODE_FILE_X Error in MATLAB_SOURCE_CODE_FILE_Y (line 85) despite the fact that Some_Function has a corresponding pcode file in the pcode folder.
I tried listing at the bottom of the main function for the standalone app all the pcode files as other threads suggest but that doesn’t solve the problem for pcode files referencing functions from other pcode files. Any ideas? I have a MATLAB standalone app compiled from many different source code files. Some of the dependencies for this app are sensitive IP so I identified all required files using requiredFilesAndProducts and I obfuscated those sensitive dependencies (since source code is to be delivered as part of this project). Some of those dependencies use functions from other dependencies so I recursively called requiredFilesAndProducts to get a complete list of all required files. From that list, I then ran pcode against the sensitive IP and gathered all the pcode files into one location.
When I compile the standalone executable, I add the path to the pcode folder addpath(genpath(‘C:pathtopcodefolder’)) as well as the safe to distribute MATLAB source code files and compile compiler.build.standaloneApplication(‘MATLAB_SOURCE_CODE_FILE_Y.m’).
When I run the standalone app, some of the functions from the pcode will yield Undefined function ‘Some_Function’ for input arguments of type ‘char’. Error in PCODE_FILE_X Error in MATLAB_SOURCE_CODE_FILE_Y (line 85) despite the fact that Some_Function has a corresponding pcode file in the pcode folder.
I tried listing at the bottom of the main function for the standalone app all the pcode files as other threads suggest but that doesn’t solve the problem for pcode files referencing functions from other pcode files. Any ideas? matlab compiler, pcode MATLAB Answers — New Questions
Why am I receiving this error?
% Input data
EL = 38.60e9; % Longitudinal modulus (Pa)
ET = 8.27e9; % Transverse modulus (Pa)
GLT = 4.14e9; % Shear modulus (Pa)
nuLT = 0.26; % Poisson’s ratio
thickness = 0.002; % Thickness of each layer (m)
layer_angles = [45, -45, -45, 45]; % Fiber orientations of each layer (degrees)
mid_plane_strains = [0.05, 0.00, 0.00]; % Mid-plane strains (epsilon_x, epsilon_y, gamma_xy)
curvatures = [0.05, 0.020, 0.0250; 0, 0.010, 0.0125]; % Curvatures (kappa_x, kappa_y, kappa_xy)
% Number of layers
num_layers = length(layer_angles);
% Initialize arrays to store stresses
sigma_x_top = zeros(num_layers, 1);
sigma_y_top = zeros(num_layers, 1);
tau_xy_top = zeros(num_layers, 1);
sigma_x_bottom = zeros(num_layers, 1);
sigma_y_bottom = zeros(num_layers, 1);
tau_xy_bottom = zeros(num_layers, 1);
% Compute stresses for each layer
for i = 1:num_layers
theta = deg2rad(layer_angles(i));
% Transformation matrix
T = [cos(theta)^2, sin(theta)^2, 2*sin(theta)*cos(theta);
sin(theta)^2, cos(theta)^2, -2*sin(theta)*cos(theta);
-sin(theta)*cos(theta), sin(theta)*cos(theta), cos(theta)^2-sin(theta)^2];
% Reduced stiffness matrix
Q11 = EL / (1 – nuLT^2);
Q12 = nuLT * EL / (1 – nuLT^2);
Q22 = ET / (1 – nuLT^2);
Q66 = GLT;
Q = [Q11, Q12, 0;
Q12, Q22, 0;
0, 0, Q66];
% Transform stiffness matrix to layer coordinates
Q_bar = (T) / Q * T’;
% Strain matrix
strain = [mid_plane_strains(1); mid_plane_strains(2); mid_plane_strains(3)];
curvature = [curvatures(1, i); curvatures(2, i); 0]; % Assume no curvature in z direction
% Stress resultants
stress_resultants = Q_bar * strain + curvature;
% Stresses at top and bottom of the layer
sigma_x_top(i) = stress_resultants(1) + mid_plane_strains(1) * thickness / 2;
sigma_y_top(i) = stress_resultants(2) + mid_plane_strains(2) * thickness / 2;
tau_xy_top(i) = stress_resultants(3);
sigma_x_bottom(i) = stress_resultants(1) – mid_plane_strains(1) * thickness / 2;
sigma_y_bottom(i) = stress_resultants(2) – mid_plane_strains(2) * thickness / 2;
tau_xy_bottom(i) = stress_resultants(3);
end
% Display results
fprintf(‘LayertSigma_x_top (Pa)tSigma_y_top (Pa)tTau_xy_top (Pa)tSigma_x_bottom (Pa)tSigma_y_bottom (Pa)tTau_xy_bottom (Pa)n’);
for i = 1:num_layers
fprintf(‘%dt%.2ft%.2ft%.2ft%.2ft%.2ft%.2fn’, i, sigma_x_top(i), sigma_y_top(i), tau_xy_top(i), sigma_x_bottom(i), sigma_y_bottom(i), tau_xy_bottom(i));
end
% Plot stress variation through thickness
layer_depths = linspace(-thickness/2, thickness/2, num_layers);
figure;
hold on;
plot(sigma_x_top, layer_depths, ‘r’, ‘LineWidth’, 1.5);
plot(sigma_y_top, layer_depths, ‘g’, ‘LineWidth’, 1.5);
plot(tau_xy_top, layer_depths, ‘b’, ‘LineWidth’, 1.5);
plot(sigma_x_bottom, layer_depths, ‘r–‘, ‘LineWidth’, 1.5);
plot(sigma_y_bottom, layer_depths, ‘g–‘, ‘LineWidth’, 1.5);
plot(tau_xy_bottom, layer_depths, ‘b–‘, ‘LineWidth’, 1.5);
title(‘Stress Variation Through Laminate Thickness’);
xlabel(‘Stress (Pa)’);
ylabel(‘Depth (m)’);
legend(‘sigma_x’, ‘sigma_y’, ‘tau_{xy}’, ‘Location’, ‘best’);
grid on;
hold off;
ERROR:
Index in position 2 exceeds array bounds. Index must not exceed 3.
Error in Project_1_new (line 45)
curvature = [curvatures(1, i); curvatures(2, i); 0]; % Assume no curvature in z direction% Input data
EL = 38.60e9; % Longitudinal modulus (Pa)
ET = 8.27e9; % Transverse modulus (Pa)
GLT = 4.14e9; % Shear modulus (Pa)
nuLT = 0.26; % Poisson’s ratio
thickness = 0.002; % Thickness of each layer (m)
layer_angles = [45, -45, -45, 45]; % Fiber orientations of each layer (degrees)
mid_plane_strains = [0.05, 0.00, 0.00]; % Mid-plane strains (epsilon_x, epsilon_y, gamma_xy)
curvatures = [0.05, 0.020, 0.0250; 0, 0.010, 0.0125]; % Curvatures (kappa_x, kappa_y, kappa_xy)
% Number of layers
num_layers = length(layer_angles);
% Initialize arrays to store stresses
sigma_x_top = zeros(num_layers, 1);
sigma_y_top = zeros(num_layers, 1);
tau_xy_top = zeros(num_layers, 1);
sigma_x_bottom = zeros(num_layers, 1);
sigma_y_bottom = zeros(num_layers, 1);
tau_xy_bottom = zeros(num_layers, 1);
% Compute stresses for each layer
for i = 1:num_layers
theta = deg2rad(layer_angles(i));
% Transformation matrix
T = [cos(theta)^2, sin(theta)^2, 2*sin(theta)*cos(theta);
sin(theta)^2, cos(theta)^2, -2*sin(theta)*cos(theta);
-sin(theta)*cos(theta), sin(theta)*cos(theta), cos(theta)^2-sin(theta)^2];
% Reduced stiffness matrix
Q11 = EL / (1 – nuLT^2);
Q12 = nuLT * EL / (1 – nuLT^2);
Q22 = ET / (1 – nuLT^2);
Q66 = GLT;
Q = [Q11, Q12, 0;
Q12, Q22, 0;
0, 0, Q66];
% Transform stiffness matrix to layer coordinates
Q_bar = (T) / Q * T’;
% Strain matrix
strain = [mid_plane_strains(1); mid_plane_strains(2); mid_plane_strains(3)];
curvature = [curvatures(1, i); curvatures(2, i); 0]; % Assume no curvature in z direction
% Stress resultants
stress_resultants = Q_bar * strain + curvature;
% Stresses at top and bottom of the layer
sigma_x_top(i) = stress_resultants(1) + mid_plane_strains(1) * thickness / 2;
sigma_y_top(i) = stress_resultants(2) + mid_plane_strains(2) * thickness / 2;
tau_xy_top(i) = stress_resultants(3);
sigma_x_bottom(i) = stress_resultants(1) – mid_plane_strains(1) * thickness / 2;
sigma_y_bottom(i) = stress_resultants(2) – mid_plane_strains(2) * thickness / 2;
tau_xy_bottom(i) = stress_resultants(3);
end
% Display results
fprintf(‘LayertSigma_x_top (Pa)tSigma_y_top (Pa)tTau_xy_top (Pa)tSigma_x_bottom (Pa)tSigma_y_bottom (Pa)tTau_xy_bottom (Pa)n’);
for i = 1:num_layers
fprintf(‘%dt%.2ft%.2ft%.2ft%.2ft%.2ft%.2fn’, i, sigma_x_top(i), sigma_y_top(i), tau_xy_top(i), sigma_x_bottom(i), sigma_y_bottom(i), tau_xy_bottom(i));
end
% Plot stress variation through thickness
layer_depths = linspace(-thickness/2, thickness/2, num_layers);
figure;
hold on;
plot(sigma_x_top, layer_depths, ‘r’, ‘LineWidth’, 1.5);
plot(sigma_y_top, layer_depths, ‘g’, ‘LineWidth’, 1.5);
plot(tau_xy_top, layer_depths, ‘b’, ‘LineWidth’, 1.5);
plot(sigma_x_bottom, layer_depths, ‘r–‘, ‘LineWidth’, 1.5);
plot(sigma_y_bottom, layer_depths, ‘g–‘, ‘LineWidth’, 1.5);
plot(tau_xy_bottom, layer_depths, ‘b–‘, ‘LineWidth’, 1.5);
title(‘Stress Variation Through Laminate Thickness’);
xlabel(‘Stress (Pa)’);
ylabel(‘Depth (m)’);
legend(‘sigma_x’, ‘sigma_y’, ‘tau_{xy}’, ‘Location’, ‘best’);
grid on;
hold off;
ERROR:
Index in position 2 exceeds array bounds. Index must not exceed 3.
Error in Project_1_new (line 45)
curvature = [curvatures(1, i); curvatures(2, i); 0]; % Assume no curvature in z direction % Input data
EL = 38.60e9; % Longitudinal modulus (Pa)
ET = 8.27e9; % Transverse modulus (Pa)
GLT = 4.14e9; % Shear modulus (Pa)
nuLT = 0.26; % Poisson’s ratio
thickness = 0.002; % Thickness of each layer (m)
layer_angles = [45, -45, -45, 45]; % Fiber orientations of each layer (degrees)
mid_plane_strains = [0.05, 0.00, 0.00]; % Mid-plane strains (epsilon_x, epsilon_y, gamma_xy)
curvatures = [0.05, 0.020, 0.0250; 0, 0.010, 0.0125]; % Curvatures (kappa_x, kappa_y, kappa_xy)
% Number of layers
num_layers = length(layer_angles);
% Initialize arrays to store stresses
sigma_x_top = zeros(num_layers, 1);
sigma_y_top = zeros(num_layers, 1);
tau_xy_top = zeros(num_layers, 1);
sigma_x_bottom = zeros(num_layers, 1);
sigma_y_bottom = zeros(num_layers, 1);
tau_xy_bottom = zeros(num_layers, 1);
% Compute stresses for each layer
for i = 1:num_layers
theta = deg2rad(layer_angles(i));
% Transformation matrix
T = [cos(theta)^2, sin(theta)^2, 2*sin(theta)*cos(theta);
sin(theta)^2, cos(theta)^2, -2*sin(theta)*cos(theta);
-sin(theta)*cos(theta), sin(theta)*cos(theta), cos(theta)^2-sin(theta)^2];
% Reduced stiffness matrix
Q11 = EL / (1 – nuLT^2);
Q12 = nuLT * EL / (1 – nuLT^2);
Q22 = ET / (1 – nuLT^2);
Q66 = GLT;
Q = [Q11, Q12, 0;
Q12, Q22, 0;
0, 0, Q66];
% Transform stiffness matrix to layer coordinates
Q_bar = (T) / Q * T’;
% Strain matrix
strain = [mid_plane_strains(1); mid_plane_strains(2); mid_plane_strains(3)];
curvature = [curvatures(1, i); curvatures(2, i); 0]; % Assume no curvature in z direction
% Stress resultants
stress_resultants = Q_bar * strain + curvature;
% Stresses at top and bottom of the layer
sigma_x_top(i) = stress_resultants(1) + mid_plane_strains(1) * thickness / 2;
sigma_y_top(i) = stress_resultants(2) + mid_plane_strains(2) * thickness / 2;
tau_xy_top(i) = stress_resultants(3);
sigma_x_bottom(i) = stress_resultants(1) – mid_plane_strains(1) * thickness / 2;
sigma_y_bottom(i) = stress_resultants(2) – mid_plane_strains(2) * thickness / 2;
tau_xy_bottom(i) = stress_resultants(3);
end
% Display results
fprintf(‘LayertSigma_x_top (Pa)tSigma_y_top (Pa)tTau_xy_top (Pa)tSigma_x_bottom (Pa)tSigma_y_bottom (Pa)tTau_xy_bottom (Pa)n’);
for i = 1:num_layers
fprintf(‘%dt%.2ft%.2ft%.2ft%.2ft%.2ft%.2fn’, i, sigma_x_top(i), sigma_y_top(i), tau_xy_top(i), sigma_x_bottom(i), sigma_y_bottom(i), tau_xy_bottom(i));
end
% Plot stress variation through thickness
layer_depths = linspace(-thickness/2, thickness/2, num_layers);
figure;
hold on;
plot(sigma_x_top, layer_depths, ‘r’, ‘LineWidth’, 1.5);
plot(sigma_y_top, layer_depths, ‘g’, ‘LineWidth’, 1.5);
plot(tau_xy_top, layer_depths, ‘b’, ‘LineWidth’, 1.5);
plot(sigma_x_bottom, layer_depths, ‘r–‘, ‘LineWidth’, 1.5);
plot(sigma_y_bottom, layer_depths, ‘g–‘, ‘LineWidth’, 1.5);
plot(tau_xy_bottom, layer_depths, ‘b–‘, ‘LineWidth’, 1.5);
title(‘Stress Variation Through Laminate Thickness’);
xlabel(‘Stress (Pa)’);
ylabel(‘Depth (m)’);
legend(‘sigma_x’, ‘sigma_y’, ‘tau_{xy}’, ‘Location’, ‘best’);
grid on;
hold off;
ERROR:
Index in position 2 exceeds array bounds. Index must not exceed 3.
Error in Project_1_new (line 45)
curvature = [curvatures(1, i); curvatures(2, i); 0]; % Assume no curvature in z direction error, array bounds MATLAB Answers — New Questions
how to use sprintf to an array ?
Hi guys, im trying to make some text using sprintf, here i give example below:
Basically I want all datas from variable ID,X,Z in cell array comes out one bye one to the txtline(ij). Is it possible?
Here i give the code :
clear;
clc;
H = 5;
L = 15;
Ns = 2;
Nb = 1;
PortalHeight = H;
Bayspan = L;
NumberStory = Ns;
NumberBay = Nb;
% Variable1
h = [0.8,1.00,1.20,1.40,1.6,1.80];
% Variable2
Lss = [2.00,2.40,2.80,3.20,3.60,4.00];
% Variable3
Nss = [2,3,4];
% Definition
Var1HeightofTrussBeam = h;
Var2LengthSpecialSegment = Lss;
Var3NumberSpecialSegment = Nss;
% % Xbase = zeros(1,length(Totalvariant));
% % Zbase = zeros(1,length(Totalvariant));
% % Xcol = zeros(1,length(Totalvariant));
% % Zcol = zeros(1,length(Totalvariant));
% % Xos = zeros(1,length(Totalvariant));
% % Zos = zeros(1,length(Totalvariant));
% % Xss = zeros(1,length(Totalvariant));
% % Zss = zeros(1,length(Totalvariant));
% % X = zeros(1,length(Totalvariant));
% % Z = zeros(1,length(Totalvariant));
% % jointbase = zeros(1,length(Totalvariant));
% % jointcolumn = zeros(1,length(Totalvariant));
% % jointordinarysegment = zeros(1,length(Totalvariant));
% % jointtopordinarysegment = zeros(1,length(Totalvariant));
% % jointbottomordinarysegment = zeros(1,length(Totalvariant));
% % jointspecialsegment = zeros(1,length(Totalvariant));
% % jointtopspecialsegment = zeros(1,length(Totalvariant));
% % jointbottomspecialsegment = zeros(1,length(Totalvariant));
ijk = 0;
for i = 1:numel(h)
for j = 1:numel(Lss)
for k = 1:numel(Nss)
ijk = ijk+1;
Variantmodel{ijk,:} = table(ijk,h(i),Lss(j),Nss(k),’VariableNames’,{‘VariantID’,’Height’,’Length’,’Number’});
%% Base(base)
Xbase{ijk,:} = L*(0:NumberBay);
Zbase{ijk,:} = repelem(0,1,length(Xbase{ijk,:}));
%% Column(col)
Xcolumn = L*(0:NumberBay);
Zcolumn = repelem(H*(1:NumberStory),1,length(Xcolumn));
Xbotbeam = L*(0:NumberBay);
Zbotbeam = repelem((H*(1:NumberStory)-h(i)),1,length(Xbotbeam));
% replicate [X] to be the same size as [Z] for plotting:
Xcol{ijk,:} = repmat([Xcolumn,Xbotbeam],1,NumberStory);
Zcol{ijk,:} = [Zcolumn,Zbotbeam];
%% Ordinary Segment
% calculate span length of ordinary segment
Los = (L-Lss(j))/2;
Nos = Los/h(i);
Nos = round(Nos);
los = Los/Nos;
totalspan{ijk,:} = los*Nos*2+Lss(j);
if totalspan{ijk,:} == 15.000
checkspan{ijk,:} = "correct span";
else
checkspan{ijk,:} = "span must be 15m";
end
% top and bottom joint of ordinary segment(os)
XTopOrdinarySegment = reshape([los*(1:Nos),(L/2+Lss(j)/2)+los*(0:Nos-1)].’+L*(0:(NumberBay-1)),1,[]);
XBottomOrdinarySegment = XTopOrdinarySegment;
ZTopOrdinarySegment = repelem(H*(1:NumberStory),1,2*Nos*NumberBay);
ZBottomOrdinarySegment = repelem(H*(1:NumberStory)-h(i),1,2*Nos*NumberBay);
% replicate [X] to be the same size as [Z] for plotting:
Xos{ijk,:} = repmat([XTopOrdinarySegment,XBottomOrdinarySegment],1,NumberStory);
Zos{ijk,:} = [ZTopOrdinarySegment,ZBottomOrdinarySegment];
%% Special Segment
% calculate span length of special segment
lss = Lss(j)/Nss(k);
% top and bottom joint of special segment(ss)
XTopSpecialSegment = reshape((lss*(0:Nss(k))+L/2-Lss(j)/2).’+L*(0:(NumberBay-1)),1,[]);
XBottomSpecialSegment = XTopSpecialSegment;
ZTopSpecialSegment = repelem(H*(1:NumberStory),1,length(XTopSpecialSegment));
ZBottomSpecialSegment = repelem(H*(1:NumberStory)-h(i),1,length(XBottomSpecialSegment));
% replicate [X] to be the same size as [Z] for plotting:
Xss{ijk,:} = repmat([XTopSpecialSegment,XBottomSpecialSegment],1,NumberStory);
Zss{ijk,:} = [ZTopSpecialSegment,ZBottomSpecialSegment];
%% Plot Joint
X{ijk,:} = [Xbase{ijk,:},Xcol{ijk,:},Xos{ijk,:},Xss{ijk,:}];
Z{ijk,:} = [Zbase{ijk,:},Zcol{ijk,:},Zos{ijk,:},Zss{ijk,:}];
scatter(X{ijk,:},Z{ijk,:},’filled’),grid on
%check angle
tangent = (Lss(j)/Nss(k))/h(i);
anglespecialsegment(ijk) = atand(tangent);
%% Name Joint
jointbase{ijk} = table((1:numel(Xbase{ijk,:}))’,Xbase{ijk,:}’,Zbase{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointcolumn{ijk} = table((max(jointbase{ijk}.ID)+1:numel(Xcol{ijk,:})+max(jointbase{ijk}.ID))’,Xcol{ijk,:}’,Zcol{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointordinarysegment{ijk} = table((max(jointcolumn{ijk}.ID)+1:numel(Xos{ijk,:})+max(jointcolumn{ijk}.ID))’,Xos{ijk,:}’,Zos{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointtopordinarysegment{ijk} = jointordinarysegment{ijk}(ismember(jointordinarysegment{ijk}.Z,Zcolumn),:);
jointbottomordinarysegment{ijk} = jointordinarysegment{ijk}(ismember(jointordinarysegment{ijk}.Z,Zbotbeam),:);
jointspecialsegment{ijk} = table((max(jointbottomordinarysegment{ijk}.ID)+1:numel(Xss{ijk,:})+max(jointbottomordinarysegment{ijk}.ID))’,Xss{ijk,:}’,Zss{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointtopspecialsegment{ijk} = jointspecialsegment{ijk}(ismember(jointspecialsegment{ijk}.Z,Zcolumn),:);
jointbottomspecialsegment{ijk} = jointspecialsegment{ijk}(ismember(jointspecialsegment{ijk}.Z,Zbotbeam),:);
end
end
end
%% Verify Variants Which Passed the Angle Requirement
tablecheck = table((1:numel(anglespecialsegment))’,totalspan,anglespecialsegment’,’VariableNames’,{‘VariantID’,’Total Span’,’Angle’});
VariantIDPassed = tablecheck.VariantID(tablecheck.Angle>=30 & tablecheck.Angle<=60);
jointbase = table((1:numel(jointbase))’,jointbase’,’VariableNames’,{‘VariantID’,’Joint Base’});
jointbase = jointbase(ismember(jointbase.VariantID,VariantIDPassed),:);
jointcolumn = table((1:numel(jointcolumn))’,jointcolumn’,’VariableNames’,{‘VariantID’,’Joint Column’});
jointcolumn = jointcolumn(ismember(jointcolumn.VariantID,VariantIDPassed),:);
jointtopordinarysegment = table((1:numel(jointtopordinarysegment))’,jointtopordinarysegment’,’VariableNames’,{‘VariantID’,’Joint Top Ordinary Segment’});
jointtopordinarysegment = jointtopordinarysegment(ismember(jointtopordinarysegment.VariantID,VariantIDPassed),:);
jointbottomordinarysegment = table((1:numel(jointbottomordinarysegment))’,jointbottomordinarysegment’,’VariableNames’,{‘VariantID’,’Joint Bottom Ordinary Segment’});
jointbottomordinarysegment = jointbottomordinarysegment(ismember(jointbottomordinarysegment.VariantID,VariantIDPassed),:);
jointtopspecialsegment = table((1:numel(jointtopspecialsegment))’,jointtopspecialsegment’,’VariableNames’,{‘VariantID’,’Joint Top Special Segment’});
jointtopspecialsegment = jointtopspecialsegment(ismember(jointtopspecialsegment.VariantID,VariantIDPassed),:);
jointbottomspecialsegment = table((1:numel(jointbottomspecialsegment))’,jointbottomspecialsegment’,’VariableNames’,{‘VariantID’,’Joint Bottom Special Segment’});
jointbottomspecialsegment = jointbottomspecialsegment(ismember(jointbottomspecialsegment.VariantID,VariantIDPassed),:);
%% Print data in cell array one-by-one
ij = 0
for i = 1:height(jointbottomspecialsegment)
BottomSS = jointbottomspecialsegment.("Joint Bottom Special Segment")(i)
for j = 1:height(BottomSS{1,1})
ij = ij+1
Joint = BottomSS{1,1}.ID(j)
X = BottomSS{1,1}.X(j)
Z =BottomSS{1,1}.Z(j)
txtline(ij) = sprintf(‘ Joint=%d CoordSys=GLOBAL CoordType=Cartesian XorR=%d Y=0 Z=%d SpecialJt=No GlobalX=%d GlobalY=0 GlobalZ=%d’);
end
endHi guys, im trying to make some text using sprintf, here i give example below:
Basically I want all datas from variable ID,X,Z in cell array comes out one bye one to the txtline(ij). Is it possible?
Here i give the code :
clear;
clc;
H = 5;
L = 15;
Ns = 2;
Nb = 1;
PortalHeight = H;
Bayspan = L;
NumberStory = Ns;
NumberBay = Nb;
% Variable1
h = [0.8,1.00,1.20,1.40,1.6,1.80];
% Variable2
Lss = [2.00,2.40,2.80,3.20,3.60,4.00];
% Variable3
Nss = [2,3,4];
% Definition
Var1HeightofTrussBeam = h;
Var2LengthSpecialSegment = Lss;
Var3NumberSpecialSegment = Nss;
% % Xbase = zeros(1,length(Totalvariant));
% % Zbase = zeros(1,length(Totalvariant));
% % Xcol = zeros(1,length(Totalvariant));
% % Zcol = zeros(1,length(Totalvariant));
% % Xos = zeros(1,length(Totalvariant));
% % Zos = zeros(1,length(Totalvariant));
% % Xss = zeros(1,length(Totalvariant));
% % Zss = zeros(1,length(Totalvariant));
% % X = zeros(1,length(Totalvariant));
% % Z = zeros(1,length(Totalvariant));
% % jointbase = zeros(1,length(Totalvariant));
% % jointcolumn = zeros(1,length(Totalvariant));
% % jointordinarysegment = zeros(1,length(Totalvariant));
% % jointtopordinarysegment = zeros(1,length(Totalvariant));
% % jointbottomordinarysegment = zeros(1,length(Totalvariant));
% % jointspecialsegment = zeros(1,length(Totalvariant));
% % jointtopspecialsegment = zeros(1,length(Totalvariant));
% % jointbottomspecialsegment = zeros(1,length(Totalvariant));
ijk = 0;
for i = 1:numel(h)
for j = 1:numel(Lss)
for k = 1:numel(Nss)
ijk = ijk+1;
Variantmodel{ijk,:} = table(ijk,h(i),Lss(j),Nss(k),’VariableNames’,{‘VariantID’,’Height’,’Length’,’Number’});
%% Base(base)
Xbase{ijk,:} = L*(0:NumberBay);
Zbase{ijk,:} = repelem(0,1,length(Xbase{ijk,:}));
%% Column(col)
Xcolumn = L*(0:NumberBay);
Zcolumn = repelem(H*(1:NumberStory),1,length(Xcolumn));
Xbotbeam = L*(0:NumberBay);
Zbotbeam = repelem((H*(1:NumberStory)-h(i)),1,length(Xbotbeam));
% replicate [X] to be the same size as [Z] for plotting:
Xcol{ijk,:} = repmat([Xcolumn,Xbotbeam],1,NumberStory);
Zcol{ijk,:} = [Zcolumn,Zbotbeam];
%% Ordinary Segment
% calculate span length of ordinary segment
Los = (L-Lss(j))/2;
Nos = Los/h(i);
Nos = round(Nos);
los = Los/Nos;
totalspan{ijk,:} = los*Nos*2+Lss(j);
if totalspan{ijk,:} == 15.000
checkspan{ijk,:} = "correct span";
else
checkspan{ijk,:} = "span must be 15m";
end
% top and bottom joint of ordinary segment(os)
XTopOrdinarySegment = reshape([los*(1:Nos),(L/2+Lss(j)/2)+los*(0:Nos-1)].’+L*(0:(NumberBay-1)),1,[]);
XBottomOrdinarySegment = XTopOrdinarySegment;
ZTopOrdinarySegment = repelem(H*(1:NumberStory),1,2*Nos*NumberBay);
ZBottomOrdinarySegment = repelem(H*(1:NumberStory)-h(i),1,2*Nos*NumberBay);
% replicate [X] to be the same size as [Z] for plotting:
Xos{ijk,:} = repmat([XTopOrdinarySegment,XBottomOrdinarySegment],1,NumberStory);
Zos{ijk,:} = [ZTopOrdinarySegment,ZBottomOrdinarySegment];
%% Special Segment
% calculate span length of special segment
lss = Lss(j)/Nss(k);
% top and bottom joint of special segment(ss)
XTopSpecialSegment = reshape((lss*(0:Nss(k))+L/2-Lss(j)/2).’+L*(0:(NumberBay-1)),1,[]);
XBottomSpecialSegment = XTopSpecialSegment;
ZTopSpecialSegment = repelem(H*(1:NumberStory),1,length(XTopSpecialSegment));
ZBottomSpecialSegment = repelem(H*(1:NumberStory)-h(i),1,length(XBottomSpecialSegment));
% replicate [X] to be the same size as [Z] for plotting:
Xss{ijk,:} = repmat([XTopSpecialSegment,XBottomSpecialSegment],1,NumberStory);
Zss{ijk,:} = [ZTopSpecialSegment,ZBottomSpecialSegment];
%% Plot Joint
X{ijk,:} = [Xbase{ijk,:},Xcol{ijk,:},Xos{ijk,:},Xss{ijk,:}];
Z{ijk,:} = [Zbase{ijk,:},Zcol{ijk,:},Zos{ijk,:},Zss{ijk,:}];
scatter(X{ijk,:},Z{ijk,:},’filled’),grid on
%check angle
tangent = (Lss(j)/Nss(k))/h(i);
anglespecialsegment(ijk) = atand(tangent);
%% Name Joint
jointbase{ijk} = table((1:numel(Xbase{ijk,:}))’,Xbase{ijk,:}’,Zbase{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointcolumn{ijk} = table((max(jointbase{ijk}.ID)+1:numel(Xcol{ijk,:})+max(jointbase{ijk}.ID))’,Xcol{ijk,:}’,Zcol{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointordinarysegment{ijk} = table((max(jointcolumn{ijk}.ID)+1:numel(Xos{ijk,:})+max(jointcolumn{ijk}.ID))’,Xos{ijk,:}’,Zos{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointtopordinarysegment{ijk} = jointordinarysegment{ijk}(ismember(jointordinarysegment{ijk}.Z,Zcolumn),:);
jointbottomordinarysegment{ijk} = jointordinarysegment{ijk}(ismember(jointordinarysegment{ijk}.Z,Zbotbeam),:);
jointspecialsegment{ijk} = table((max(jointbottomordinarysegment{ijk}.ID)+1:numel(Xss{ijk,:})+max(jointbottomordinarysegment{ijk}.ID))’,Xss{ijk,:}’,Zss{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointtopspecialsegment{ijk} = jointspecialsegment{ijk}(ismember(jointspecialsegment{ijk}.Z,Zcolumn),:);
jointbottomspecialsegment{ijk} = jointspecialsegment{ijk}(ismember(jointspecialsegment{ijk}.Z,Zbotbeam),:);
end
end
end
%% Verify Variants Which Passed the Angle Requirement
tablecheck = table((1:numel(anglespecialsegment))’,totalspan,anglespecialsegment’,’VariableNames’,{‘VariantID’,’Total Span’,’Angle’});
VariantIDPassed = tablecheck.VariantID(tablecheck.Angle>=30 & tablecheck.Angle<=60);
jointbase = table((1:numel(jointbase))’,jointbase’,’VariableNames’,{‘VariantID’,’Joint Base’});
jointbase = jointbase(ismember(jointbase.VariantID,VariantIDPassed),:);
jointcolumn = table((1:numel(jointcolumn))’,jointcolumn’,’VariableNames’,{‘VariantID’,’Joint Column’});
jointcolumn = jointcolumn(ismember(jointcolumn.VariantID,VariantIDPassed),:);
jointtopordinarysegment = table((1:numel(jointtopordinarysegment))’,jointtopordinarysegment’,’VariableNames’,{‘VariantID’,’Joint Top Ordinary Segment’});
jointtopordinarysegment = jointtopordinarysegment(ismember(jointtopordinarysegment.VariantID,VariantIDPassed),:);
jointbottomordinarysegment = table((1:numel(jointbottomordinarysegment))’,jointbottomordinarysegment’,’VariableNames’,{‘VariantID’,’Joint Bottom Ordinary Segment’});
jointbottomordinarysegment = jointbottomordinarysegment(ismember(jointbottomordinarysegment.VariantID,VariantIDPassed),:);
jointtopspecialsegment = table((1:numel(jointtopspecialsegment))’,jointtopspecialsegment’,’VariableNames’,{‘VariantID’,’Joint Top Special Segment’});
jointtopspecialsegment = jointtopspecialsegment(ismember(jointtopspecialsegment.VariantID,VariantIDPassed),:);
jointbottomspecialsegment = table((1:numel(jointbottomspecialsegment))’,jointbottomspecialsegment’,’VariableNames’,{‘VariantID’,’Joint Bottom Special Segment’});
jointbottomspecialsegment = jointbottomspecialsegment(ismember(jointbottomspecialsegment.VariantID,VariantIDPassed),:);
%% Print data in cell array one-by-one
ij = 0
for i = 1:height(jointbottomspecialsegment)
BottomSS = jointbottomspecialsegment.("Joint Bottom Special Segment")(i)
for j = 1:height(BottomSS{1,1})
ij = ij+1
Joint = BottomSS{1,1}.ID(j)
X = BottomSS{1,1}.X(j)
Z =BottomSS{1,1}.Z(j)
txtline(ij) = sprintf(‘ Joint=%d CoordSys=GLOBAL CoordType=Cartesian XorR=%d Y=0 Z=%d SpecialJt=No GlobalX=%d GlobalY=0 GlobalZ=%d’);
end
end Hi guys, im trying to make some text using sprintf, here i give example below:
Basically I want all datas from variable ID,X,Z in cell array comes out one bye one to the txtline(ij). Is it possible?
Here i give the code :
clear;
clc;
H = 5;
L = 15;
Ns = 2;
Nb = 1;
PortalHeight = H;
Bayspan = L;
NumberStory = Ns;
NumberBay = Nb;
% Variable1
h = [0.8,1.00,1.20,1.40,1.6,1.80];
% Variable2
Lss = [2.00,2.40,2.80,3.20,3.60,4.00];
% Variable3
Nss = [2,3,4];
% Definition
Var1HeightofTrussBeam = h;
Var2LengthSpecialSegment = Lss;
Var3NumberSpecialSegment = Nss;
% % Xbase = zeros(1,length(Totalvariant));
% % Zbase = zeros(1,length(Totalvariant));
% % Xcol = zeros(1,length(Totalvariant));
% % Zcol = zeros(1,length(Totalvariant));
% % Xos = zeros(1,length(Totalvariant));
% % Zos = zeros(1,length(Totalvariant));
% % Xss = zeros(1,length(Totalvariant));
% % Zss = zeros(1,length(Totalvariant));
% % X = zeros(1,length(Totalvariant));
% % Z = zeros(1,length(Totalvariant));
% % jointbase = zeros(1,length(Totalvariant));
% % jointcolumn = zeros(1,length(Totalvariant));
% % jointordinarysegment = zeros(1,length(Totalvariant));
% % jointtopordinarysegment = zeros(1,length(Totalvariant));
% % jointbottomordinarysegment = zeros(1,length(Totalvariant));
% % jointspecialsegment = zeros(1,length(Totalvariant));
% % jointtopspecialsegment = zeros(1,length(Totalvariant));
% % jointbottomspecialsegment = zeros(1,length(Totalvariant));
ijk = 0;
for i = 1:numel(h)
for j = 1:numel(Lss)
for k = 1:numel(Nss)
ijk = ijk+1;
Variantmodel{ijk,:} = table(ijk,h(i),Lss(j),Nss(k),’VariableNames’,{‘VariantID’,’Height’,’Length’,’Number’});
%% Base(base)
Xbase{ijk,:} = L*(0:NumberBay);
Zbase{ijk,:} = repelem(0,1,length(Xbase{ijk,:}));
%% Column(col)
Xcolumn = L*(0:NumberBay);
Zcolumn = repelem(H*(1:NumberStory),1,length(Xcolumn));
Xbotbeam = L*(0:NumberBay);
Zbotbeam = repelem((H*(1:NumberStory)-h(i)),1,length(Xbotbeam));
% replicate [X] to be the same size as [Z] for plotting:
Xcol{ijk,:} = repmat([Xcolumn,Xbotbeam],1,NumberStory);
Zcol{ijk,:} = [Zcolumn,Zbotbeam];
%% Ordinary Segment
% calculate span length of ordinary segment
Los = (L-Lss(j))/2;
Nos = Los/h(i);
Nos = round(Nos);
los = Los/Nos;
totalspan{ijk,:} = los*Nos*2+Lss(j);
if totalspan{ijk,:} == 15.000
checkspan{ijk,:} = "correct span";
else
checkspan{ijk,:} = "span must be 15m";
end
% top and bottom joint of ordinary segment(os)
XTopOrdinarySegment = reshape([los*(1:Nos),(L/2+Lss(j)/2)+los*(0:Nos-1)].’+L*(0:(NumberBay-1)),1,[]);
XBottomOrdinarySegment = XTopOrdinarySegment;
ZTopOrdinarySegment = repelem(H*(1:NumberStory),1,2*Nos*NumberBay);
ZBottomOrdinarySegment = repelem(H*(1:NumberStory)-h(i),1,2*Nos*NumberBay);
% replicate [X] to be the same size as [Z] for plotting:
Xos{ijk,:} = repmat([XTopOrdinarySegment,XBottomOrdinarySegment],1,NumberStory);
Zos{ijk,:} = [ZTopOrdinarySegment,ZBottomOrdinarySegment];
%% Special Segment
% calculate span length of special segment
lss = Lss(j)/Nss(k);
% top and bottom joint of special segment(ss)
XTopSpecialSegment = reshape((lss*(0:Nss(k))+L/2-Lss(j)/2).’+L*(0:(NumberBay-1)),1,[]);
XBottomSpecialSegment = XTopSpecialSegment;
ZTopSpecialSegment = repelem(H*(1:NumberStory),1,length(XTopSpecialSegment));
ZBottomSpecialSegment = repelem(H*(1:NumberStory)-h(i),1,length(XBottomSpecialSegment));
% replicate [X] to be the same size as [Z] for plotting:
Xss{ijk,:} = repmat([XTopSpecialSegment,XBottomSpecialSegment],1,NumberStory);
Zss{ijk,:} = [ZTopSpecialSegment,ZBottomSpecialSegment];
%% Plot Joint
X{ijk,:} = [Xbase{ijk,:},Xcol{ijk,:},Xos{ijk,:},Xss{ijk,:}];
Z{ijk,:} = [Zbase{ijk,:},Zcol{ijk,:},Zos{ijk,:},Zss{ijk,:}];
scatter(X{ijk,:},Z{ijk,:},’filled’),grid on
%check angle
tangent = (Lss(j)/Nss(k))/h(i);
anglespecialsegment(ijk) = atand(tangent);
%% Name Joint
jointbase{ijk} = table((1:numel(Xbase{ijk,:}))’,Xbase{ijk,:}’,Zbase{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointcolumn{ijk} = table((max(jointbase{ijk}.ID)+1:numel(Xcol{ijk,:})+max(jointbase{ijk}.ID))’,Xcol{ijk,:}’,Zcol{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointordinarysegment{ijk} = table((max(jointcolumn{ijk}.ID)+1:numel(Xos{ijk,:})+max(jointcolumn{ijk}.ID))’,Xos{ijk,:}’,Zos{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointtopordinarysegment{ijk} = jointordinarysegment{ijk}(ismember(jointordinarysegment{ijk}.Z,Zcolumn),:);
jointbottomordinarysegment{ijk} = jointordinarysegment{ijk}(ismember(jointordinarysegment{ijk}.Z,Zbotbeam),:);
jointspecialsegment{ijk} = table((max(jointbottomordinarysegment{ijk}.ID)+1:numel(Xss{ijk,:})+max(jointbottomordinarysegment{ijk}.ID))’,Xss{ijk,:}’,Zss{ijk,:}’,’VariableNames’,{‘ID’,’X’,’Z’});
jointtopspecialsegment{ijk} = jointspecialsegment{ijk}(ismember(jointspecialsegment{ijk}.Z,Zcolumn),:);
jointbottomspecialsegment{ijk} = jointspecialsegment{ijk}(ismember(jointspecialsegment{ijk}.Z,Zbotbeam),:);
end
end
end
%% Verify Variants Which Passed the Angle Requirement
tablecheck = table((1:numel(anglespecialsegment))’,totalspan,anglespecialsegment’,’VariableNames’,{‘VariantID’,’Total Span’,’Angle’});
VariantIDPassed = tablecheck.VariantID(tablecheck.Angle>=30 & tablecheck.Angle<=60);
jointbase = table((1:numel(jointbase))’,jointbase’,’VariableNames’,{‘VariantID’,’Joint Base’});
jointbase = jointbase(ismember(jointbase.VariantID,VariantIDPassed),:);
jointcolumn = table((1:numel(jointcolumn))’,jointcolumn’,’VariableNames’,{‘VariantID’,’Joint Column’});
jointcolumn = jointcolumn(ismember(jointcolumn.VariantID,VariantIDPassed),:);
jointtopordinarysegment = table((1:numel(jointtopordinarysegment))’,jointtopordinarysegment’,’VariableNames’,{‘VariantID’,’Joint Top Ordinary Segment’});
jointtopordinarysegment = jointtopordinarysegment(ismember(jointtopordinarysegment.VariantID,VariantIDPassed),:);
jointbottomordinarysegment = table((1:numel(jointbottomordinarysegment))’,jointbottomordinarysegment’,’VariableNames’,{‘VariantID’,’Joint Bottom Ordinary Segment’});
jointbottomordinarysegment = jointbottomordinarysegment(ismember(jointbottomordinarysegment.VariantID,VariantIDPassed),:);
jointtopspecialsegment = table((1:numel(jointtopspecialsegment))’,jointtopspecialsegment’,’VariableNames’,{‘VariantID’,’Joint Top Special Segment’});
jointtopspecialsegment = jointtopspecialsegment(ismember(jointtopspecialsegment.VariantID,VariantIDPassed),:);
jointbottomspecialsegment = table((1:numel(jointbottomspecialsegment))’,jointbottomspecialsegment’,’VariableNames’,{‘VariantID’,’Joint Bottom Special Segment’});
jointbottomspecialsegment = jointbottomspecialsegment(ismember(jointbottomspecialsegment.VariantID,VariantIDPassed),:);
%% Print data in cell array one-by-one
ij = 0
for i = 1:height(jointbottomspecialsegment)
BottomSS = jointbottomspecialsegment.("Joint Bottom Special Segment")(i)
for j = 1:height(BottomSS{1,1})
ij = ij+1
Joint = BottomSS{1,1}.ID(j)
X = BottomSS{1,1}.X(j)
Z =BottomSS{1,1}.Z(j)
txtline(ij) = sprintf(‘ Joint=%d CoordSys=GLOBAL CoordType=Cartesian XorR=%d Y=0 Z=%d SpecialJt=No GlobalX=%d GlobalY=0 GlobalZ=%d’);
end
end sprintf MATLAB Answers — New Questions