Category: Matlab
Category Archives: Matlab
trainbr returns best network by performance not the best regularized
Using trainbr in R2022b for a feedforwardnet should return the network with the best regularization. However, it seems that the best network by performance is returned. The performance in the following example is lowest in epoch 2 (as indicated by tr.best_epoch) and the returned net seem to be from this epoch (when I set net.trainParam.epochs=2 the same net results). This network is not very much regularized and the optimization process continues for another 998 epochs and ends with a "Effective # of Parameters" of roughly 4 which the result returned does not reflect at all.
If I set net.trainParam.max_fail=5; I can get train to return the net from epoch 19 which is nuch more regularized.
Long story short, I think trainbr is buggy and returns the wrong net.
rng(0)
% load data
[X, T_] = simplefit_dataset;
% resample data and apply noise
X= X(1:3:end);
T_= T_(1:3:end);
T= T_ + randn(size(T_));
% network with too many neurons
net= feedforwardnet(30, ‘trainbr’);
% net.trainParam.epochs=2;
% net.trainParam.max_fail=5;
[net, tr] = train(net, X, T);
% display results
Y = sim(net, X);
figure(1)
clf
hold on
plot(X, T_, ‘DisplayName’, ‘real’)
plot(X, Y, ‘DisplayName’, ‘model’)
plot(X(tr.trainInd), T(tr.trainInd), ‘.’, ‘DisplayName’, ‘Training’)
plot(X(tr.valInd), T(tr.valInd), ‘o’, ‘DisplayName’, ‘Validation’)
plot(X(tr.testInd), T(tr.testInd), ‘*’, ‘DisplayName’, ‘Test’)
hold off
grid on
legendUsing trainbr in R2022b for a feedforwardnet should return the network with the best regularization. However, it seems that the best network by performance is returned. The performance in the following example is lowest in epoch 2 (as indicated by tr.best_epoch) and the returned net seem to be from this epoch (when I set net.trainParam.epochs=2 the same net results). This network is not very much regularized and the optimization process continues for another 998 epochs and ends with a "Effective # of Parameters" of roughly 4 which the result returned does not reflect at all.
If I set net.trainParam.max_fail=5; I can get train to return the net from epoch 19 which is nuch more regularized.
Long story short, I think trainbr is buggy and returns the wrong net.
rng(0)
% load data
[X, T_] = simplefit_dataset;
% resample data and apply noise
X= X(1:3:end);
T_= T_(1:3:end);
T= T_ + randn(size(T_));
% network with too many neurons
net= feedforwardnet(30, ‘trainbr’);
% net.trainParam.epochs=2;
% net.trainParam.max_fail=5;
[net, tr] = train(net, X, T);
% display results
Y = sim(net, X);
figure(1)
clf
hold on
plot(X, T_, ‘DisplayName’, ‘real’)
plot(X, Y, ‘DisplayName’, ‘model’)
plot(X(tr.trainInd), T(tr.trainInd), ‘.’, ‘DisplayName’, ‘Training’)
plot(X(tr.valInd), T(tr.valInd), ‘o’, ‘DisplayName’, ‘Validation’)
plot(X(tr.testInd), T(tr.testInd), ‘*’, ‘DisplayName’, ‘Test’)
hold off
grid on
legend Using trainbr in R2022b for a feedforwardnet should return the network with the best regularization. However, it seems that the best network by performance is returned. The performance in the following example is lowest in epoch 2 (as indicated by tr.best_epoch) and the returned net seem to be from this epoch (when I set net.trainParam.epochs=2 the same net results). This network is not very much regularized and the optimization process continues for another 998 epochs and ends with a "Effective # of Parameters" of roughly 4 which the result returned does not reflect at all.
If I set net.trainParam.max_fail=5; I can get train to return the net from epoch 19 which is nuch more regularized.
Long story short, I think trainbr is buggy and returns the wrong net.
rng(0)
% load data
[X, T_] = simplefit_dataset;
% resample data and apply noise
X= X(1:3:end);
T_= T_(1:3:end);
T= T_ + randn(size(T_));
% network with too many neurons
net= feedforwardnet(30, ‘trainbr’);
% net.trainParam.epochs=2;
% net.trainParam.max_fail=5;
[net, tr] = train(net, X, T);
% display results
Y = sim(net, X);
figure(1)
clf
hold on
plot(X, T_, ‘DisplayName’, ‘real’)
plot(X, Y, ‘DisplayName’, ‘model’)
plot(X(tr.trainInd), T(tr.trainInd), ‘.’, ‘DisplayName’, ‘Training’)
plot(X(tr.valInd), T(tr.valInd), ‘o’, ‘DisplayName’, ‘Validation’)
plot(X(tr.testInd), T(tr.testInd), ‘*’, ‘DisplayName’, ‘Test’)
hold off
grid on
legend trainbr, regularization MATLAB Answers — New Questions
simulink Array plot channel bug?
when I array plot three vector use 3 port , start a run simulation but the channel1 channel2 channel3 sometimes not the same order as the port from up to down?when I array plot three vector use 3 port , start a run simulation but the channel1 channel2 channel3 sometimes not the same order as the port from up to down? when I array plot three vector use 3 port , start a run simulation but the channel1 channel2 channel3 sometimes not the same order as the port from up to down? array plot, simulink MATLAB Answers — New Questions
Pacer in the codegen Executable
Hi,
I used to use the Set Pace block in the Aerospace Blockset for pilot in the loop simulation and use Simulink coder to generate a .exe file. The .exe can run in real-time as a standalone software without Matlab installed. Mathworks seems to block such function with latest Simulink Coder. The coder will ignor the pace block.
Is there any alternative way to generate an .exe with real-time pace?
Thanks!Hi,
I used to use the Set Pace block in the Aerospace Blockset for pilot in the loop simulation and use Simulink coder to generate a .exe file. The .exe can run in real-time as a standalone software without Matlab installed. Mathworks seems to block such function with latest Simulink Coder. The coder will ignor the pace block.
Is there any alternative way to generate an .exe with real-time pace?
Thanks! Hi,
I used to use the Set Pace block in the Aerospace Blockset for pilot in the loop simulation and use Simulink coder to generate a .exe file. The .exe can run in real-time as a standalone software without Matlab installed. Mathworks seems to block such function with latest Simulink Coder. The coder will ignor the pace block.
Is there any alternative way to generate an .exe with real-time pace?
Thanks! pacer, real-time, codegen, executable MATLAB Answers — New Questions
Find Geiger counter CPM
I am trying to find the counts per minute of a geiger counter signal using Simulink.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds)I am trying to find the counts per minute of a geiger counter signal using Simulink.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds) I am trying to find the counts per minute of a geiger counter signal using Simulink.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds) simulink, geiger counter, counts per minute MATLAB Answers — New Questions
How to calculate Hypervolume Indicator for Negative Objective Values on Pareto Front
Good day.
I’m currently working on a two-objective multiobjective algorithm. I need assistance in calculating the hypervolume indicator between the estimated Pareto front (P) and a reference point (R). Despite checking certain Matlab files, such as
Yi Cao (2023). Hypervolume Indicator (https://www.mathworks.com/matlabcentral/fileexchange/19651-hypervolume-indicator), MATLAB Central File Exchange. Retrieved December 15, 2023.
Bahman Ahmadi (2023). C-index, spacing, and hypervolume (https://www.mathworks.com/matlabcentral/fileexchange/125980-c-index-spacing-and-hypervolume), MATLAB Central File Exchange. Retrieved December 15, 2023.
it seems they only support cases where the objective function values on the Pareto front are strictly positive.
When I tested with benchmark functions like Kursawe (which has negative objectives function values on both sides), the hypervolume results appeared incorrect. Are there any solutions or code available for calculating the hypervolume when objective function values are negative?"
Thank you in advance.Good day.
I’m currently working on a two-objective multiobjective algorithm. I need assistance in calculating the hypervolume indicator between the estimated Pareto front (P) and a reference point (R). Despite checking certain Matlab files, such as
Yi Cao (2023). Hypervolume Indicator (https://www.mathworks.com/matlabcentral/fileexchange/19651-hypervolume-indicator), MATLAB Central File Exchange. Retrieved December 15, 2023.
Bahman Ahmadi (2023). C-index, spacing, and hypervolume (https://www.mathworks.com/matlabcentral/fileexchange/125980-c-index-spacing-and-hypervolume), MATLAB Central File Exchange. Retrieved December 15, 2023.
it seems they only support cases where the objective function values on the Pareto front are strictly positive.
When I tested with benchmark functions like Kursawe (which has negative objectives function values on both sides), the hypervolume results appeared incorrect. Are there any solutions or code available for calculating the hypervolume when objective function values are negative?"
Thank you in advance. Good day.
I’m currently working on a two-objective multiobjective algorithm. I need assistance in calculating the hypervolume indicator between the estimated Pareto front (P) and a reference point (R). Despite checking certain Matlab files, such as
Yi Cao (2023). Hypervolume Indicator (https://www.mathworks.com/matlabcentral/fileexchange/19651-hypervolume-indicator), MATLAB Central File Exchange. Retrieved December 15, 2023.
Bahman Ahmadi (2023). C-index, spacing, and hypervolume (https://www.mathworks.com/matlabcentral/fileexchange/125980-c-index-spacing-and-hypervolume), MATLAB Central File Exchange. Retrieved December 15, 2023.
it seems they only support cases where the objective function values on the Pareto front are strictly positive.
When I tested with benchmark functions like Kursawe (which has negative objectives function values on both sides), the hypervolume results appeared incorrect. Are there any solutions or code available for calculating the hypervolume when objective function values are negative?"
Thank you in advance. hypervolume, pareto, optimization, benchmark function MATLAB Answers — New Questions
Error : Unable to use a value of type optim.problemdef.OptimizationVariable as an index.
Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance!Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance! Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance! optimization, solve, error MATLAB Answers — New Questions
Find Geiger counter CPM
I am trying to find the counts per minute of a geiger counter signal.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds)I am trying to find the counts per minute of a geiger counter signal.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds) I am trying to find the counts per minute of a geiger counter signal.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds) simulink, geiger counter, counts per minute MATLAB Answers — New Questions
How to differentiate a time series while minimizing noise in the signal?
I have a timeseries that represents the X coordinate of the 3D position of a point (see top plot in image, please ignore vertical lines as they’re not relevant). I want to compute its velocity, acceleration, and jerk. I am currently just using diff() but as you can see in the 3rd & 4th plots, the noise increases so much that it’s not very useful.
I know that differentiating will always introduce some noise. But how can I filter and/or differentiate this signal with minimal noise added?
I tried looking into FFT and Mathworks’ page on derivatives using digital signal processing techniques but am at a loss currently.
Another idea I had is to fit an exponential function to the data, then differentiate that and interpolate it, but I’m not sure if that’s the right approach.
Also, the sampling rate of my data is 250 Hz, X axis tick labels are indices.I have a timeseries that represents the X coordinate of the 3D position of a point (see top plot in image, please ignore vertical lines as they’re not relevant). I want to compute its velocity, acceleration, and jerk. I am currently just using diff() but as you can see in the 3rd & 4th plots, the noise increases so much that it’s not very useful.
I know that differentiating will always introduce some noise. But how can I filter and/or differentiate this signal with minimal noise added?
I tried looking into FFT and Mathworks’ page on derivatives using digital signal processing techniques but am at a loss currently.
Another idea I had is to fit an exponential function to the data, then differentiate that and interpolate it, but I’m not sure if that’s the right approach.
Also, the sampling rate of my data is 250 Hz, X axis tick labels are indices. I have a timeseries that represents the X coordinate of the 3D position of a point (see top plot in image, please ignore vertical lines as they’re not relevant). I want to compute its velocity, acceleration, and jerk. I am currently just using diff() but as you can see in the 3rd & 4th plots, the noise increases so much that it’s not very useful.
I know that differentiating will always introduce some noise. But how can I filter and/or differentiate this signal with minimal noise added?
I tried looking into FFT and Mathworks’ page on derivatives using digital signal processing techniques but am at a loss currently.
Another idea I had is to fit an exponential function to the data, then differentiate that and interpolate it, but I’m not sure if that’s the right approach.
Also, the sampling rate of my data is 250 Hz, X axis tick labels are indices. derivative, time series, noise, digital signal processing, signal processing, acceleration, jerk, velocity MATLAB Answers — New Questions
3D position approximation of object using magnetometer and permanent magnet
Hey everyone,
I am currently using an Arduino Uno, a permanent magnet and a magnetometer to get the x, y and z coordinates of a metal object within a small rectangular box of known size. The magnetometer and permanent magnet are separated by 5cm, and the metal object moves between them (with the theory being that the metal object blocks the magnetic field from the permanent magnet, causing the readings measured by the magnetometer to change). To prove the concept, I used Matlab to take the magnetic field strength readings (which are output as x, y and z readings) at known distances, and create a calibration curve, in which I derived the equation (I only moved the metal object in one plane). This worked great, as long as the object is along the exact path I calibrated it for.
The problem is that the metal object can move anywhere within the box, and for example, movement only in the x plane also causes change in the y and z planes magnetic field readings. This causes the distance measurements to be wrong, unless the object follows the exact path it was calibrated for. So now I have moved to calibrating the position and magnetic field data in 3D, and this is where I am stuck. I am currently measuring the magnetic field data at different positions in the 3D plane, and storing this as a .mat file for another seperate code to use in real-time to find the position. The issue is that the readings are nowhere near accurate or even representative of distance.
I appreciate any help/suggestions. Cheers.
Calibration Code
% Initialize 3D grid of positions
x_positions = 0:2.5:5; % X Positions from 0cm to 5cm in steps of 2.5cm
y_positions = 0:2.5:7.5; % Y Positions from 0cm to 7.5cm in steps of 2.5cm
z_positions = 0:2.5:5; % Z Positions from 0cm to 10cm in steps of 2.5cm
% Note increment steps can be decreased, but only once the code is working
% accurately.
% Initialize 3D arrays for magnetic field measurements
Bx = zeros(length(y_positions), length(x_positions), length(z_positions));
By = zeros(length(y_positions), length(x_positions), length(z_positions));
Bz = zeros(length(y_positions), length(x_positions), length(z_positions));
% Set up serial connection
s = serial(‘COM4’);
set(s,’BaudRate’,115200);
s.InputBufferSize = 4096; % Increase input buffer size
fopen(s);
% Number of measurements to average
num_measurements = 100;
% Loop over all positions in the grid
for i = 1:length(x_positions)
for j = 1:length(y_positions)
for k = 1:length(z_positions)
% Print current position
fprintf(‘Current position: X = %.2f cm, Y = %.2f cm, Z = %.2f cmn’, x_positions(i), y_positions(j), z_positions(k));
% Wait for user to press Enter before taking measurements
input(‘Move needle to current position and press Enter’);
% Initialize arrays to store multiple measurements
magnetic_X = zeros(num_measurements, 1);
magnetic_Y = zeros(num_measurements, 1);
magnetic_Z = zeros(num_measurements, 1);
% Take multiple measurements
for m = 1:num_measurements
% Measure magnetic field at current position
line = fgets(s);
% Check if data contains ‘X:’, ‘Y:’, and ‘Z:’ labels
if contains(line, ‘X:’) && contains(line, ‘Y:’) && contains(line, ‘Z:’)
magnetic = sscanf(line, ‘X:%f, Y:%f, Z:%f’);
% Check if magnetic has 3 elements
if length(magnetic) == 3
% Store magnetic fields in arrays
magnetic_X(m) = magnetic(1);
magnetic_Y(m) = magnetic(2);
magnetic_Z(m) = magnetic(3);
else
fprintf(‘Unexpected data format: %sn’, line);
end
else
fprintf(‘Unexpected data format: %sn’, line);
end
end
% Average the measurements and store in Bx, By, Bz
Bx(j, i, k) = mean(magnetic_X);
By(j, i, k) = mean(magnetic_Y);
Bz(j, i, k) = mean(magnetic_Z);
end
end
end
% Close serial connection
fclose(s);
% Create a 3D grid for interpolation
[X, Y, Z] = meshgrid(x_positions, y_positions, z_positions);
% Flatten and concatenate the grid coordinates
X_flat = X(:);
Y_flat = Y(:);
Z_flat = Z(:);
% Flatten and concatenate the magnetic field measurements
Bx_flat = Bx(:);
By_flat = By(:);
Bz_flat = Bz(:);
% Combine the magnetic field measurements into a matrix
B_flat = [Bx_flat, By_flat, Bz_flat];
% Train three SVM models
mdl_x = fitrsvm(B_flat, X_flat);
mdl_y = fitrsvm(B_flat, Y_flat);
mdl_z = fitrsvm(B_flat, Z_flat);
% Save to a .mat file
save(‘C:\Users\calibration_data.mat’, ‘x_positions’, ‘y_positions’, ‘z_positions’, ‘Bx’, ‘By’, ‘Bz’, ‘mdl_x’, ‘mdl_y’, ‘mdl_z’);Hey everyone,
I am currently using an Arduino Uno, a permanent magnet and a magnetometer to get the x, y and z coordinates of a metal object within a small rectangular box of known size. The magnetometer and permanent magnet are separated by 5cm, and the metal object moves between them (with the theory being that the metal object blocks the magnetic field from the permanent magnet, causing the readings measured by the magnetometer to change). To prove the concept, I used Matlab to take the magnetic field strength readings (which are output as x, y and z readings) at known distances, and create a calibration curve, in which I derived the equation (I only moved the metal object in one plane). This worked great, as long as the object is along the exact path I calibrated it for.
The problem is that the metal object can move anywhere within the box, and for example, movement only in the x plane also causes change in the y and z planes magnetic field readings. This causes the distance measurements to be wrong, unless the object follows the exact path it was calibrated for. So now I have moved to calibrating the position and magnetic field data in 3D, and this is where I am stuck. I am currently measuring the magnetic field data at different positions in the 3D plane, and storing this as a .mat file for another seperate code to use in real-time to find the position. The issue is that the readings are nowhere near accurate or even representative of distance.
I appreciate any help/suggestions. Cheers.
Calibration Code
% Initialize 3D grid of positions
x_positions = 0:2.5:5; % X Positions from 0cm to 5cm in steps of 2.5cm
y_positions = 0:2.5:7.5; % Y Positions from 0cm to 7.5cm in steps of 2.5cm
z_positions = 0:2.5:5; % Z Positions from 0cm to 10cm in steps of 2.5cm
% Note increment steps can be decreased, but only once the code is working
% accurately.
% Initialize 3D arrays for magnetic field measurements
Bx = zeros(length(y_positions), length(x_positions), length(z_positions));
By = zeros(length(y_positions), length(x_positions), length(z_positions));
Bz = zeros(length(y_positions), length(x_positions), length(z_positions));
% Set up serial connection
s = serial(‘COM4’);
set(s,’BaudRate’,115200);
s.InputBufferSize = 4096; % Increase input buffer size
fopen(s);
% Number of measurements to average
num_measurements = 100;
% Loop over all positions in the grid
for i = 1:length(x_positions)
for j = 1:length(y_positions)
for k = 1:length(z_positions)
% Print current position
fprintf(‘Current position: X = %.2f cm, Y = %.2f cm, Z = %.2f cmn’, x_positions(i), y_positions(j), z_positions(k));
% Wait for user to press Enter before taking measurements
input(‘Move needle to current position and press Enter’);
% Initialize arrays to store multiple measurements
magnetic_X = zeros(num_measurements, 1);
magnetic_Y = zeros(num_measurements, 1);
magnetic_Z = zeros(num_measurements, 1);
% Take multiple measurements
for m = 1:num_measurements
% Measure magnetic field at current position
line = fgets(s);
% Check if data contains ‘X:’, ‘Y:’, and ‘Z:’ labels
if contains(line, ‘X:’) && contains(line, ‘Y:’) && contains(line, ‘Z:’)
magnetic = sscanf(line, ‘X:%f, Y:%f, Z:%f’);
% Check if magnetic has 3 elements
if length(magnetic) == 3
% Store magnetic fields in arrays
magnetic_X(m) = magnetic(1);
magnetic_Y(m) = magnetic(2);
magnetic_Z(m) = magnetic(3);
else
fprintf(‘Unexpected data format: %sn’, line);
end
else
fprintf(‘Unexpected data format: %sn’, line);
end
end
% Average the measurements and store in Bx, By, Bz
Bx(j, i, k) = mean(magnetic_X);
By(j, i, k) = mean(magnetic_Y);
Bz(j, i, k) = mean(magnetic_Z);
end
end
end
% Close serial connection
fclose(s);
% Create a 3D grid for interpolation
[X, Y, Z] = meshgrid(x_positions, y_positions, z_positions);
% Flatten and concatenate the grid coordinates
X_flat = X(:);
Y_flat = Y(:);
Z_flat = Z(:);
% Flatten and concatenate the magnetic field measurements
Bx_flat = Bx(:);
By_flat = By(:);
Bz_flat = Bz(:);
% Combine the magnetic field measurements into a matrix
B_flat = [Bx_flat, By_flat, Bz_flat];
% Train three SVM models
mdl_x = fitrsvm(B_flat, X_flat);
mdl_y = fitrsvm(B_flat, Y_flat);
mdl_z = fitrsvm(B_flat, Z_flat);
% Save to a .mat file
save(‘C:\Users\calibration_data.mat’, ‘x_positions’, ‘y_positions’, ‘z_positions’, ‘Bx’, ‘By’, ‘Bz’, ‘mdl_x’, ‘mdl_y’, ‘mdl_z’); Hey everyone,
I am currently using an Arduino Uno, a permanent magnet and a magnetometer to get the x, y and z coordinates of a metal object within a small rectangular box of known size. The magnetometer and permanent magnet are separated by 5cm, and the metal object moves between them (with the theory being that the metal object blocks the magnetic field from the permanent magnet, causing the readings measured by the magnetometer to change). To prove the concept, I used Matlab to take the magnetic field strength readings (which are output as x, y and z readings) at known distances, and create a calibration curve, in which I derived the equation (I only moved the metal object in one plane). This worked great, as long as the object is along the exact path I calibrated it for.
The problem is that the metal object can move anywhere within the box, and for example, movement only in the x plane also causes change in the y and z planes magnetic field readings. This causes the distance measurements to be wrong, unless the object follows the exact path it was calibrated for. So now I have moved to calibrating the position and magnetic field data in 3D, and this is where I am stuck. I am currently measuring the magnetic field data at different positions in the 3D plane, and storing this as a .mat file for another seperate code to use in real-time to find the position. The issue is that the readings are nowhere near accurate or even representative of distance.
I appreciate any help/suggestions. Cheers.
Calibration Code
% Initialize 3D grid of positions
x_positions = 0:2.5:5; % X Positions from 0cm to 5cm in steps of 2.5cm
y_positions = 0:2.5:7.5; % Y Positions from 0cm to 7.5cm in steps of 2.5cm
z_positions = 0:2.5:5; % Z Positions from 0cm to 10cm in steps of 2.5cm
% Note increment steps can be decreased, but only once the code is working
% accurately.
% Initialize 3D arrays for magnetic field measurements
Bx = zeros(length(y_positions), length(x_positions), length(z_positions));
By = zeros(length(y_positions), length(x_positions), length(z_positions));
Bz = zeros(length(y_positions), length(x_positions), length(z_positions));
% Set up serial connection
s = serial(‘COM4’);
set(s,’BaudRate’,115200);
s.InputBufferSize = 4096; % Increase input buffer size
fopen(s);
% Number of measurements to average
num_measurements = 100;
% Loop over all positions in the grid
for i = 1:length(x_positions)
for j = 1:length(y_positions)
for k = 1:length(z_positions)
% Print current position
fprintf(‘Current position: X = %.2f cm, Y = %.2f cm, Z = %.2f cmn’, x_positions(i), y_positions(j), z_positions(k));
% Wait for user to press Enter before taking measurements
input(‘Move needle to current position and press Enter’);
% Initialize arrays to store multiple measurements
magnetic_X = zeros(num_measurements, 1);
magnetic_Y = zeros(num_measurements, 1);
magnetic_Z = zeros(num_measurements, 1);
% Take multiple measurements
for m = 1:num_measurements
% Measure magnetic field at current position
line = fgets(s);
% Check if data contains ‘X:’, ‘Y:’, and ‘Z:’ labels
if contains(line, ‘X:’) && contains(line, ‘Y:’) && contains(line, ‘Z:’)
magnetic = sscanf(line, ‘X:%f, Y:%f, Z:%f’);
% Check if magnetic has 3 elements
if length(magnetic) == 3
% Store magnetic fields in arrays
magnetic_X(m) = magnetic(1);
magnetic_Y(m) = magnetic(2);
magnetic_Z(m) = magnetic(3);
else
fprintf(‘Unexpected data format: %sn’, line);
end
else
fprintf(‘Unexpected data format: %sn’, line);
end
end
% Average the measurements and store in Bx, By, Bz
Bx(j, i, k) = mean(magnetic_X);
By(j, i, k) = mean(magnetic_Y);
Bz(j, i, k) = mean(magnetic_Z);
end
end
end
% Close serial connection
fclose(s);
% Create a 3D grid for interpolation
[X, Y, Z] = meshgrid(x_positions, y_positions, z_positions);
% Flatten and concatenate the grid coordinates
X_flat = X(:);
Y_flat = Y(:);
Z_flat = Z(:);
% Flatten and concatenate the magnetic field measurements
Bx_flat = Bx(:);
By_flat = By(:);
Bz_flat = Bz(:);
% Combine the magnetic field measurements into a matrix
B_flat = [Bx_flat, By_flat, Bz_flat];
% Train three SVM models
mdl_x = fitrsvm(B_flat, X_flat);
mdl_y = fitrsvm(B_flat, Y_flat);
mdl_z = fitrsvm(B_flat, Z_flat);
% Save to a .mat file
save(‘C:\Users\calibration_data.mat’, ‘x_positions’, ‘y_positions’, ‘z_positions’, ‘Bx’, ‘By’, ‘Bz’, ‘mdl_x’, ‘mdl_y’, ‘mdl_z’); signal processing, 3d, machine learning, arduino, magnetometer MATLAB Answers — New Questions
3D position approximation of object using magnetometer and permanent magnet
Hey everyone,
I am currently using an Arduino Uno, a permanent magnet and a magnetometer to get the x, y and z coordinates of a metal object within a small rectangular box of known size. The magnetometer and permanent magnet are separated by 5cm, and the metal object moves between them (with the theory being that the metal object blocks the magnetic field from the permanent magnet, causing the readings measured by the magnetometer to change). To prove the concept, I used Matlab to take the magnetic field strength readings (which are output as x, y and z readings) at known distances, and create a calibration curve, in which I derived the equation (I only moved the metal object in one plane). This worked great, as long as the object is along the exact path I calibrated it for.
The problem is that the metal object can move anywhere within the box, and for example, movement only in the x plane also causes change in the y and z planes magnetic field readings. This causes the distance measurements to be wrong, unless the object follows the exact path it was calibrated for. So now I have moved to calibrating the position and magnetic field data in 3D, and this is where I am stuck. I am currently measuring the magnetic field data at different positions in the 3D plane, and storing this as a .mat file for another seperate code to use in real-time to find the position. The issue is that the readings are nowhere near accurate or even representative of distance.
I appreciate any help/suggestions. Cheers.
Calibration Code
% Initialize 3D grid of positions
x_positions = 0:2.5:5; % X Positions from 0cm to 5cm in steps of 2.5cm
y_positions = 0:2.5:7.5; % Y Positions from 0cm to 7.5cm in steps of 2.5cm
z_positions = 0:2.5:5; % Z Positions from 0cm to 10cm in steps of 2.5cm
% Note increment steps can be decreased, but only once the code is working
% accurately.
% Initialize 3D arrays for magnetic field measurements
Bx = zeros(length(y_positions), length(x_positions), length(z_positions));
By = zeros(length(y_positions), length(x_positions), length(z_positions));
Bz = zeros(length(y_positions), length(x_positions), length(z_positions));
% Set up serial connection
s = serial(‘COM4’);
set(s,’BaudRate’,115200);
s.InputBufferSize = 4096; % Increase input buffer size
fopen(s);
% Number of measurements to average
num_measurements = 100;
% Loop over all positions in the grid
for i = 1:length(x_positions)
for j = 1:length(y_positions)
for k = 1:length(z_positions)
% Print current position
fprintf(‘Current position: X = %.2f cm, Y = %.2f cm, Z = %.2f cmn’, x_positions(i), y_positions(j), z_positions(k));
% Wait for user to press Enter before taking measurements
input(‘Move needle to current position and press Enter’);
% Initialize arrays to store multiple measurements
magnetic_X = zeros(num_measurements, 1);
magnetic_Y = zeros(num_measurements, 1);
magnetic_Z = zeros(num_measurements, 1);
% Take multiple measurements
for m = 1:num_measurements
% Measure magnetic field at current position
line = fgets(s);
% Check if data contains ‘X:’, ‘Y:’, and ‘Z:’ labels
if contains(line, ‘X:’) && contains(line, ‘Y:’) && contains(line, ‘Z:’)
magnetic = sscanf(line, ‘X:%f, Y:%f, Z:%f’);
% Check if magnetic has 3 elements
if length(magnetic) == 3
% Store magnetic fields in arrays
magnetic_X(m) = magnetic(1);
magnetic_Y(m) = magnetic(2);
magnetic_Z(m) = magnetic(3);
else
fprintf(‘Unexpected data format: %sn’, line);
end
else
fprintf(‘Unexpected data format: %sn’, line);
end
end
% Average the measurements and store in Bx, By, Bz
Bx(j, i, k) = mean(magnetic_X);
By(j, i, k) = mean(magnetic_Y);
Bz(j, i, k) = mean(magnetic_Z);
end
end
end
% Close serial connection
fclose(s);
% Create a 3D grid for interpolation
[X, Y, Z] = meshgrid(x_positions, y_positions, z_positions);
% Flatten and concatenate the grid coordinates
X_flat = X(:);
Y_flat = Y(:);
Z_flat = Z(:);
% Flatten and concatenate the magnetic field measurements
Bx_flat = Bx(:);
By_flat = By(:);
Bz_flat = Bz(:);
% Combine the magnetic field measurements into a matrix
B_flat = [Bx_flat, By_flat, Bz_flat];
% Train three SVM models
mdl_x = fitrsvm(B_flat, X_flat);
mdl_y = fitrsvm(B_flat, Y_flat);
mdl_z = fitrsvm(B_flat, Z_flat);
% Save to a .mat file
save(‘C:\Users\calibration_data.mat’, ‘x_positions’, ‘y_positions’, ‘z_positions’, ‘Bx’, ‘By’, ‘Bz’, ‘mdl_x’, ‘mdl_y’, ‘mdl_z’);Hey everyone,
I am currently using an Arduino Uno, a permanent magnet and a magnetometer to get the x, y and z coordinates of a metal object within a small rectangular box of known size. The magnetometer and permanent magnet are separated by 5cm, and the metal object moves between them (with the theory being that the metal object blocks the magnetic field from the permanent magnet, causing the readings measured by the magnetometer to change). To prove the concept, I used Matlab to take the magnetic field strength readings (which are output as x, y and z readings) at known distances, and create a calibration curve, in which I derived the equation (I only moved the metal object in one plane). This worked great, as long as the object is along the exact path I calibrated it for.
The problem is that the metal object can move anywhere within the box, and for example, movement only in the x plane also causes change in the y and z planes magnetic field readings. This causes the distance measurements to be wrong, unless the object follows the exact path it was calibrated for. So now I have moved to calibrating the position and magnetic field data in 3D, and this is where I am stuck. I am currently measuring the magnetic field data at different positions in the 3D plane, and storing this as a .mat file for another seperate code to use in real-time to find the position. The issue is that the readings are nowhere near accurate or even representative of distance.
I appreciate any help/suggestions. Cheers.
Calibration Code
% Initialize 3D grid of positions
x_positions = 0:2.5:5; % X Positions from 0cm to 5cm in steps of 2.5cm
y_positions = 0:2.5:7.5; % Y Positions from 0cm to 7.5cm in steps of 2.5cm
z_positions = 0:2.5:5; % Z Positions from 0cm to 10cm in steps of 2.5cm
% Note increment steps can be decreased, but only once the code is working
% accurately.
% Initialize 3D arrays for magnetic field measurements
Bx = zeros(length(y_positions), length(x_positions), length(z_positions));
By = zeros(length(y_positions), length(x_positions), length(z_positions));
Bz = zeros(length(y_positions), length(x_positions), length(z_positions));
% Set up serial connection
s = serial(‘COM4’);
set(s,’BaudRate’,115200);
s.InputBufferSize = 4096; % Increase input buffer size
fopen(s);
% Number of measurements to average
num_measurements = 100;
% Loop over all positions in the grid
for i = 1:length(x_positions)
for j = 1:length(y_positions)
for k = 1:length(z_positions)
% Print current position
fprintf(‘Current position: X = %.2f cm, Y = %.2f cm, Z = %.2f cmn’, x_positions(i), y_positions(j), z_positions(k));
% Wait for user to press Enter before taking measurements
input(‘Move needle to current position and press Enter’);
% Initialize arrays to store multiple measurements
magnetic_X = zeros(num_measurements, 1);
magnetic_Y = zeros(num_measurements, 1);
magnetic_Z = zeros(num_measurements, 1);
% Take multiple measurements
for m = 1:num_measurements
% Measure magnetic field at current position
line = fgets(s);
% Check if data contains ‘X:’, ‘Y:’, and ‘Z:’ labels
if contains(line, ‘X:’) && contains(line, ‘Y:’) && contains(line, ‘Z:’)
magnetic = sscanf(line, ‘X:%f, Y:%f, Z:%f’);
% Check if magnetic has 3 elements
if length(magnetic) == 3
% Store magnetic fields in arrays
magnetic_X(m) = magnetic(1);
magnetic_Y(m) = magnetic(2);
magnetic_Z(m) = magnetic(3);
else
fprintf(‘Unexpected data format: %sn’, line);
end
else
fprintf(‘Unexpected data format: %sn’, line);
end
end
% Average the measurements and store in Bx, By, Bz
Bx(j, i, k) = mean(magnetic_X);
By(j, i, k) = mean(magnetic_Y);
Bz(j, i, k) = mean(magnetic_Z);
end
end
end
% Close serial connection
fclose(s);
% Create a 3D grid for interpolation
[X, Y, Z] = meshgrid(x_positions, y_positions, z_positions);
% Flatten and concatenate the grid coordinates
X_flat = X(:);
Y_flat = Y(:);
Z_flat = Z(:);
% Flatten and concatenate the magnetic field measurements
Bx_flat = Bx(:);
By_flat = By(:);
Bz_flat = Bz(:);
% Combine the magnetic field measurements into a matrix
B_flat = [Bx_flat, By_flat, Bz_flat];
% Train three SVM models
mdl_x = fitrsvm(B_flat, X_flat);
mdl_y = fitrsvm(B_flat, Y_flat);
mdl_z = fitrsvm(B_flat, Z_flat);
% Save to a .mat file
save(‘C:\Users\calibration_data.mat’, ‘x_positions’, ‘y_positions’, ‘z_positions’, ‘Bx’, ‘By’, ‘Bz’, ‘mdl_x’, ‘mdl_y’, ‘mdl_z’); Hey everyone,
I am currently using an Arduino Uno, a permanent magnet and a magnetometer to get the x, y and z coordinates of a metal object within a small rectangular box of known size. The magnetometer and permanent magnet are separated by 5cm, and the metal object moves between them (with the theory being that the metal object blocks the magnetic field from the permanent magnet, causing the readings measured by the magnetometer to change). To prove the concept, I used Matlab to take the magnetic field strength readings (which are output as x, y and z readings) at known distances, and create a calibration curve, in which I derived the equation (I only moved the metal object in one plane). This worked great, as long as the object is along the exact path I calibrated it for.
The problem is that the metal object can move anywhere within the box, and for example, movement only in the x plane also causes change in the y and z planes magnetic field readings. This causes the distance measurements to be wrong, unless the object follows the exact path it was calibrated for. So now I have moved to calibrating the position and magnetic field data in 3D, and this is where I am stuck. I am currently measuring the magnetic field data at different positions in the 3D plane, and storing this as a .mat file for another seperate code to use in real-time to find the position. The issue is that the readings are nowhere near accurate or even representative of distance.
I appreciate any help/suggestions. Cheers.
Calibration Code
% Initialize 3D grid of positions
x_positions = 0:2.5:5; % X Positions from 0cm to 5cm in steps of 2.5cm
y_positions = 0:2.5:7.5; % Y Positions from 0cm to 7.5cm in steps of 2.5cm
z_positions = 0:2.5:5; % Z Positions from 0cm to 10cm in steps of 2.5cm
% Note increment steps can be decreased, but only once the code is working
% accurately.
% Initialize 3D arrays for magnetic field measurements
Bx = zeros(length(y_positions), length(x_positions), length(z_positions));
By = zeros(length(y_positions), length(x_positions), length(z_positions));
Bz = zeros(length(y_positions), length(x_positions), length(z_positions));
% Set up serial connection
s = serial(‘COM4’);
set(s,’BaudRate’,115200);
s.InputBufferSize = 4096; % Increase input buffer size
fopen(s);
% Number of measurements to average
num_measurements = 100;
% Loop over all positions in the grid
for i = 1:length(x_positions)
for j = 1:length(y_positions)
for k = 1:length(z_positions)
% Print current position
fprintf(‘Current position: X = %.2f cm, Y = %.2f cm, Z = %.2f cmn’, x_positions(i), y_positions(j), z_positions(k));
% Wait for user to press Enter before taking measurements
input(‘Move needle to current position and press Enter’);
% Initialize arrays to store multiple measurements
magnetic_X = zeros(num_measurements, 1);
magnetic_Y = zeros(num_measurements, 1);
magnetic_Z = zeros(num_measurements, 1);
% Take multiple measurements
for m = 1:num_measurements
% Measure magnetic field at current position
line = fgets(s);
% Check if data contains ‘X:’, ‘Y:’, and ‘Z:’ labels
if contains(line, ‘X:’) && contains(line, ‘Y:’) && contains(line, ‘Z:’)
magnetic = sscanf(line, ‘X:%f, Y:%f, Z:%f’);
% Check if magnetic has 3 elements
if length(magnetic) == 3
% Store magnetic fields in arrays
magnetic_X(m) = magnetic(1);
magnetic_Y(m) = magnetic(2);
magnetic_Z(m) = magnetic(3);
else
fprintf(‘Unexpected data format: %sn’, line);
end
else
fprintf(‘Unexpected data format: %sn’, line);
end
end
% Average the measurements and store in Bx, By, Bz
Bx(j, i, k) = mean(magnetic_X);
By(j, i, k) = mean(magnetic_Y);
Bz(j, i, k) = mean(magnetic_Z);
end
end
end
% Close serial connection
fclose(s);
% Create a 3D grid for interpolation
[X, Y, Z] = meshgrid(x_positions, y_positions, z_positions);
% Flatten and concatenate the grid coordinates
X_flat = X(:);
Y_flat = Y(:);
Z_flat = Z(:);
% Flatten and concatenate the magnetic field measurements
Bx_flat = Bx(:);
By_flat = By(:);
Bz_flat = Bz(:);
% Combine the magnetic field measurements into a matrix
B_flat = [Bx_flat, By_flat, Bz_flat];
% Train three SVM models
mdl_x = fitrsvm(B_flat, X_flat);
mdl_y = fitrsvm(B_flat, Y_flat);
mdl_z = fitrsvm(B_flat, Z_flat);
% Save to a .mat file
save(‘C:\Users\calibration_data.mat’, ‘x_positions’, ‘y_positions’, ‘z_positions’, ‘Bx’, ‘By’, ‘Bz’, ‘mdl_x’, ‘mdl_y’, ‘mdl_z’); signal processing, 3d, machine learning, arduino, magnetometer MATLAB Answers — New Questions
Find Geiger counter CPM
I am trying to find the counts per minute of a geiger counter signal.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds)I am trying to find the counts per minute of a geiger counter signal.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds) I am trying to find the counts per minute of a geiger counter signal.
I managed to get the signal in a digital/binary form shown below:
I want to figure out how many pulses there are in a given timefram (1-3 seconds) simulink MATLAB Answers — New Questions
I need a help to plots pressure vs. Temp at equilibrium from the attached paper and in the same graph another plot using Peng Robinson model.
plot (p, T)
# in the same figure, plot using the model from the paper for P and T and compare it with Peng Robinson model. at equilibriumplot (p, T)
# in the same figure, plot using the model from the paper for P and T and compare it with Peng Robinson model. at equilibrium plot (p, T)
# in the same figure, plot using the model from the paper for P and T and compare it with Peng Robinson model. at equilibrium torsten MATLAB Answers — New Questions
Saving a Script from another script
Hello – I am using an input script to run a main simulation file on a computing cluster. For this, I need to change one or two parameters in the input script before uploading it and running it again. This requires me to manually generate hundreds of input files. Is there a way to write a third script that changes 1-2 lines of code in the input script and then saves it as a new file?
I have attached my code – I need to change the diameter and concentration parameters and then resave each file as of now but it’s quite slow as you can imagine…
% OPTIONS FOR RUN
main = 1;
scatter = 0;
eff_path = 0;
tic
load ‘Si_n_complex’ %loads complex Si refractive index data (lambda = 250-1000 nm)
global lambda diameter NW_conc bound_x bound_y bound_z n0 n1_all N_photon N_steps
n0=1.33; %Refractive index of surrounnding medium
n1_all=complex(Si_n(2,:),Si_k(2,:)); %Complex refractive index of dielectric
NW_num = 1e8; %NWs per mL
NW_conc = NW_num/1000; %putting conc into mm^-3 for script
diameter = 200;
bound_x = [0 10]; % sets -/+ x boundaries
bound_y = [-5 5]; % sets -/+ y boundaries
bound_z = [-22.5 22.5]; % sets -/+ z boundaries
if main == 1
lambda_all = [400e-9:1e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all];
writematrix(Q,file_name)
elseif scatter == 1
lambda = [655e-9];
N_photon = 1000000; %number of photons to walk
N_steps = 200; % maximum number of steps in walk
MC_main_v17
file_name = mfilename;
Q1 = [transpose(side_exit_position_x),transpose(side_exit_position_y),];
Q2 = [transpose(back_exit_position_x),transpose(back_exit_position_y)];
Q3 = [transpose(trans_exit_position_x),transpose(trans_exit_position_y)];
writematrix(Q1,file_name+"_side");
writematrix(Q2,file_name+"_back");
writematrix(Q3,file_name+"_trans");
elseif eff_path == 1
lambda_all = [400e-9:10e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
eff_path_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
eff_path_all(qq) = mean(eff_path);
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all,eff_path_all];
writematrix(Q,file_name)
else
error(‘Run options not specified’)
end
tocHello – I am using an input script to run a main simulation file on a computing cluster. For this, I need to change one or two parameters in the input script before uploading it and running it again. This requires me to manually generate hundreds of input files. Is there a way to write a third script that changes 1-2 lines of code in the input script and then saves it as a new file?
I have attached my code – I need to change the diameter and concentration parameters and then resave each file as of now but it’s quite slow as you can imagine…
% OPTIONS FOR RUN
main = 1;
scatter = 0;
eff_path = 0;
tic
load ‘Si_n_complex’ %loads complex Si refractive index data (lambda = 250-1000 nm)
global lambda diameter NW_conc bound_x bound_y bound_z n0 n1_all N_photon N_steps
n0=1.33; %Refractive index of surrounnding medium
n1_all=complex(Si_n(2,:),Si_k(2,:)); %Complex refractive index of dielectric
NW_num = 1e8; %NWs per mL
NW_conc = NW_num/1000; %putting conc into mm^-3 for script
diameter = 200;
bound_x = [0 10]; % sets -/+ x boundaries
bound_y = [-5 5]; % sets -/+ y boundaries
bound_z = [-22.5 22.5]; % sets -/+ z boundaries
if main == 1
lambda_all = [400e-9:1e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all];
writematrix(Q,file_name)
elseif scatter == 1
lambda = [655e-9];
N_photon = 1000000; %number of photons to walk
N_steps = 200; % maximum number of steps in walk
MC_main_v17
file_name = mfilename;
Q1 = [transpose(side_exit_position_x),transpose(side_exit_position_y),];
Q2 = [transpose(back_exit_position_x),transpose(back_exit_position_y)];
Q3 = [transpose(trans_exit_position_x),transpose(trans_exit_position_y)];
writematrix(Q1,file_name+"_side");
writematrix(Q2,file_name+"_back");
writematrix(Q3,file_name+"_trans");
elseif eff_path == 1
lambda_all = [400e-9:10e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
eff_path_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
eff_path_all(qq) = mean(eff_path);
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all,eff_path_all];
writematrix(Q,file_name)
else
error(‘Run options not specified’)
end
toc Hello – I am using an input script to run a main simulation file on a computing cluster. For this, I need to change one or two parameters in the input script before uploading it and running it again. This requires me to manually generate hundreds of input files. Is there a way to write a third script that changes 1-2 lines of code in the input script and then saves it as a new file?
I have attached my code – I need to change the diameter and concentration parameters and then resave each file as of now but it’s quite slow as you can imagine…
% OPTIONS FOR RUN
main = 1;
scatter = 0;
eff_path = 0;
tic
load ‘Si_n_complex’ %loads complex Si refractive index data (lambda = 250-1000 nm)
global lambda diameter NW_conc bound_x bound_y bound_z n0 n1_all N_photon N_steps
n0=1.33; %Refractive index of surrounnding medium
n1_all=complex(Si_n(2,:),Si_k(2,:)); %Complex refractive index of dielectric
NW_num = 1e8; %NWs per mL
NW_conc = NW_num/1000; %putting conc into mm^-3 for script
diameter = 200;
bound_x = [0 10]; % sets -/+ x boundaries
bound_y = [-5 5]; % sets -/+ y boundaries
bound_z = [-22.5 22.5]; % sets -/+ z boundaries
if main == 1
lambda_all = [400e-9:1e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all];
writematrix(Q,file_name)
elseif scatter == 1
lambda = [655e-9];
N_photon = 1000000; %number of photons to walk
N_steps = 200; % maximum number of steps in walk
MC_main_v17
file_name = mfilename;
Q1 = [transpose(side_exit_position_x),transpose(side_exit_position_y),];
Q2 = [transpose(back_exit_position_x),transpose(back_exit_position_y)];
Q3 = [transpose(trans_exit_position_x),transpose(trans_exit_position_y)];
writematrix(Q1,file_name+"_side");
writematrix(Q2,file_name+"_back");
writematrix(Q3,file_name+"_trans");
elseif eff_path == 1
lambda_all = [400e-9:10e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
eff_path_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
eff_path_all(qq) = mean(eff_path);
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all,eff_path_all];
writematrix(Q,file_name)
else
error(‘Run options not specified’)
end
toc how to read in a data file? MATLAB Answers — New Questions
Saving a Script from another script
Hello – I am using an input script to run a main simulation file on a computing cluster. For this, I need to change one or two parameters in the input script before uploading it and running it again. This requires me to manually generate hundreds of input files. Is there a way to write a third script that changes 1-2 lines of code in the input script and then saves it as a new file?
I have attached my code – I need to change the diameter and concentration parameters and then resave each file as of now but it’s quite slow as you can imagine…
% OPTIONS FOR RUN
main = 1;
scatter = 0;
eff_path = 0;
tic
load ‘Si_n_complex’ %loads complex Si refractive index data (lambda = 250-1000 nm)
global lambda diameter NW_conc bound_x bound_y bound_z n0 n1_all N_photon N_steps
n0=1.33; %Refractive index of surrounnding medium
n1_all=complex(Si_n(2,:),Si_k(2,:)); %Complex refractive index of dielectric
NW_num = 1e8; %NWs per mL
NW_conc = NW_num/1000; %putting conc into mm^-3 for script
diameter = 200;
bound_x = [0 10]; % sets -/+ x boundaries
bound_y = [-5 5]; % sets -/+ y boundaries
bound_z = [-22.5 22.5]; % sets -/+ z boundaries
if main == 1
lambda_all = [400e-9:1e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all];
writematrix(Q,file_name)
elseif scatter == 1
lambda = [655e-9];
N_photon = 1000000; %number of photons to walk
N_steps = 200; % maximum number of steps in walk
MC_main_v17
file_name = mfilename;
Q1 = [transpose(side_exit_position_x),transpose(side_exit_position_y),];
Q2 = [transpose(back_exit_position_x),transpose(back_exit_position_y)];
Q3 = [transpose(trans_exit_position_x),transpose(trans_exit_position_y)];
writematrix(Q1,file_name+"_side");
writematrix(Q2,file_name+"_back");
writematrix(Q3,file_name+"_trans");
elseif eff_path == 1
lambda_all = [400e-9:10e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
eff_path_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
eff_path_all(qq) = mean(eff_path);
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all,eff_path_all];
writematrix(Q,file_name)
else
error(‘Run options not specified’)
end
tocHello – I am using an input script to run a main simulation file on a computing cluster. For this, I need to change one or two parameters in the input script before uploading it and running it again. This requires me to manually generate hundreds of input files. Is there a way to write a third script that changes 1-2 lines of code in the input script and then saves it as a new file?
I have attached my code – I need to change the diameter and concentration parameters and then resave each file as of now but it’s quite slow as you can imagine…
% OPTIONS FOR RUN
main = 1;
scatter = 0;
eff_path = 0;
tic
load ‘Si_n_complex’ %loads complex Si refractive index data (lambda = 250-1000 nm)
global lambda diameter NW_conc bound_x bound_y bound_z n0 n1_all N_photon N_steps
n0=1.33; %Refractive index of surrounnding medium
n1_all=complex(Si_n(2,:),Si_k(2,:)); %Complex refractive index of dielectric
NW_num = 1e8; %NWs per mL
NW_conc = NW_num/1000; %putting conc into mm^-3 for script
diameter = 200;
bound_x = [0 10]; % sets -/+ x boundaries
bound_y = [-5 5]; % sets -/+ y boundaries
bound_z = [-22.5 22.5]; % sets -/+ z boundaries
if main == 1
lambda_all = [400e-9:1e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all];
writematrix(Q,file_name)
elseif scatter == 1
lambda = [655e-9];
N_photon = 1000000; %number of photons to walk
N_steps = 200; % maximum number of steps in walk
MC_main_v17
file_name = mfilename;
Q1 = [transpose(side_exit_position_x),transpose(side_exit_position_y),];
Q2 = [transpose(back_exit_position_x),transpose(back_exit_position_y)];
Q3 = [transpose(trans_exit_position_x),transpose(trans_exit_position_y)];
writematrix(Q1,file_name+"_side");
writematrix(Q2,file_name+"_back");
writematrix(Q3,file_name+"_trans");
elseif eff_path == 1
lambda_all = [400e-9:10e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
eff_path_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
eff_path_all(qq) = mean(eff_path);
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all,eff_path_all];
writematrix(Q,file_name)
else
error(‘Run options not specified’)
end
toc Hello – I am using an input script to run a main simulation file on a computing cluster. For this, I need to change one or two parameters in the input script before uploading it and running it again. This requires me to manually generate hundreds of input files. Is there a way to write a third script that changes 1-2 lines of code in the input script and then saves it as a new file?
I have attached my code – I need to change the diameter and concentration parameters and then resave each file as of now but it’s quite slow as you can imagine…
% OPTIONS FOR RUN
main = 1;
scatter = 0;
eff_path = 0;
tic
load ‘Si_n_complex’ %loads complex Si refractive index data (lambda = 250-1000 nm)
global lambda diameter NW_conc bound_x bound_y bound_z n0 n1_all N_photon N_steps
n0=1.33; %Refractive index of surrounnding medium
n1_all=complex(Si_n(2,:),Si_k(2,:)); %Complex refractive index of dielectric
NW_num = 1e8; %NWs per mL
NW_conc = NW_num/1000; %putting conc into mm^-3 for script
diameter = 200;
bound_x = [0 10]; % sets -/+ x boundaries
bound_y = [-5 5]; % sets -/+ y boundaries
bound_z = [-22.5 22.5]; % sets -/+ z boundaries
if main == 1
lambda_all = [400e-9:1e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all];
writematrix(Q,file_name)
elseif scatter == 1
lambda = [655e-9];
N_photon = 1000000; %number of photons to walk
N_steps = 200; % maximum number of steps in walk
MC_main_v17
file_name = mfilename;
Q1 = [transpose(side_exit_position_x),transpose(side_exit_position_y),];
Q2 = [transpose(back_exit_position_x),transpose(back_exit_position_y)];
Q3 = [transpose(trans_exit_position_x),transpose(trans_exit_position_y)];
writematrix(Q1,file_name+"_side");
writematrix(Q2,file_name+"_back");
writematrix(Q3,file_name+"_trans");
elseif eff_path == 1
lambda_all = [400e-9:10e-9:1200e-9];
N_photon_all = zeros(length(lambda_all),1);
counter_abs_all = zeros(length(lambda_all),1);
counter_side_all = zeros(length(lambda_all),1);
counter_back_all = zeros(length(lambda_all),1);
counter_trans_all = zeros(length(lambda_all),1);
eff_path_all = zeros(length(lambda_all),1);
N_photon = 1000; %number of photons to walk
N_steps = 10000; % maximum number of steps in walk
for qq = 1:length(lambda_all)
try
lambda = lambda_all(qq);
MC_main_v17
N_photon_all(qq) = N_photon;
counter_abs_all(qq) = counter_abs;
counter_back_all(qq) = counter_back;
counter_side_all(qq) = counter_side_exit;
counter_trans_all(qq) = counter_exit;
eff_path_all(qq) = mean(eff_path);
catch
break
end
end
file_name = mfilename + ".csv";
Q = [transpose(lambda_all),N_photon_all,counter_abs_all,counter_side_all,counter_back_all,counter_trans_all,eff_path_all];
writematrix(Q,file_name)
else
error(‘Run options not specified’)
end
toc how to read in a data file? MATLAB Answers — New Questions
I need to know a command to find errors in data file
I have a program which analyzes ticket sales and I have everything but one of the requirements is to find the errors on the data file (the data file is "WDWtixdata1.txt")(The errors are numbers grearest than 10 like 11,12,13, etc and numbers lower than 1 like 0,-1, etc.
Which command can I use to find the errors? The one I used tells me hat theres 8 errors but the right answer is 101 so I am doing somthing wrong.
I would appreciate the help.
% This Program analyzes ticket sales data for an event at Walt Disney World
% Load data from the file
data = load(‘WDWtixdata1.txt’);
% Filter out errors (tickets greater than 10 days or less than 1 day)
valid_data = data(data >= 1 & data <= 10);
% Define ticket prices
one_day_price = 122.00;
two_to_three_day_price = 101.67;
four_to_seven_day_price = 67.50;
eight_to_ten_day_price = 48.34;
% Calculate total number of tickets sold
total_tickets_sold = numel(valid_data);
% Calculate tickets sold in each category
one_day_tickets = sum(valid_data == 1);
two_to_three_day_tickets = sum(valid_data >= 2 & valid_data <= 3);
four_to_seven_day_tickets = sum(valid_data >= 4 & valid_data <= 7);
eight_to_ten_day_tickets = sum(valid_data >= 8 & valid_data <= 10);
% Calculate percentages
one_day_percentage = (one_day_tickets / total_tickets_sold) * 100;
two_to_three_day_percentage = (two_to_three_day_tickets / total_tickets_sold) * 100;
four_to_seven_day_percentage = (four_to_seven_day_tickets / total_tickets_sold) * 100;
eight_to_ten_day_percentage = (eight_to_ten_day_tickets / total_tickets_sold) * 100;
% Calculate total revenue
total_revenue = (one_day_tickets * one_day_price) + (two_to_three_day_tickets * two_to_three_day_price * valid_data(1)) + (four_to_seven_day_tickets * four_to_seven_day_price * valid_data(1)) + (eight_to_ten_day_tickets * eight_to_ten_day_price * valid_data(1));
% Identify errors
total_errors = (load(‘WDWtixdata1.txt’) <= 1 & data >= 10);
% Display results
disp([‘WDW sold a total of ‘ num2str(total_tickets_sold) ‘ tickets.’]);
disp([‘WDW sold ‘ num2str(one_day_tickets) ‘ one-day tickets, which is ‘ num2str(one_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(two_to_three_day_tickets) ‘ two-to-three-day tickets, which is ‘ num2str(two_to_three_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(four_to_seven_day_tickets) ‘ four-to-seven-day tickets, which is ‘ num2str(four_to_seven_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(eight_to_ten_day_tickets) ‘ eight-to-ten-day tickets, which is ‘ num2str(eight_to_ten_day_percentage) ‘% of all tickets sold.’]);
disp([‘Walt Disney World took in a total of $’ num2str(total_revenue)]);
disp([‘The data file WDWtixdata1.txt had a total of ‘ numel(total_errors) ‘ errors.’]);I have a program which analyzes ticket sales and I have everything but one of the requirements is to find the errors on the data file (the data file is "WDWtixdata1.txt")(The errors are numbers grearest than 10 like 11,12,13, etc and numbers lower than 1 like 0,-1, etc.
Which command can I use to find the errors? The one I used tells me hat theres 8 errors but the right answer is 101 so I am doing somthing wrong.
I would appreciate the help.
% This Program analyzes ticket sales data for an event at Walt Disney World
% Load data from the file
data = load(‘WDWtixdata1.txt’);
% Filter out errors (tickets greater than 10 days or less than 1 day)
valid_data = data(data >= 1 & data <= 10);
% Define ticket prices
one_day_price = 122.00;
two_to_three_day_price = 101.67;
four_to_seven_day_price = 67.50;
eight_to_ten_day_price = 48.34;
% Calculate total number of tickets sold
total_tickets_sold = numel(valid_data);
% Calculate tickets sold in each category
one_day_tickets = sum(valid_data == 1);
two_to_three_day_tickets = sum(valid_data >= 2 & valid_data <= 3);
four_to_seven_day_tickets = sum(valid_data >= 4 & valid_data <= 7);
eight_to_ten_day_tickets = sum(valid_data >= 8 & valid_data <= 10);
% Calculate percentages
one_day_percentage = (one_day_tickets / total_tickets_sold) * 100;
two_to_three_day_percentage = (two_to_three_day_tickets / total_tickets_sold) * 100;
four_to_seven_day_percentage = (four_to_seven_day_tickets / total_tickets_sold) * 100;
eight_to_ten_day_percentage = (eight_to_ten_day_tickets / total_tickets_sold) * 100;
% Calculate total revenue
total_revenue = (one_day_tickets * one_day_price) + (two_to_three_day_tickets * two_to_three_day_price * valid_data(1)) + (four_to_seven_day_tickets * four_to_seven_day_price * valid_data(1)) + (eight_to_ten_day_tickets * eight_to_ten_day_price * valid_data(1));
% Identify errors
total_errors = (load(‘WDWtixdata1.txt’) <= 1 & data >= 10);
% Display results
disp([‘WDW sold a total of ‘ num2str(total_tickets_sold) ‘ tickets.’]);
disp([‘WDW sold ‘ num2str(one_day_tickets) ‘ one-day tickets, which is ‘ num2str(one_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(two_to_three_day_tickets) ‘ two-to-three-day tickets, which is ‘ num2str(two_to_three_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(four_to_seven_day_tickets) ‘ four-to-seven-day tickets, which is ‘ num2str(four_to_seven_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(eight_to_ten_day_tickets) ‘ eight-to-ten-day tickets, which is ‘ num2str(eight_to_ten_day_percentage) ‘% of all tickets sold.’]);
disp([‘Walt Disney World took in a total of $’ num2str(total_revenue)]);
disp([‘The data file WDWtixdata1.txt had a total of ‘ numel(total_errors) ‘ errors.’]); I have a program which analyzes ticket sales and I have everything but one of the requirements is to find the errors on the data file (the data file is "WDWtixdata1.txt")(The errors are numbers grearest than 10 like 11,12,13, etc and numbers lower than 1 like 0,-1, etc.
Which command can I use to find the errors? The one I used tells me hat theres 8 errors but the right answer is 101 so I am doing somthing wrong.
I would appreciate the help.
% This Program analyzes ticket sales data for an event at Walt Disney World
% Load data from the file
data = load(‘WDWtixdata1.txt’);
% Filter out errors (tickets greater than 10 days or less than 1 day)
valid_data = data(data >= 1 & data <= 10);
% Define ticket prices
one_day_price = 122.00;
two_to_three_day_price = 101.67;
four_to_seven_day_price = 67.50;
eight_to_ten_day_price = 48.34;
% Calculate total number of tickets sold
total_tickets_sold = numel(valid_data);
% Calculate tickets sold in each category
one_day_tickets = sum(valid_data == 1);
two_to_three_day_tickets = sum(valid_data >= 2 & valid_data <= 3);
four_to_seven_day_tickets = sum(valid_data >= 4 & valid_data <= 7);
eight_to_ten_day_tickets = sum(valid_data >= 8 & valid_data <= 10);
% Calculate percentages
one_day_percentage = (one_day_tickets / total_tickets_sold) * 100;
two_to_three_day_percentage = (two_to_three_day_tickets / total_tickets_sold) * 100;
four_to_seven_day_percentage = (four_to_seven_day_tickets / total_tickets_sold) * 100;
eight_to_ten_day_percentage = (eight_to_ten_day_tickets / total_tickets_sold) * 100;
% Calculate total revenue
total_revenue = (one_day_tickets * one_day_price) + (two_to_three_day_tickets * two_to_three_day_price * valid_data(1)) + (four_to_seven_day_tickets * four_to_seven_day_price * valid_data(1)) + (eight_to_ten_day_tickets * eight_to_ten_day_price * valid_data(1));
% Identify errors
total_errors = (load(‘WDWtixdata1.txt’) <= 1 & data >= 10);
% Display results
disp([‘WDW sold a total of ‘ num2str(total_tickets_sold) ‘ tickets.’]);
disp([‘WDW sold ‘ num2str(one_day_tickets) ‘ one-day tickets, which is ‘ num2str(one_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(two_to_three_day_tickets) ‘ two-to-three-day tickets, which is ‘ num2str(two_to_three_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(four_to_seven_day_tickets) ‘ four-to-seven-day tickets, which is ‘ num2str(four_to_seven_day_percentage) ‘% of all tickets sold.’]);
disp([‘WDW sold ‘ num2str(eight_to_ten_day_tickets) ‘ eight-to-ten-day tickets, which is ‘ num2str(eight_to_ten_day_percentage) ‘% of all tickets sold.’]);
disp([‘Walt Disney World took in a total of $’ num2str(total_revenue)]);
disp([‘The data file WDWtixdata1.txt had a total of ‘ numel(total_errors) ‘ errors.’]); finderrors, findespecificnumbersindatafile MATLAB Answers — New Questions
i have ascii data converted into columns and rows seperatby str2num command now i want to add all rows in orderly in one cell by using for loop can you give me ans
Post Content Post Content addition of cells MATLAB Answers — New Questions
Error : Unable to use a value of type optim.problemdef.OptimizationVariable as an index.
Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance!Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance! Hello !
I am working on a problem-based optimization task where I need to assign 4 subtasks to 4 different nodes. My approach involves defining an optimization variable as a vector with integer elements ranging from 1 to 4, each representing the node assigned to a subtask.
Here’s a snippet of my current setup:
numSubtasks = 4;
numNodes = 4;
taskAssignmentVector = optimvar(‘taskAssignmentVector’, numSubtasks, ‘Type’, ‘integer’, ‘LowerBound’, 1, ‘UpperBound’, numSubtasks);
My goal is to reshape this vector into a 4×4 binary assignment matrix within the optimization framework. Each row of this matrix should correspond to a subtask, and each column to a node, with ‘1’ indicating the assignment.
I attempted to implement this by creating a function to generate the assignment matrix based on the vector, but I’m facing challenges in using the optimization variable as an index, leading to errors.
AssignedMatrix = zeros(numSubtasks, numNodes);
for s = 1:numSubtasks
nodeAssigned = taskAssignmentVector(s); % Node assigned for each subtask
AssignedMatrix(s, nodeAssigned) = 1;
end
Could you please advise on the best approach to reshape this vector into a matrix form within the problem-based optimization framework? I am looking for a way to link the task assignments in the vector with a binary matrix that I can use in my objective function and constraints.
Thank you for your assistance! optimization, solve, error MATLAB Answers — New Questions
how create app design by MATLAB to read file(wav file),plot signal as audacity, calculate fft (spectrum) and plot fft?
I should use the code attached below, but I don’t know how and where to put it in the code view:
clear
clc
close all
% To read wav-file:
[file,path]=uigetfile({‘*.wav;*.mp3’ ‘Recorded Sound Files’;’*.wav’ ‘wave-file’; ‘*.mp3’ ‘MP3-file’},’Select a file’);
filename=[path file]; % This joins the folder name and file name in one variable
[sgnl,Fs]=audioread(filename); % reads data from filename, and returns sampled data y, and a sampling frequency for that data Fs.
figure
plot(sgnl(:,1)) % to plot the signal [there are 2 column because there are 2 channels on Laptop]
sound(sgnl(:,1),Fs) % to play the sound signal
% to create time steps using the recorded signal and Fs
N = size(sgnl,1); % Assuming Column Vectors
t = linspace(0, N, N)/Fs; % Time Vector
figure
plot(t,sgnl)
xlabel(‘time [sec]’)
ylabel(‘Amplitude’)I should use the code attached below, but I don’t know how and where to put it in the code view:
clear
clc
close all
% To read wav-file:
[file,path]=uigetfile({‘*.wav;*.mp3’ ‘Recorded Sound Files’;’*.wav’ ‘wave-file’; ‘*.mp3’ ‘MP3-file’},’Select a file’);
filename=[path file]; % This joins the folder name and file name in one variable
[sgnl,Fs]=audioread(filename); % reads data from filename, and returns sampled data y, and a sampling frequency for that data Fs.
figure
plot(sgnl(:,1)) % to plot the signal [there are 2 column because there are 2 channels on Laptop]
sound(sgnl(:,1),Fs) % to play the sound signal
% to create time steps using the recorded signal and Fs
N = size(sgnl,1); % Assuming Column Vectors
t = linspace(0, N, N)/Fs; % Time Vector
figure
plot(t,sgnl)
xlabel(‘time [sec]’)
ylabel(‘Amplitude’) I should use the code attached below, but I don’t know how and where to put it in the code view:
clear
clc
close all
% To read wav-file:
[file,path]=uigetfile({‘*.wav;*.mp3’ ‘Recorded Sound Files’;’*.wav’ ‘wave-file’; ‘*.mp3’ ‘MP3-file’},’Select a file’);
filename=[path file]; % This joins the folder name and file name in one variable
[sgnl,Fs]=audioread(filename); % reads data from filename, and returns sampled data y, and a sampling frequency for that data Fs.
figure
plot(sgnl(:,1)) % to plot the signal [there are 2 column because there are 2 channels on Laptop]
sound(sgnl(:,1),Fs) % to play the sound signal
% to create time steps using the recorded signal and Fs
N = size(sgnl,1); % Assuming Column Vectors
t = linspace(0, N, N)/Fs; % Time Vector
figure
plot(t,sgnl)
xlabel(‘time [sec]’)
ylabel(‘Amplitude’) app design, mapping of noise pollution, plot, fft, read file(wav file), plot signal as audacity MATLAB Answers — New Questions
how create app design by MATLAB to read file(wav file),plot signal as audacity, calculate fft (spectrum) and plot fft?
I should use the code attached below, but I don’t know how and where to put it in the code view:
clear
clc
close all
% To read wav-file:
[file,path]=uigetfile({‘*.wav;*.mp3’ ‘Recorded Sound Files’;’*.wav’ ‘wave-file’; ‘*.mp3’ ‘MP3-file’},’Select a file’);
filename=[path file]; % This joins the folder name and file name in one variable
[sgnl,Fs]=audioread(filename); % reads data from filename, and returns sampled data y, and a sampling frequency for that data Fs.
figure
plot(sgnl(:,1)) % to plot the signal [there are 2 column because there are 2 channels on Laptop]
sound(sgnl(:,1),Fs) % to play the sound signal
% to create time steps using the recorded signal and Fs
N = size(sgnl,1); % Assuming Column Vectors
t = linspace(0, N, N)/Fs; % Time Vector
figure
plot(t,sgnl)
xlabel(‘time [sec]’)
ylabel(‘Amplitude’)I should use the code attached below, but I don’t know how and where to put it in the code view:
clear
clc
close all
% To read wav-file:
[file,path]=uigetfile({‘*.wav;*.mp3’ ‘Recorded Sound Files’;’*.wav’ ‘wave-file’; ‘*.mp3’ ‘MP3-file’},’Select a file’);
filename=[path file]; % This joins the folder name and file name in one variable
[sgnl,Fs]=audioread(filename); % reads data from filename, and returns sampled data y, and a sampling frequency for that data Fs.
figure
plot(sgnl(:,1)) % to plot the signal [there are 2 column because there are 2 channels on Laptop]
sound(sgnl(:,1),Fs) % to play the sound signal
% to create time steps using the recorded signal and Fs
N = size(sgnl,1); % Assuming Column Vectors
t = linspace(0, N, N)/Fs; % Time Vector
figure
plot(t,sgnl)
xlabel(‘time [sec]’)
ylabel(‘Amplitude’) I should use the code attached below, but I don’t know how and where to put it in the code view:
clear
clc
close all
% To read wav-file:
[file,path]=uigetfile({‘*.wav;*.mp3’ ‘Recorded Sound Files’;’*.wav’ ‘wave-file’; ‘*.mp3’ ‘MP3-file’},’Select a file’);
filename=[path file]; % This joins the folder name and file name in one variable
[sgnl,Fs]=audioread(filename); % reads data from filename, and returns sampled data y, and a sampling frequency for that data Fs.
figure
plot(sgnl(:,1)) % to plot the signal [there are 2 column because there are 2 channels on Laptop]
sound(sgnl(:,1),Fs) % to play the sound signal
% to create time steps using the recorded signal and Fs
N = size(sgnl,1); % Assuming Column Vectors
t = linspace(0, N, N)/Fs; % Time Vector
figure
plot(t,sgnl)
xlabel(‘time [sec]’)
ylabel(‘Amplitude’) app design, mapping of noise pollution, plot, fft, read file(wav file), plot signal as audacity MATLAB Answers — New Questions
how can I view each individual superpixel?
I have performed SLIC algorithm. I want to view each individual pixel and what are the superpixels connected to each other ?
Thank youI have performed SLIC algorithm. I want to view each individual pixel and what are the superpixels connected to each other ?
Thank you I have performed SLIC algorithm. I want to view each individual pixel and what are the superpixels connected to each other ?
Thank you image processing, glcm, gray level co-occurrence matrix MATLAB Answers — New Questions