Category: Matlab
Category Archives: Matlab
Can i run the matlab A version simulink file in matlab B version?
clear allclear all clear all matlabb MATLAB Answers — New Questions
Why does the code always return “-ve” values?
When I run the main, it returns me all negative values though I have given only two negative values.
Explanaton: Inside main, I have provided only two negative values in vector u. But when I run it, it gives me either all negative values or three of them as negative values though the magnitudes are nearly the same but the signs are negative. Where does this negative sign come from?
All the three codes are attached. Just run main and see the result in the command window. The values of vector u are returned back in a variable best.When I run the main, it returns me all negative values though I have given only two negative values.
Explanaton: Inside main, I have provided only two negative values in vector u. But when I run it, it gives me either all negative values or three of them as negative values though the magnitudes are nearly the same but the signs are negative. Where does this negative sign come from?
All the three codes are attached. Just run main and see the result in the command window. The values of vector u are returned back in a variable best. When I run the main, it returns me all negative values though I have given only two negative values.
Explanaton: Inside main, I have provided only two negative values in vector u. But when I run it, it gives me either all negative values or three of them as negative values though the magnitudes are nearly the same but the signs are negative. Where does this negative sign come from?
All the three codes are attached. Just run main and see the result in the command window. The values of vector u are returned back in a variable best. all negative values, three of them negative, from where does -ve sign come, how to overcome it MATLAB Answers — New Questions
gradient descent optimization doesnt work in code?
This is the code right now it does the oppisite of a descent optimization. Do you know what is wrong with it?
I tried to minimize the energy of a robot path by changing the waypointtimes, right now it maximizes it for some reason?
clear all
clc
close all
global waypointTimes_start trajTimes;
waypointTimes_start = 1*[0 5 10 15 20];
% The trajectory will be divided into "Number_of_steps" steps:
Number_of_steps =20 ;
% Time is discretized in steps of duration ts:
ts = waypointTimes_start(length(waypointTimes_start))/Number_of_steps;
% Vector of discretized times:
trajTimes = 0:ts:waypointTimes_start(end);
waypointTimes_guess = 1 * [0 5 10 15 20];
% Fix the first and last waypoint times
waypointTimes_guess(1) = 0; % Fix the first waypoint time
waypointTimes_guess(end) = 20; % Fix the last waypoint time
% Set optimization parameters
alfa = 1e-2;
maxIterations = 100;
tolerance = 1e-4;
% Perform gradient descent optimization
waypointTimes = waypointTimes_guess;
for iter = 1:maxIterations
energy(iter)=generateEnergy(waypointTimes);
generateEnergy(waypointTimes)
gradient = computeGradient(waypointTimes);
waypointTimes(2:end-1)=waypointTimes(2:end-1)-alfa*gradient;
number_iterations(iter)=iter;
end
plot(number_iterations,energy,’b -‘);
xlabel(‘iterations’)
ylabel(‘Energy [W]’)
function Energyconsumption = generateEnergy(waypointTimes)
global trajTimes;
robot = loadrobot("kinovaGen3");
robot.Gravity = [0 0 -9.81];
robot.DataFormat = ‘column’;
q_home = [0 15 180 -130 0 55 90]’*pi/180;
eeName = string(robot.BodyNames(length(robot.BodyNames)));
T_home = getTransform(robot, q_home, eeName);
toolPositionHome = T_home(1:3,4);
% Define a Set of Waypoints Based on the Tool Position
waypoints = toolPositionHome + …
[0 0 0 ; -0.1 0.2 0.2 ; -0.2 0 0.1 ; -0.1 -0.2 0.2 ; 0 0 0]’;
orientations = [pi/2 0 pi/2;
(pi/2)+(pi/4) 0 pi/2;
pi/2 0 pi;
(pi/2)-(pi/4) 0 pi/2;
pi/2 0 pi/2]’;
%time from the start to the waypoints
% The trajectory will be divided into "Number_of_steps" steps:
% Time is discretized in steps of duration ts:
% Vector of discretized times:
% Velocities joints at waypoint:
waypointVels= 1*[0 0 0 0 0 0 0;
-1 -1 1 -1 1 0 -1;
-1 1 1 1 1 0 -1;
1 1 -1 -1 1 0 1;
0 0 0 0 0 0 0]’;
% Accelerations at waypoints is computed from velocity. But first we must
% allocate memory for accelerations:
%accelerations joints at waypoints
waypointAccels = 1*[0 0 0 0 0 0 0;
-1 -1 1 -1 1 0 -1;
-1 1 1 1 1 0 -1;
1 1 -1 -1 1 0 1;
0 0 0 0 0 0 0]’ ;
waypointAccelTimes = diff(waypointTimes)/4;
ik = inverseKinematics(‘RigidBodyTree’,robot);
% Weights for pose tolerances, specified as a six-element vector.
% The first three elements of the vector correspond to the weights
% on the error in orientation for the desired pose.
% The last three elements of the vector correspond to the weights on
% the error in the xyz position for the desired pose.
ikWeights = [1 1 1 1 1 1];
% inverseKinematics has several additional options (e.g. max number of
% interations, joint limits, tolerances, etc.)
% The numerical solution starts from an initial guess, taken here as the
% home configuration:
ikInitGuess = q_home’;
% Angles are adapted so to be between -pi e +pi:
ikInitGuess(ikInitGuess > pi) = ikInitGuess(ikInitGuess > pi) – 2*pi;
ikInitGuess(ikInitGuess < -pi) = ikInitGuess(ikInitGuess < -pi) + 2*pi;
% The inverse kinematics problem can be solved with reference to
% positions only, or we can also include the orientation of the EE
% by setting the following Boolean flag to "true":
includeOrientation = false;
numWaypoints = size(waypoints,2); % Number of waypoints
numJoints = numel(robot.homeConfiguration);
% Allocate memory:
jointWaypoints = zeros(numJoints,numWaypoints);
% Waypoints have been defined in Cartesian coordinates. They must be
% converted to the corresponding homogeneous transformation. This is done
% using "trvec2tform".
% Orientations have been described using Euler’s angles (Tait-Bryan,
% extrinsic ZYX). They must be transformed into homogeneous transformation.
% This is done by the command "eul2tform".
%trajectory following loop joint space
for idx = 1:numWaypoints
if includeOrientation
tgtPose = trvec2tform(waypoints(:,idx)’) * eul2tform(orientations(:,idx)’);
else
tgtPose = trvec2tform(waypoints(:,idx)’) * eul2tform([pi/2 0 pi/2]);
end
%IK = inverse kinematics
[config,~] = ik(eeName,tgtPose,ikWeights’,ikInitGuess’);
jointWaypoints(:,idx) = config’;
end
trajType = ‘trap’;
switch trajType
case ‘trap’
[q,qd,qdd] = trapveltraj(jointWaypoints,numel(trajTimes), …
‘AccelTime’,repmat(waypointAccelTimes,[numJoints 1]), …
‘EndTime’,repmat(diff(waypointTimes),[numJoints 1]));
case ‘cubic’
[q,qd,qdd] = cubicpolytraj(jointWaypoints,waypointTimes,trajTimes, …
‘VelocityBoundaryCondition’,waypointVels);
case ‘quintic’
[q,qd,qdd] = quinticpolytraj(jointWaypoints,waypointTimes,trajTimes, …
‘VelocityBoundaryCondition’,waypointVels, …
‘AccelerationBoundaryCondition’,waypointAccels);
case ‘bspline’
ctrlpoints = jointWaypoints; % Can adapt this as needed
[q,qd,qdd] = bsplinepolytraj(ctrlpoints,waypointTimes([1 end]),trajTimes);
% Remove the first velocity sample
qd(:,1) = zeros (7,1);
otherwise
error(‘Invalid trajectory type! Use ”trap”, ”cubic”, ”quintic”, or ”bspline”’);
end
% Let’s compute joint torques and power.
%
% Number of time intervals:
N = numel(trajTimes);
% jointTorq = inverseDynamics(gen3,q(:,1)’,qd(:,1)’,qdd(:,1)’)
% preallocate memory:
jointTorques = zeros(numJoints,N);
Power = zeros(1,N); % vector with N 0’s
TotalPower = zeros(1,N);
JointPower = zeros(numJoints,N);
for i = 1:N
jointTorques(:,i) = inverseDynamics(robot,q(:,i),qd(:,i),qdd(:,i));
Power(i) = dot(qd(:,i),jointTorques(:,i)); % scalar product
JointPower(:,i) = qd(:,i).*jointTorques(:,i); % element-wise product
TotalPower(i) = sumabs(JointPower(:,i)); % sum of absolute values
end
%calculating energyconsumption
Energyconsumption = trapz(trajTimes,TotalPower);
end
function gradient = computeGradient(waypointTimes)
% Compute gradient using numerical differentiation
epsilon = 1e-1; % Small perturbation
numWaypoints = numel(waypointTimes);
gradient = zeros(size(waypointTimes)-1);
for i = 2:numWaypoints-1 % Excluding the first and last waypoint times
% Perturb the waypoint time
global energy_perturbed;
waypointTimes_perturbed = waypointTimes;
waypointTimes_perturbed(i) = waypointTimes_perturbed(i) + epsilon;
% Compute energy consumption with perturbed waypoint times
energy_perturbed = generateEnergy(waypointTimes_perturbed);
Original_energy = generateEnergy(waypointTimes);
% Compute gradient using central difference
gradient(i-1) = (energy_perturbed – Original_energy) / epsilon;
end
end
% EXERCISE: adapt the script so to interpolate waypoints in the task
% spaceThis is the code right now it does the oppisite of a descent optimization. Do you know what is wrong with it?
I tried to minimize the energy of a robot path by changing the waypointtimes, right now it maximizes it for some reason?
clear all
clc
close all
global waypointTimes_start trajTimes;
waypointTimes_start = 1*[0 5 10 15 20];
% The trajectory will be divided into "Number_of_steps" steps:
Number_of_steps =20 ;
% Time is discretized in steps of duration ts:
ts = waypointTimes_start(length(waypointTimes_start))/Number_of_steps;
% Vector of discretized times:
trajTimes = 0:ts:waypointTimes_start(end);
waypointTimes_guess = 1 * [0 5 10 15 20];
% Fix the first and last waypoint times
waypointTimes_guess(1) = 0; % Fix the first waypoint time
waypointTimes_guess(end) = 20; % Fix the last waypoint time
% Set optimization parameters
alfa = 1e-2;
maxIterations = 100;
tolerance = 1e-4;
% Perform gradient descent optimization
waypointTimes = waypointTimes_guess;
for iter = 1:maxIterations
energy(iter)=generateEnergy(waypointTimes);
generateEnergy(waypointTimes)
gradient = computeGradient(waypointTimes);
waypointTimes(2:end-1)=waypointTimes(2:end-1)-alfa*gradient;
number_iterations(iter)=iter;
end
plot(number_iterations,energy,’b -‘);
xlabel(‘iterations’)
ylabel(‘Energy [W]’)
function Energyconsumption = generateEnergy(waypointTimes)
global trajTimes;
robot = loadrobot("kinovaGen3");
robot.Gravity = [0 0 -9.81];
robot.DataFormat = ‘column’;
q_home = [0 15 180 -130 0 55 90]’*pi/180;
eeName = string(robot.BodyNames(length(robot.BodyNames)));
T_home = getTransform(robot, q_home, eeName);
toolPositionHome = T_home(1:3,4);
% Define a Set of Waypoints Based on the Tool Position
waypoints = toolPositionHome + …
[0 0 0 ; -0.1 0.2 0.2 ; -0.2 0 0.1 ; -0.1 -0.2 0.2 ; 0 0 0]’;
orientations = [pi/2 0 pi/2;
(pi/2)+(pi/4) 0 pi/2;
pi/2 0 pi;
(pi/2)-(pi/4) 0 pi/2;
pi/2 0 pi/2]’;
%time from the start to the waypoints
% The trajectory will be divided into "Number_of_steps" steps:
% Time is discretized in steps of duration ts:
% Vector of discretized times:
% Velocities joints at waypoint:
waypointVels= 1*[0 0 0 0 0 0 0;
-1 -1 1 -1 1 0 -1;
-1 1 1 1 1 0 -1;
1 1 -1 -1 1 0 1;
0 0 0 0 0 0 0]’;
% Accelerations at waypoints is computed from velocity. But first we must
% allocate memory for accelerations:
%accelerations joints at waypoints
waypointAccels = 1*[0 0 0 0 0 0 0;
-1 -1 1 -1 1 0 -1;
-1 1 1 1 1 0 -1;
1 1 -1 -1 1 0 1;
0 0 0 0 0 0 0]’ ;
waypointAccelTimes = diff(waypointTimes)/4;
ik = inverseKinematics(‘RigidBodyTree’,robot);
% Weights for pose tolerances, specified as a six-element vector.
% The first three elements of the vector correspond to the weights
% on the error in orientation for the desired pose.
% The last three elements of the vector correspond to the weights on
% the error in the xyz position for the desired pose.
ikWeights = [1 1 1 1 1 1];
% inverseKinematics has several additional options (e.g. max number of
% interations, joint limits, tolerances, etc.)
% The numerical solution starts from an initial guess, taken here as the
% home configuration:
ikInitGuess = q_home’;
% Angles are adapted so to be between -pi e +pi:
ikInitGuess(ikInitGuess > pi) = ikInitGuess(ikInitGuess > pi) – 2*pi;
ikInitGuess(ikInitGuess < -pi) = ikInitGuess(ikInitGuess < -pi) + 2*pi;
% The inverse kinematics problem can be solved with reference to
% positions only, or we can also include the orientation of the EE
% by setting the following Boolean flag to "true":
includeOrientation = false;
numWaypoints = size(waypoints,2); % Number of waypoints
numJoints = numel(robot.homeConfiguration);
% Allocate memory:
jointWaypoints = zeros(numJoints,numWaypoints);
% Waypoints have been defined in Cartesian coordinates. They must be
% converted to the corresponding homogeneous transformation. This is done
% using "trvec2tform".
% Orientations have been described using Euler’s angles (Tait-Bryan,
% extrinsic ZYX). They must be transformed into homogeneous transformation.
% This is done by the command "eul2tform".
%trajectory following loop joint space
for idx = 1:numWaypoints
if includeOrientation
tgtPose = trvec2tform(waypoints(:,idx)’) * eul2tform(orientations(:,idx)’);
else
tgtPose = trvec2tform(waypoints(:,idx)’) * eul2tform([pi/2 0 pi/2]);
end
%IK = inverse kinematics
[config,~] = ik(eeName,tgtPose,ikWeights’,ikInitGuess’);
jointWaypoints(:,idx) = config’;
end
trajType = ‘trap’;
switch trajType
case ‘trap’
[q,qd,qdd] = trapveltraj(jointWaypoints,numel(trajTimes), …
‘AccelTime’,repmat(waypointAccelTimes,[numJoints 1]), …
‘EndTime’,repmat(diff(waypointTimes),[numJoints 1]));
case ‘cubic’
[q,qd,qdd] = cubicpolytraj(jointWaypoints,waypointTimes,trajTimes, …
‘VelocityBoundaryCondition’,waypointVels);
case ‘quintic’
[q,qd,qdd] = quinticpolytraj(jointWaypoints,waypointTimes,trajTimes, …
‘VelocityBoundaryCondition’,waypointVels, …
‘AccelerationBoundaryCondition’,waypointAccels);
case ‘bspline’
ctrlpoints = jointWaypoints; % Can adapt this as needed
[q,qd,qdd] = bsplinepolytraj(ctrlpoints,waypointTimes([1 end]),trajTimes);
% Remove the first velocity sample
qd(:,1) = zeros (7,1);
otherwise
error(‘Invalid trajectory type! Use ”trap”, ”cubic”, ”quintic”, or ”bspline”’);
end
% Let’s compute joint torques and power.
%
% Number of time intervals:
N = numel(trajTimes);
% jointTorq = inverseDynamics(gen3,q(:,1)’,qd(:,1)’,qdd(:,1)’)
% preallocate memory:
jointTorques = zeros(numJoints,N);
Power = zeros(1,N); % vector with N 0’s
TotalPower = zeros(1,N);
JointPower = zeros(numJoints,N);
for i = 1:N
jointTorques(:,i) = inverseDynamics(robot,q(:,i),qd(:,i),qdd(:,i));
Power(i) = dot(qd(:,i),jointTorques(:,i)); % scalar product
JointPower(:,i) = qd(:,i).*jointTorques(:,i); % element-wise product
TotalPower(i) = sumabs(JointPower(:,i)); % sum of absolute values
end
%calculating energyconsumption
Energyconsumption = trapz(trajTimes,TotalPower);
end
function gradient = computeGradient(waypointTimes)
% Compute gradient using numerical differentiation
epsilon = 1e-1; % Small perturbation
numWaypoints = numel(waypointTimes);
gradient = zeros(size(waypointTimes)-1);
for i = 2:numWaypoints-1 % Excluding the first and last waypoint times
% Perturb the waypoint time
global energy_perturbed;
waypointTimes_perturbed = waypointTimes;
waypointTimes_perturbed(i) = waypointTimes_perturbed(i) + epsilon;
% Compute energy consumption with perturbed waypoint times
energy_perturbed = generateEnergy(waypointTimes_perturbed);
Original_energy = generateEnergy(waypointTimes);
% Compute gradient using central difference
gradient(i-1) = (energy_perturbed – Original_energy) / epsilon;
end
end
% EXERCISE: adapt the script so to interpolate waypoints in the task
% space This is the code right now it does the oppisite of a descent optimization. Do you know what is wrong with it?
I tried to minimize the energy of a robot path by changing the waypointtimes, right now it maximizes it for some reason?
clear all
clc
close all
global waypointTimes_start trajTimes;
waypointTimes_start = 1*[0 5 10 15 20];
% The trajectory will be divided into "Number_of_steps" steps:
Number_of_steps =20 ;
% Time is discretized in steps of duration ts:
ts = waypointTimes_start(length(waypointTimes_start))/Number_of_steps;
% Vector of discretized times:
trajTimes = 0:ts:waypointTimes_start(end);
waypointTimes_guess = 1 * [0 5 10 15 20];
% Fix the first and last waypoint times
waypointTimes_guess(1) = 0; % Fix the first waypoint time
waypointTimes_guess(end) = 20; % Fix the last waypoint time
% Set optimization parameters
alfa = 1e-2;
maxIterations = 100;
tolerance = 1e-4;
% Perform gradient descent optimization
waypointTimes = waypointTimes_guess;
for iter = 1:maxIterations
energy(iter)=generateEnergy(waypointTimes);
generateEnergy(waypointTimes)
gradient = computeGradient(waypointTimes);
waypointTimes(2:end-1)=waypointTimes(2:end-1)-alfa*gradient;
number_iterations(iter)=iter;
end
plot(number_iterations,energy,’b -‘);
xlabel(‘iterations’)
ylabel(‘Energy [W]’)
function Energyconsumption = generateEnergy(waypointTimes)
global trajTimes;
robot = loadrobot("kinovaGen3");
robot.Gravity = [0 0 -9.81];
robot.DataFormat = ‘column’;
q_home = [0 15 180 -130 0 55 90]’*pi/180;
eeName = string(robot.BodyNames(length(robot.BodyNames)));
T_home = getTransform(robot, q_home, eeName);
toolPositionHome = T_home(1:3,4);
% Define a Set of Waypoints Based on the Tool Position
waypoints = toolPositionHome + …
[0 0 0 ; -0.1 0.2 0.2 ; -0.2 0 0.1 ; -0.1 -0.2 0.2 ; 0 0 0]’;
orientations = [pi/2 0 pi/2;
(pi/2)+(pi/4) 0 pi/2;
pi/2 0 pi;
(pi/2)-(pi/4) 0 pi/2;
pi/2 0 pi/2]’;
%time from the start to the waypoints
% The trajectory will be divided into "Number_of_steps" steps:
% Time is discretized in steps of duration ts:
% Vector of discretized times:
% Velocities joints at waypoint:
waypointVels= 1*[0 0 0 0 0 0 0;
-1 -1 1 -1 1 0 -1;
-1 1 1 1 1 0 -1;
1 1 -1 -1 1 0 1;
0 0 0 0 0 0 0]’;
% Accelerations at waypoints is computed from velocity. But first we must
% allocate memory for accelerations:
%accelerations joints at waypoints
waypointAccels = 1*[0 0 0 0 0 0 0;
-1 -1 1 -1 1 0 -1;
-1 1 1 1 1 0 -1;
1 1 -1 -1 1 0 1;
0 0 0 0 0 0 0]’ ;
waypointAccelTimes = diff(waypointTimes)/4;
ik = inverseKinematics(‘RigidBodyTree’,robot);
% Weights for pose tolerances, specified as a six-element vector.
% The first three elements of the vector correspond to the weights
% on the error in orientation for the desired pose.
% The last three elements of the vector correspond to the weights on
% the error in the xyz position for the desired pose.
ikWeights = [1 1 1 1 1 1];
% inverseKinematics has several additional options (e.g. max number of
% interations, joint limits, tolerances, etc.)
% The numerical solution starts from an initial guess, taken here as the
% home configuration:
ikInitGuess = q_home’;
% Angles are adapted so to be between -pi e +pi:
ikInitGuess(ikInitGuess > pi) = ikInitGuess(ikInitGuess > pi) – 2*pi;
ikInitGuess(ikInitGuess < -pi) = ikInitGuess(ikInitGuess < -pi) + 2*pi;
% The inverse kinematics problem can be solved with reference to
% positions only, or we can also include the orientation of the EE
% by setting the following Boolean flag to "true":
includeOrientation = false;
numWaypoints = size(waypoints,2); % Number of waypoints
numJoints = numel(robot.homeConfiguration);
% Allocate memory:
jointWaypoints = zeros(numJoints,numWaypoints);
% Waypoints have been defined in Cartesian coordinates. They must be
% converted to the corresponding homogeneous transformation. This is done
% using "trvec2tform".
% Orientations have been described using Euler’s angles (Tait-Bryan,
% extrinsic ZYX). They must be transformed into homogeneous transformation.
% This is done by the command "eul2tform".
%trajectory following loop joint space
for idx = 1:numWaypoints
if includeOrientation
tgtPose = trvec2tform(waypoints(:,idx)’) * eul2tform(orientations(:,idx)’);
else
tgtPose = trvec2tform(waypoints(:,idx)’) * eul2tform([pi/2 0 pi/2]);
end
%IK = inverse kinematics
[config,~] = ik(eeName,tgtPose,ikWeights’,ikInitGuess’);
jointWaypoints(:,idx) = config’;
end
trajType = ‘trap’;
switch trajType
case ‘trap’
[q,qd,qdd] = trapveltraj(jointWaypoints,numel(trajTimes), …
‘AccelTime’,repmat(waypointAccelTimes,[numJoints 1]), …
‘EndTime’,repmat(diff(waypointTimes),[numJoints 1]));
case ‘cubic’
[q,qd,qdd] = cubicpolytraj(jointWaypoints,waypointTimes,trajTimes, …
‘VelocityBoundaryCondition’,waypointVels);
case ‘quintic’
[q,qd,qdd] = quinticpolytraj(jointWaypoints,waypointTimes,trajTimes, …
‘VelocityBoundaryCondition’,waypointVels, …
‘AccelerationBoundaryCondition’,waypointAccels);
case ‘bspline’
ctrlpoints = jointWaypoints; % Can adapt this as needed
[q,qd,qdd] = bsplinepolytraj(ctrlpoints,waypointTimes([1 end]),trajTimes);
% Remove the first velocity sample
qd(:,1) = zeros (7,1);
otherwise
error(‘Invalid trajectory type! Use ”trap”, ”cubic”, ”quintic”, or ”bspline”’);
end
% Let’s compute joint torques and power.
%
% Number of time intervals:
N = numel(trajTimes);
% jointTorq = inverseDynamics(gen3,q(:,1)’,qd(:,1)’,qdd(:,1)’)
% preallocate memory:
jointTorques = zeros(numJoints,N);
Power = zeros(1,N); % vector with N 0’s
TotalPower = zeros(1,N);
JointPower = zeros(numJoints,N);
for i = 1:N
jointTorques(:,i) = inverseDynamics(robot,q(:,i),qd(:,i),qdd(:,i));
Power(i) = dot(qd(:,i),jointTorques(:,i)); % scalar product
JointPower(:,i) = qd(:,i).*jointTorques(:,i); % element-wise product
TotalPower(i) = sumabs(JointPower(:,i)); % sum of absolute values
end
%calculating energyconsumption
Energyconsumption = trapz(trajTimes,TotalPower);
end
function gradient = computeGradient(waypointTimes)
% Compute gradient using numerical differentiation
epsilon = 1e-1; % Small perturbation
numWaypoints = numel(waypointTimes);
gradient = zeros(size(waypointTimes)-1);
for i = 2:numWaypoints-1 % Excluding the first and last waypoint times
% Perturb the waypoint time
global energy_perturbed;
waypointTimes_perturbed = waypointTimes;
waypointTimes_perturbed(i) = waypointTimes_perturbed(i) + epsilon;
% Compute energy consumption with perturbed waypoint times
energy_perturbed = generateEnergy(waypointTimes_perturbed);
Original_energy = generateEnergy(waypointTimes);
% Compute gradient using central difference
gradient(i-1) = (energy_perturbed – Original_energy) / epsilon;
end
end
% EXERCISE: adapt the script so to interpolate waypoints in the task
% space optimization, steepest descent, robot MATLAB Answers — New Questions
Break in the axis
Hi
I have a plot of data points (x, y). The issue is that one of the first data points has a very large amplitude, whereas the rest of the data points have very small magnitudes. So what I thought that I wanted to do is to make a "cut" in the y-axis, such that it goes from 0..1 and then skips to 100..105. Perhaps with a mark such as this "—-//—-" in between.
Is that possible in MatLAB?
Best,
Niles.Hi
I have a plot of data points (x, y). The issue is that one of the first data points has a very large amplitude, whereas the rest of the data points have very small magnitudes. So what I thought that I wanted to do is to make a "cut" in the y-axis, such that it goes from 0..1 and then skips to 100..105. Perhaps with a mark such as this "—-//—-" in between.
Is that possible in MatLAB?
Best,
Niles. Hi
I have a plot of data points (x, y). The issue is that one of the first data points has a very large amplitude, whereas the rest of the data points have very small magnitudes. So what I thought that I wanted to do is to make a "cut" in the y-axis, such that it goes from 0..1 and then skips to 100..105. Perhaps with a mark such as this "—-//—-" in between.
Is that possible in MatLAB?
Best,
Niles. break y-axis MATLAB Answers — New Questions
Vector with symbolic variable
I have created a 8×1 sym (vector?) called psi and a 1×1000 double (vector?) called time. When I try to plug in a value from the double into the psi I use the syntax:
psi_eval = psi(time(2));
since this is the way I would have done it in python, however it does not work. I get an error saying:
Array indices must be positive integers or logical values.
Error in sym/subsref (line 909)
R_tilde = builtin(‘subsref’,L_tilde,Idx);
Error in BachelorThesis (line 65)
psi_eval = psi(time(2));
The array index I have given is a positive value so I don’t understand the error I get. What am I doing wrong?I have created a 8×1 sym (vector?) called psi and a 1×1000 double (vector?) called time. When I try to plug in a value from the double into the psi I use the syntax:
psi_eval = psi(time(2));
since this is the way I would have done it in python, however it does not work. I get an error saying:
Array indices must be positive integers or logical values.
Error in sym/subsref (line 909)
R_tilde = builtin(‘subsref’,L_tilde,Idx);
Error in BachelorThesis (line 65)
psi_eval = psi(time(2));
The array index I have given is a positive value so I don’t understand the error I get. What am I doing wrong? I have created a 8×1 sym (vector?) called psi and a 1×1000 double (vector?) called time. When I try to plug in a value from the double into the psi I use the syntax:
psi_eval = psi(time(2));
since this is the way I would have done it in python, however it does not work. I get an error saying:
Array indices must be positive integers or logical values.
Error in sym/subsref (line 909)
R_tilde = builtin(‘subsref’,L_tilde,Idx);
Error in BachelorThesis (line 65)
psi_eval = psi(time(2));
The array index I have given is a positive value so I don’t understand the error I get. What am I doing wrong? symbolic, vector MATLAB Answers — New Questions
have a static text display box to display text (GUI) app designer
Hello to everybody, I have a problem, I want to write a program with a graphical interface (GUI) app designer, I want to have a static text display box to display text information in matlap, but I don’t know where the static text is.Hello to everybody, I have a problem, I want to write a program with a graphical interface (GUI) app designer, I want to have a static text display box to display text information in matlap, but I don’t know where the static text is. Hello to everybody, I have a problem, I want to write a program with a graphical interface (GUI) app designer, I want to have a static text display box to display text information in matlap, but I don’t know where the static text is. static text(gui) app designer MATLAB Answers — New Questions
Plot a surface for a 3D matrix 2x361x360
Good morning, I have a problem with a matrix plot. Basically I get through calculations a 3D matrix and I need to plot it to make a powerpoint about the results I am getting. I have tried both surf and plot, but both commands are ineffective.Good morning, I have a problem with a matrix plot. Basically I get through calculations a 3D matrix and I need to plot it to make a powerpoint about the results I am getting. I have tried both surf and plot, but both commands are ineffective. Good morning, I have a problem with a matrix plot. Basically I get through calculations a 3D matrix and I need to plot it to make a powerpoint about the results I am getting. I have tried both surf and plot, but both commands are ineffective. 3d matrix, surface, plotting MATLAB Answers — New Questions
in 2024a version of MATLAB, I can’t see my training and validation accuracy in training plot progress.
I am using MATLAB 2024a version. Some functions and things are a littelke bit different in this version. I am experimenting a cnn architecture from scratch to classify images. In earlier version of MATLAB, final validation accuiracy could be seen in training plot progress. But in this version I can’t see it. I have checked the MATLAB documentation but could not find any solution.
Also, I can not use ‘classify’ function here and i am confused about ‘forward’ function in this version.I am using MATLAB 2024a version. Some functions and things are a littelke bit different in this version. I am experimenting a cnn architecture from scratch to classify images. In earlier version of MATLAB, final validation accuiracy could be seen in training plot progress. But in this version I can’t see it. I have checked the MATLAB documentation but could not find any solution.
Also, I can not use ‘classify’ function here and i am confused about ‘forward’ function in this version. I am using MATLAB 2024a version. Some functions and things are a littelke bit different in this version. I am experimenting a cnn architecture from scratch to classify images. In earlier version of MATLAB, final validation accuiracy could be seen in training plot progress. But in this version I can’t see it. I have checked the MATLAB documentation but could not find any solution.
Also, I can not use ‘classify’ function here and i am confused about ‘forward’ function in this version. validation accuracy, testing accuracy MATLAB Answers — New Questions
Line in Matlab plot do not appear
I am self studying Matlab and I want to create a plot with electron concentration and inverse temperature as the picture shows:
% Constants
k = 1.38e-23; % Boltzmann’s constant (J/K)
Eg = 1.12; % Energy band gap of silicon (eV)
A = 2.5e19; % Constant for intrinsic carrier concentration calculation
Nc = 2.8e19; % Effective density of states in conduction band (cm^-3)
Nd = 1e16; % Doping concentration (cm^-3)
% Temperature range
T = linspace(100, 1000, 100); % Temperature range from 100 K to 1000 K
% Electron concentration for n-type doping
n = (Nc * Nv)^0.5 * exp(-Eg./(2*k*T));
% Calculate ln(n)
ln_n = log(n);
% Calculate 1/T
inv_T = 1 ./ T;
% Plot
plot(inv_T, ln_n, ‘r’, ‘LineWidth’, 2);
xlabel(‘1/T’);
ylabel(‘ln(N_D)’);
title(‘ln(Electron Concentration) vs. 1/T for Silicon’);
grid on;
Does anyone knows ?I am self studying Matlab and I want to create a plot with electron concentration and inverse temperature as the picture shows:
% Constants
k = 1.38e-23; % Boltzmann’s constant (J/K)
Eg = 1.12; % Energy band gap of silicon (eV)
A = 2.5e19; % Constant for intrinsic carrier concentration calculation
Nc = 2.8e19; % Effective density of states in conduction band (cm^-3)
Nd = 1e16; % Doping concentration (cm^-3)
% Temperature range
T = linspace(100, 1000, 100); % Temperature range from 100 K to 1000 K
% Electron concentration for n-type doping
n = (Nc * Nv)^0.5 * exp(-Eg./(2*k*T));
% Calculate ln(n)
ln_n = log(n);
% Calculate 1/T
inv_T = 1 ./ T;
% Plot
plot(inv_T, ln_n, ‘r’, ‘LineWidth’, 2);
xlabel(‘1/T’);
ylabel(‘ln(N_D)’);
title(‘ln(Electron Concentration) vs. 1/T for Silicon’);
grid on;
Does anyone knows ? I am self studying Matlab and I want to create a plot with electron concentration and inverse temperature as the picture shows:
% Constants
k = 1.38e-23; % Boltzmann’s constant (J/K)
Eg = 1.12; % Energy band gap of silicon (eV)
A = 2.5e19; % Constant for intrinsic carrier concentration calculation
Nc = 2.8e19; % Effective density of states in conduction band (cm^-3)
Nd = 1e16; % Doping concentration (cm^-3)
% Temperature range
T = linspace(100, 1000, 100); % Temperature range from 100 K to 1000 K
% Electron concentration for n-type doping
n = (Nc * Nv)^0.5 * exp(-Eg./(2*k*T));
% Calculate ln(n)
ln_n = log(n);
% Calculate 1/T
inv_T = 1 ./ T;
% Plot
plot(inv_T, ln_n, ‘r’, ‘LineWidth’, 2);
xlabel(‘1/T’);
ylabel(‘ln(N_D)’);
title(‘ln(Electron Concentration) vs. 1/T for Silicon’);
grid on;
Does anyone knows ? plot, graphics, programming MATLAB Answers — New Questions
Solve long matrices equation
Hello,
please I would like help to solve this equation with matlab ( you can see it in the screenshot). I want to find the matrix P11. All other matrices in the equation are known.Hello,
please I would like help to solve this equation with matlab ( you can see it in the screenshot). I want to find the matrix P11. All other matrices in the equation are known. Hello,
please I would like help to solve this equation with matlab ( you can see it in the screenshot). I want to find the matrix P11. All other matrices in the equation are known. solve, matrices, equations MATLAB Answers — New Questions
loops and divisions by 7 and calling function
function [whatsLeft, divisionCount] = divideBySeven(number)
%Enter the code for your function here.
while number < 1
number = number / 7
divisionCount = divisionCount + 1
end
whatsLeft = number
this is my code to call my function:
[whatsLeft, divisionCount] = divideBySeven(256)
I tried to run this and the error was that: Output argument "divisionCount" (and maybe others) not assigned during call to "divideBySeven".function [whatsLeft, divisionCount] = divideBySeven(number)
%Enter the code for your function here.
while number < 1
number = number / 7
divisionCount = divisionCount + 1
end
whatsLeft = number
this is my code to call my function:
[whatsLeft, divisionCount] = divideBySeven(256)
I tried to run this and the error was that: Output argument "divisionCount" (and maybe others) not assigned during call to "divideBySeven". function [whatsLeft, divisionCount] = divideBySeven(number)
%Enter the code for your function here.
while number < 1
number = number / 7
divisionCount = divisionCount + 1
end
whatsLeft = number
this is my code to call my function:
[whatsLeft, divisionCount] = divideBySeven(256)
I tried to run this and the error was that: Output argument "divisionCount" (and maybe others) not assigned during call to "divideBySeven". loops MATLAB Answers — New Questions
read and store data from struct file during each iteration in the for loop
Hi,
I have a for loop as shown. During each iteration the will store entire output in the struct file named Measurements. (file attached here)
From this struct file file, I need to read and store only ‘Centroid’, ‘Eccentricity’, ‘EquivDiameter’ in the sepearte array.
for i = 1:1:1000
% some operation
Measurements = some operation
endHi,
I have a for loop as shown. During each iteration the will store entire output in the struct file named Measurements. (file attached here)
From this struct file file, I need to read and store only ‘Centroid’, ‘Eccentricity’, ‘EquivDiameter’ in the sepearte array.
for i = 1:1:1000
% some operation
Measurements = some operation
end Hi,
I have a for loop as shown. During each iteration the will store entire output in the struct file named Measurements. (file attached here)
From this struct file file, I need to read and store only ‘Centroid’, ‘Eccentricity’, ‘EquivDiameter’ in the sepearte array.
for i = 1:1:1000
% some operation
Measurements = some operation
end struct, cell array, for loop, store data, struct file MATLAB Answers — New Questions
matrix, where each element is a column vector
Excuse me, I need some help. I have an 11*7 matrix. Each element of this matrix consists of a column vector 1001*1. I want to calculate for each column matrix the maximum value. thanks for your help
ETATT=cell(11,7); % initial matrix
Etat=zeros(1001,1); % column vector, contained in each element of the ETATT matrix
I want to find the maximum value of each Etat contained in ETATT
THANKSExcuse me, I need some help. I have an 11*7 matrix. Each element of this matrix consists of a column vector 1001*1. I want to calculate for each column matrix the maximum value. thanks for your help
ETATT=cell(11,7); % initial matrix
Etat=zeros(1001,1); % column vector, contained in each element of the ETATT matrix
I want to find the maximum value of each Etat contained in ETATT
THANKS Excuse me, I need some help. I have an 11*7 matrix. Each element of this matrix consists of a column vector 1001*1. I want to calculate for each column matrix the maximum value. thanks for your help
ETATT=cell(11,7); % initial matrix
Etat=zeros(1001,1); % column vector, contained in each element of the ETATT matrix
I want to find the maximum value of each Etat contained in ETATT
THANKS cell, max, matrix MATLAB Answers — New Questions
How to prevent plotted contents to spill outside of the axes lines
Using
set(gca, ‘Layer’, ‘top’)
I end up with this:
Is there a way to completely hide plotted contents that appear beyond the axes?Using
set(gca, ‘Layer’, ‘top’)
I end up with this:
Is there a way to completely hide plotted contents that appear beyond the axes? Using
set(gca, ‘Layer’, ‘top’)
I end up with this:
Is there a way to completely hide plotted contents that appear beyond the axes? figure, axes MATLAB Answers — New Questions
inverser la matrice tri-diagonale
a=3*h -2;
b=1;
c=1;
A=diag(a*ones(1,N)) + diag(b*ones(1,N-1),1)+ diag(c*ones(1,N-1),-1)
inverser Aa=3*h -2;
b=1;
c=1;
A=diag(a*ones(1,N)) + diag(b*ones(1,N-1),1)+ diag(c*ones(1,N-1),-1)
inverser A a=3*h -2;
b=1;
c=1;
A=diag(a*ones(1,N)) + diag(b*ones(1,N-1),1)+ diag(c*ones(1,N-1),-1)
inverser A inverser MATLAB Answers — New Questions
how to fast simulink model in matlab when fuzzy controller is added
help mehelp me help me fuzzy controller MATLAB Answers — New Questions
Error in untitled22>solveHeatEquation1D (line 32) U(N+2,n+1) = beta(t); Error in untitled22 (line 11) [t, x, U] = solveHeatEquation1D(T, a, b,mu, u0,alpha, N, M);
a = 0; b = 1;
T = 2;
mu = 0.5;
alpha =1;
gamma=@(t) 0 ;
beta=@(t) 0 ;
u0 = @(x) (x.^4-x.^2);
N = 100;
M = 100;
[t, x, U] = solveHeatEquation1D(T, a, b,mu, u0,alpha, N, M);
surf(t, x, U);
shading interp , colormap ( ‘jet’ )
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘U’);
title(‘la Solution de equation par methode de diff finis’);
function [t, x, U] = solveHeatEquation1D(T, a, b, mu, u0,alpha, N, M)
dt = T/M;
t = 0:dt:T;
dx = (b-a)/N+1;
x = a:dx:b;
U = zeros(N+2, M+1);
E = mu *dt/dx^2;
C = 1 – 2*E;
D = alpha *(dt/(2*dx));
U(:,1) = u0(x);
for n = 1:M
for i = 2:N+1
U(N+2,n+1) = beta(t);
U(1,n+1) = gamma(t);
U(i,n+1) = (E-D)*U(i+1,n) + C*U(i,n) + (D-E)*U(i-1,n);
end
end
enda = 0; b = 1;
T = 2;
mu = 0.5;
alpha =1;
gamma=@(t) 0 ;
beta=@(t) 0 ;
u0 = @(x) (x.^4-x.^2);
N = 100;
M = 100;
[t, x, U] = solveHeatEquation1D(T, a, b,mu, u0,alpha, N, M);
surf(t, x, U);
shading interp , colormap ( ‘jet’ )
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘U’);
title(‘la Solution de equation par methode de diff finis’);
function [t, x, U] = solveHeatEquation1D(T, a, b, mu, u0,alpha, N, M)
dt = T/M;
t = 0:dt:T;
dx = (b-a)/N+1;
x = a:dx:b;
U = zeros(N+2, M+1);
E = mu *dt/dx^2;
C = 1 – 2*E;
D = alpha *(dt/(2*dx));
U(:,1) = u0(x);
for n = 1:M
for i = 2:N+1
U(N+2,n+1) = beta(t);
U(1,n+1) = gamma(t);
U(i,n+1) = (E-D)*U(i+1,n) + C*U(i,n) + (D-E)*U(i-1,n);
end
end
end a = 0; b = 1;
T = 2;
mu = 0.5;
alpha =1;
gamma=@(t) 0 ;
beta=@(t) 0 ;
u0 = @(x) (x.^4-x.^2);
N = 100;
M = 100;
[t, x, U] = solveHeatEquation1D(T, a, b,mu, u0,alpha, N, M);
surf(t, x, U);
shading interp , colormap ( ‘jet’ )
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘U’);
title(‘la Solution de equation par methode de diff finis’);
function [t, x, U] = solveHeatEquation1D(T, a, b, mu, u0,alpha, N, M)
dt = T/M;
t = 0:dt:T;
dx = (b-a)/N+1;
x = a:dx:b;
U = zeros(N+2, M+1);
E = mu *dt/dx^2;
C = 1 – 2*E;
D = alpha *(dt/(2*dx));
U(:,1) = u0(x);
for n = 1:M
for i = 2:N+1
U(N+2,n+1) = beta(t);
U(1,n+1) = gamma(t);
U(i,n+1) = (E-D)*U(i+1,n) + C*U(i,n) + (D-E)*U(i-1,n);
end
end
end error in untitled22 solveheatequation1d (line 32) MATLAB Answers — New Questions
is there a tool to calculate and plot voltage stability curves
i’m looking to matlab code or toolbox that calculate and plot voltage stability for simulink model like IEEE 9 bus system
please if you can help me, any advice will be highly apperciated
thanks in advancei’m looking to matlab code or toolbox that calculate and plot voltage stability for simulink model like IEEE 9 bus system
please if you can help me, any advice will be highly apperciated
thanks in advance i’m looking to matlab code or toolbox that calculate and plot voltage stability for simulink model like IEEE 9 bus system
please if you can help me, any advice will be highly apperciated
thanks in advance simpowersystems, power_system, stability, voltage, simulink MATLAB Answers — New Questions
How can I perform speaker verification for X-Vectors based on the ivectorsystem documentation?
I am trying to create a basic voice based attendance system as a beginner project for biometric based security. I am using MathWorks’ implementation of X-Vector systems for this project. Based on this link’s implementation of X-Vector based speaker verification : https://www.mathworks.com/help/audio/ug/speaker-recognition-using-x-vectors.html, I have already trained the TDNN, X-Vector system and PLDA scoring. I have also obtained thresholds for the PLDA and Cosine Similarity scoring here based on the Detection Error Tradeoff figure using the X-axis values of the EER.
Since the above link states that I-Vector and X-Vector share the same classifier backend ("The x-vector system backend, or classifier, is the same as developed for i-vector systems. For details on the backend, see Speaker Verification Using i-vectors and ivectorSystem."), how would I adapt the ivectorsystem’s verify() function in the speaker verification using I-Vectors example to use X-Vectors instead per this link : https://www.mathworks.com/help/audio/ref/ivectorsystem.html? Presumably, in the X-Vector speaker recognition link, all the helper functions were probably wrapper functions for X-Vector.I am trying to create a basic voice based attendance system as a beginner project for biometric based security. I am using MathWorks’ implementation of X-Vector systems for this project. Based on this link’s implementation of X-Vector based speaker verification : https://www.mathworks.com/help/audio/ug/speaker-recognition-using-x-vectors.html, I have already trained the TDNN, X-Vector system and PLDA scoring. I have also obtained thresholds for the PLDA and Cosine Similarity scoring here based on the Detection Error Tradeoff figure using the X-axis values of the EER.
Since the above link states that I-Vector and X-Vector share the same classifier backend ("The x-vector system backend, or classifier, is the same as developed for i-vector systems. For details on the backend, see Speaker Verification Using i-vectors and ivectorSystem."), how would I adapt the ivectorsystem’s verify() function in the speaker verification using I-Vectors example to use X-Vectors instead per this link : https://www.mathworks.com/help/audio/ref/ivectorsystem.html? Presumably, in the X-Vector speaker recognition link, all the helper functions were probably wrapper functions for X-Vector. I am trying to create a basic voice based attendance system as a beginner project for biometric based security. I am using MathWorks’ implementation of X-Vector systems for this project. Based on this link’s implementation of X-Vector based speaker verification : https://www.mathworks.com/help/audio/ug/speaker-recognition-using-x-vectors.html, I have already trained the TDNN, X-Vector system and PLDA scoring. I have also obtained thresholds for the PLDA and Cosine Similarity scoring here based on the Detection Error Tradeoff figure using the X-axis values of the EER.
Since the above link states that I-Vector and X-Vector share the same classifier backend ("The x-vector system backend, or classifier, is the same as developed for i-vector systems. For details on the backend, see Speaker Verification Using i-vectors and ivectorSystem."), how would I adapt the ivectorsystem’s verify() function in the speaker verification using I-Vectors example to use X-Vectors instead per this link : https://www.mathworks.com/help/audio/ref/ivectorsystem.html? Presumably, in the X-Vector speaker recognition link, all the helper functions were probably wrapper functions for X-Vector. audio processing, speaker recognition MATLAB Answers — New Questions
What models have been used in this research project of PEV fast charging station siting and sizing on coupled transportation and power network?
There is this research paper: https://ecal.berkeley.edu/pubs/PEV-Fast-Charging-Station-Siting.pdf
Please help to find which programs shall we use for this non linear optimisation constraint problem with multiple objective functions and multivariables.
Regards,
VishalThere is this research paper: https://ecal.berkeley.edu/pubs/PEV-Fast-Charging-Station-Siting.pdf
Please help to find which programs shall we use for this non linear optimisation constraint problem with multiple objective functions and multivariables.
Regards,
Vishal There is this research paper: https://ecal.berkeley.edu/pubs/PEV-Fast-Charging-Station-Siting.pdf
Please help to find which programs shall we use for this non linear optimisation constraint problem with multiple objective functions and multivariables.
Regards,
Vishal simpowersystems, optimization, nonlinear MATLAB Answers — New Questions