Tag Archives: matlab
Why my image cannot dramical crop?
Hello. I want to ask. I want to crop my image data with specific area with a specific part of an image. And I want to use auto dynamic cropping method in matlab. I’m using ultrasound data. Why my crop image does not appear on the result? Here’s my codes and I attach with my image:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
mypath = ‘/home/motmot/Documents/test/’;
dinfo = dir(fullfile(mypath,’*.jpg’));
filenames = fullfile({dinfo.folder}, {dinfo.name});
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
[folder, basename, ext] = fileparts(thisfile);
outfile = fullfile(folder, basename + "_crop" + ext);
I = imread(thisfile);
% Get the dimensions of the image. numberOfColorChannels should be = 3.
[rows, columns, numberOfColorChannels] = size(I);
% Display the original color image.
subplot(2, 3, 1);
imshow(I);
axis on;
hp = impixelinfo(); % Show x,y and RGB as you mouse around.
title(‘Original Color Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Take the red channel.
grayImage = I(:, :, 1);
% Erase the first 110 columns to get rid of the holes.
verticalProfile = mean(grayImage, 2);
for col = 1 : 110
grayImage(:, col) = verticalProfile;
end
% Run a texture filter on it.
stdImage = stdfilt(grayImage);
% Display the image.
subplot(2, 3, 2);
imshow(stdImage, []);
axis on;
title(‘Filtered Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Enlarge figure
set(gcf, ‘Units’, ‘Normalized’, ‘Outerposition’, [0.05, 0.1, .9, .80]);
% Let’s compute and display the histogram.
subplot(2, 3, 3);
histogram(stdImage, 500); % 500 bins.
grid on;
title(‘Histogram of Filtered image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
xlabel(‘Gray Level’, ‘FontSize’, fontSize);
ylabel(‘Pixel Count’, ‘FontSize’, fontSize);
% Threshold the image.
binaryImage = stdImage > 5;
% Display the image.
subplot(2, 3, 4);
imshow(binaryImage);
axis on;
title(‘Binary Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% % Get areas of blobs
% labeledImage = bwlabel(binaryImage);
% props = regionprops(labeledImage, ‘Area’);
% allAreas = sort([props.Area])
% subplot(2, 3, 5);
% histogram(allAreas); % Show histogram of blob areas.
% title(‘Blob Areas’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Get rid of small blobs.
binaryImage = bwareafilt(binaryImage, [70, inf]); % Keep only if 70 pixels or larger.
% Display the image.
subplot(2, 3, 5);
imshow(binaryImage);
axis on;
title(‘Cleaned Binary Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Find the bounding box.
[blobRows, blobColumns] = find(binaryImage);
row1 = min(blobRows);
row2 = max(blobRows);
col1 = min(blobColumns);
col2 = max(blobColumns);
% Crop it.
croppedImage = rgbImage(row1:row2, col1:col2, :);
% Display the cropped, enhanced color image.
subplot(2, 3, 6);
imshow(croppedImage);
axis on;
title(‘Cropped Color Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
imwrite(croppedImage, outfile)
endHello. I want to ask. I want to crop my image data with specific area with a specific part of an image. And I want to use auto dynamic cropping method in matlab. I’m using ultrasound data. Why my crop image does not appear on the result? Here’s my codes and I attach with my image:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
mypath = ‘/home/motmot/Documents/test/’;
dinfo = dir(fullfile(mypath,’*.jpg’));
filenames = fullfile({dinfo.folder}, {dinfo.name});
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
[folder, basename, ext] = fileparts(thisfile);
outfile = fullfile(folder, basename + "_crop" + ext);
I = imread(thisfile);
% Get the dimensions of the image. numberOfColorChannels should be = 3.
[rows, columns, numberOfColorChannels] = size(I);
% Display the original color image.
subplot(2, 3, 1);
imshow(I);
axis on;
hp = impixelinfo(); % Show x,y and RGB as you mouse around.
title(‘Original Color Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Take the red channel.
grayImage = I(:, :, 1);
% Erase the first 110 columns to get rid of the holes.
verticalProfile = mean(grayImage, 2);
for col = 1 : 110
grayImage(:, col) = verticalProfile;
end
% Run a texture filter on it.
stdImage = stdfilt(grayImage);
% Display the image.
subplot(2, 3, 2);
imshow(stdImage, []);
axis on;
title(‘Filtered Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Enlarge figure
set(gcf, ‘Units’, ‘Normalized’, ‘Outerposition’, [0.05, 0.1, .9, .80]);
% Let’s compute and display the histogram.
subplot(2, 3, 3);
histogram(stdImage, 500); % 500 bins.
grid on;
title(‘Histogram of Filtered image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
xlabel(‘Gray Level’, ‘FontSize’, fontSize);
ylabel(‘Pixel Count’, ‘FontSize’, fontSize);
% Threshold the image.
binaryImage = stdImage > 5;
% Display the image.
subplot(2, 3, 4);
imshow(binaryImage);
axis on;
title(‘Binary Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% % Get areas of blobs
% labeledImage = bwlabel(binaryImage);
% props = regionprops(labeledImage, ‘Area’);
% allAreas = sort([props.Area])
% subplot(2, 3, 5);
% histogram(allAreas); % Show histogram of blob areas.
% title(‘Blob Areas’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Get rid of small blobs.
binaryImage = bwareafilt(binaryImage, [70, inf]); % Keep only if 70 pixels or larger.
% Display the image.
subplot(2, 3, 5);
imshow(binaryImage);
axis on;
title(‘Cleaned Binary Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Find the bounding box.
[blobRows, blobColumns] = find(binaryImage);
row1 = min(blobRows);
row2 = max(blobRows);
col1 = min(blobColumns);
col2 = max(blobColumns);
% Crop it.
croppedImage = rgbImage(row1:row2, col1:col2, :);
% Display the cropped, enhanced color image.
subplot(2, 3, 6);
imshow(croppedImage);
axis on;
title(‘Cropped Color Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
imwrite(croppedImage, outfile)
end Hello. I want to ask. I want to crop my image data with specific area with a specific part of an image. And I want to use auto dynamic cropping method in matlab. I’m using ultrasound data. Why my crop image does not appear on the result? Here’s my codes and I attach with my image:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;
mypath = ‘/home/motmot/Documents/test/’;
dinfo = dir(fullfile(mypath,’*.jpg’));
filenames = fullfile({dinfo.folder}, {dinfo.name});
nfiles = length(filenames);
for K = 1 : nfiles
thisfile = filenames{K};
[folder, basename, ext] = fileparts(thisfile);
outfile = fullfile(folder, basename + "_crop" + ext);
I = imread(thisfile);
% Get the dimensions of the image. numberOfColorChannels should be = 3.
[rows, columns, numberOfColorChannels] = size(I);
% Display the original color image.
subplot(2, 3, 1);
imshow(I);
axis on;
hp = impixelinfo(); % Show x,y and RGB as you mouse around.
title(‘Original Color Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Take the red channel.
grayImage = I(:, :, 1);
% Erase the first 110 columns to get rid of the holes.
verticalProfile = mean(grayImage, 2);
for col = 1 : 110
grayImage(:, col) = verticalProfile;
end
% Run a texture filter on it.
stdImage = stdfilt(grayImage);
% Display the image.
subplot(2, 3, 2);
imshow(stdImage, []);
axis on;
title(‘Filtered Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Enlarge figure
set(gcf, ‘Units’, ‘Normalized’, ‘Outerposition’, [0.05, 0.1, .9, .80]);
% Let’s compute and display the histogram.
subplot(2, 3, 3);
histogram(stdImage, 500); % 500 bins.
grid on;
title(‘Histogram of Filtered image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
xlabel(‘Gray Level’, ‘FontSize’, fontSize);
ylabel(‘Pixel Count’, ‘FontSize’, fontSize);
% Threshold the image.
binaryImage = stdImage > 5;
% Display the image.
subplot(2, 3, 4);
imshow(binaryImage);
axis on;
title(‘Binary Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% % Get areas of blobs
% labeledImage = bwlabel(binaryImage);
% props = regionprops(labeledImage, ‘Area’);
% allAreas = sort([props.Area])
% subplot(2, 3, 5);
% histogram(allAreas); % Show histogram of blob areas.
% title(‘Blob Areas’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Get rid of small blobs.
binaryImage = bwareafilt(binaryImage, [70, inf]); % Keep only if 70 pixels or larger.
% Display the image.
subplot(2, 3, 5);
imshow(binaryImage);
axis on;
title(‘Cleaned Binary Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
% Find the bounding box.
[blobRows, blobColumns] = find(binaryImage);
row1 = min(blobRows);
row2 = max(blobRows);
col1 = min(blobColumns);
col2 = max(blobColumns);
% Crop it.
croppedImage = rgbImage(row1:row2, col1:col2, :);
% Display the cropped, enhanced color image.
subplot(2, 3, 6);
imshow(croppedImage);
axis on;
title(‘Cropped Color Image’, ‘FontSize’, fontSize, ‘Interpreter’, ‘None’);
imwrite(croppedImage, outfile)
end crop, dynamic MATLAB Answers — New Questions
obtain the Impulse response from a frequency response
Hi everybody,
I need some help to get me started on this one:
I have a transfer function (a frequency response) that is generated by two datasets.
I need to convert this frequency response (FR) to the time domain (I guess by using the ifft function in Matlab) in order to obtain the impulse response (IR) and see how long it is in seconds.
What confuses me is if an impulse (IR) has N samples then the fft would have N/2+1 samples (please correct me if I am wrong). The rest of the samples in the FR are disregarded as they are symmetrical.
Now, if I have the FR I could go back to IR by ifft. But that would give me only N/2+1 samples. I need N for the impulse response. How do I deal with this?
Moreover, how can I determine the sampling frequency (fs) of my FR in order to calculate the duration of the IR in seconds?
My FR expands from 20 to 10000 Hz with a step of 20 Hz. Is it in this case that fs=20?
thank you for your patienceHi everybody,
I need some help to get me started on this one:
I have a transfer function (a frequency response) that is generated by two datasets.
I need to convert this frequency response (FR) to the time domain (I guess by using the ifft function in Matlab) in order to obtain the impulse response (IR) and see how long it is in seconds.
What confuses me is if an impulse (IR) has N samples then the fft would have N/2+1 samples (please correct me if I am wrong). The rest of the samples in the FR are disregarded as they are symmetrical.
Now, if I have the FR I could go back to IR by ifft. But that would give me only N/2+1 samples. I need N for the impulse response. How do I deal with this?
Moreover, how can I determine the sampling frequency (fs) of my FR in order to calculate the duration of the IR in seconds?
My FR expands from 20 to 10000 Hz with a step of 20 Hz. Is it in this case that fs=20?
thank you for your patience Hi everybody,
I need some help to get me started on this one:
I have a transfer function (a frequency response) that is generated by two datasets.
I need to convert this frequency response (FR) to the time domain (I guess by using the ifft function in Matlab) in order to obtain the impulse response (IR) and see how long it is in seconds.
What confuses me is if an impulse (IR) has N samples then the fft would have N/2+1 samples (please correct me if I am wrong). The rest of the samples in the FR are disregarded as they are symmetrical.
Now, if I have the FR I could go back to IR by ifft. But that would give me only N/2+1 samples. I need N for the impulse response. How do I deal with this?
Moreover, how can I determine the sampling frequency (fs) of my FR in order to calculate the duration of the IR in seconds?
My FR expands from 20 to 10000 Hz with a step of 20 Hz. Is it in this case that fs=20?
thank you for your patience impulse response MATLAB Answers — New Questions
Calculating sin and cos functions
Hello, i calculated the value of sin(45) in Matlab, the result was sin(45)=0.8509 and for cosin i got cos(45)= 0.5253. From general mathematics we know that sin(45)=cos(45) then why Matlab is giving different results??Hello, i calculated the value of sin(45) in Matlab, the result was sin(45)=0.8509 and for cosin i got cos(45)= 0.5253. From general mathematics we know that sin(45)=cos(45) then why Matlab is giving different results?? Hello, i calculated the value of sin(45) in Matlab, the result was sin(45)=0.8509 and for cosin i got cos(45)= 0.5253. From general mathematics we know that sin(45)=cos(45) then why Matlab is giving different results?? sine and cosine functions MATLAB Answers — New Questions
Create multi slopes from a profile
Hello there,
Is there a possible way to create some slopes within a profile? My case: I have a profile containing some group of values separated by nans. My intention is how to create slopes for each group. So, since there are some groups in the profile, there will be some slopes which corresponds to each group.
Please find attached mat file for the data.
CheersHello there,
Is there a possible way to create some slopes within a profile? My case: I have a profile containing some group of values separated by nans. My intention is how to create slopes for each group. So, since there are some groups in the profile, there will be some slopes which corresponds to each group.
Please find attached mat file for the data.
Cheers Hello there,
Is there a possible way to create some slopes within a profile? My case: I have a profile containing some group of values separated by nans. My intention is how to create slopes for each group. So, since there are some groups in the profile, there will be some slopes which corresponds to each group.
Please find attached mat file for the data.
Cheers slope, profiles, nan, multi slopes MATLAB Answers — New Questions
Rank value matrix from 3d Matrix
I have a 3d matrix of average global temperatures (0.5 degree lat/long) for 42 years (42×720×1440). For a given year (say year 42) I want to create a new matrix (720 × 1440) that ranks each lat/long pair based on the other 41 years. So if a lat/long pair is warmest, it will have a rank value of 1. If it’s coolest, it will have a rank value of 42. The resulting matrix will be 720 x 1440 matrix of values ranked from 1 to 42 based on the original matrix. Is there a simple way to take a given year from the original matrix to do this without looping?I have a 3d matrix of average global temperatures (0.5 degree lat/long) for 42 years (42×720×1440). For a given year (say year 42) I want to create a new matrix (720 × 1440) that ranks each lat/long pair based on the other 41 years. So if a lat/long pair is warmest, it will have a rank value of 1. If it’s coolest, it will have a rank value of 42. The resulting matrix will be 720 x 1440 matrix of values ranked from 1 to 42 based on the original matrix. Is there a simple way to take a given year from the original matrix to do this without looping? I have a 3d matrix of average global temperatures (0.5 degree lat/long) for 42 years (42×720×1440). For a given year (say year 42) I want to create a new matrix (720 × 1440) that ranks each lat/long pair based on the other 41 years. So if a lat/long pair is warmest, it will have a rank value of 1. If it’s coolest, it will have a rank value of 42. The resulting matrix will be 720 x 1440 matrix of values ranked from 1 to 42 based on the original matrix. Is there a simple way to take a given year from the original matrix to do this without looping? matrix, rank MATLAB Answers — New Questions
Plotting Damped Nonlinear Oscillator
The given system is a damped nonlinear oscillator with a nonlinear resistance, described by the differential equation:
where .
I tried to simulate the above problem for different values of .
As you can see below I have results for , but the code it gives me nothing for different values of . What should I change?
% Define common parameters
v = 1; % Damping coefficient
a = 1; % Linear stiffness coefficient
T = 100; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
m_values = [0.1, 1, 10]; % Different mass values
% Initialize a figure
figure(1);
hold on
% Loop through each mass value
for m = m_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current mass value
plot(t, x, ‘DisplayName’, [‘x, m = ‘, num2str(m)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘y, m = ‘, num2str(m)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Mass Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
v = 1; % Damping coefficient
m = 1; % Mass
T = 50; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
a_values = [0.1, 1, 10]; % Different stiffness values
% Initialize a figure
figure(2);
hold on
% Loop through each stiffness value
for a = a_values
b = (1/20) * a; % Nonlinear stiffness coefficient dependent on a
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current stiffness value
plot(t, x, ‘DisplayName’, [‘x, a = ‘, num2str(a)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘y, a = ‘, num2str(a)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Stiffness Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
m = 1; % Mass, kept constant
a = 1; % Linear stiffness coefficient
T = 100; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
v_values = [0.1, 1, 10]; % Different damping coefficients
% Initialize a figure
figure(3);
hold on
% Loop through each damping coefficient value
for v = v_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current damping value
plot(t, x, ‘DisplayName’, [‘Displacement, v = ‘, num2str(v)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘Velocity, v = ‘, num2str(v)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Damping Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
v = 1; % Damping coefficient
a = 1; % Linear stiffness coefficient
T = 10; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
m = 1; % Mass (constant in this case)
x0_values = [0.1, 1, 10]; % Different initial displacements
y0 = 0; % Initial velocity
% Initialize a figure
figure(4);
hold on
% Loop through each initial displacement value
for x0 = x0_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current initial displacement value
plot(t, x, ‘DisplayName’, [‘Displacement, x_0 = ‘, num2str(x0)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘Velocity, x_0 = ‘, num2str(x0)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Initial Displacements’);
legend(‘show’);
grid on;
hold off;The given system is a damped nonlinear oscillator with a nonlinear resistance, described by the differential equation:
where .
I tried to simulate the above problem for different values of .
As you can see below I have results for , but the code it gives me nothing for different values of . What should I change?
% Define common parameters
v = 1; % Damping coefficient
a = 1; % Linear stiffness coefficient
T = 100; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
m_values = [0.1, 1, 10]; % Different mass values
% Initialize a figure
figure(1);
hold on
% Loop through each mass value
for m = m_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current mass value
plot(t, x, ‘DisplayName’, [‘x, m = ‘, num2str(m)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘y, m = ‘, num2str(m)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Mass Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
v = 1; % Damping coefficient
m = 1; % Mass
T = 50; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
a_values = [0.1, 1, 10]; % Different stiffness values
% Initialize a figure
figure(2);
hold on
% Loop through each stiffness value
for a = a_values
b = (1/20) * a; % Nonlinear stiffness coefficient dependent on a
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current stiffness value
plot(t, x, ‘DisplayName’, [‘x, a = ‘, num2str(a)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘y, a = ‘, num2str(a)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Stiffness Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
m = 1; % Mass, kept constant
a = 1; % Linear stiffness coefficient
T = 100; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
v_values = [0.1, 1, 10]; % Different damping coefficients
% Initialize a figure
figure(3);
hold on
% Loop through each damping coefficient value
for v = v_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current damping value
plot(t, x, ‘DisplayName’, [‘Displacement, v = ‘, num2str(v)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘Velocity, v = ‘, num2str(v)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Damping Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
v = 1; % Damping coefficient
a = 1; % Linear stiffness coefficient
T = 10; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
m = 1; % Mass (constant in this case)
x0_values = [0.1, 1, 10]; % Different initial displacements
y0 = 0; % Initial velocity
% Initialize a figure
figure(4);
hold on
% Loop through each initial displacement value
for x0 = x0_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current initial displacement value
plot(t, x, ‘DisplayName’, [‘Displacement, x_0 = ‘, num2str(x0)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘Velocity, x_0 = ‘, num2str(x0)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Initial Displacements’);
legend(‘show’);
grid on;
hold off; The given system is a damped nonlinear oscillator with a nonlinear resistance, described by the differential equation:
where .
I tried to simulate the above problem for different values of .
As you can see below I have results for , but the code it gives me nothing for different values of . What should I change?
% Define common parameters
v = 1; % Damping coefficient
a = 1; % Linear stiffness coefficient
T = 100; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
m_values = [0.1, 1, 10]; % Different mass values
% Initialize a figure
figure(1);
hold on
% Loop through each mass value
for m = m_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current mass value
plot(t, x, ‘DisplayName’, [‘x, m = ‘, num2str(m)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘y, m = ‘, num2str(m)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Mass Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
v = 1; % Damping coefficient
m = 1; % Mass
T = 50; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
a_values = [0.1, 1, 10]; % Different stiffness values
% Initialize a figure
figure(2);
hold on
% Loop through each stiffness value
for a = a_values
b = (1/20) * a; % Nonlinear stiffness coefficient dependent on a
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current stiffness value
plot(t, x, ‘DisplayName’, [‘x, a = ‘, num2str(a)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘y, a = ‘, num2str(a)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Stiffness Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
m = 1; % Mass, kept constant
a = 1; % Linear stiffness coefficient
T = 100; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
x0 = 0.1; % Initial displacement
y0 = 0; % Initial velocity
v_values = [0.1, 1, 10]; % Different damping coefficients
% Initialize a figure
figure(3);
hold on
% Loop through each damping coefficient value
for v = v_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current damping value
plot(t, x, ‘DisplayName’, [‘Displacement, v = ‘, num2str(v)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘Velocity, v = ‘, num2str(v)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Damping Values’);
legend(‘show’);
grid on;
hold off;
% Define common parameters
v = 1; % Damping coefficient
a = 1; % Linear stiffness coefficient
T = 10; % Total simulation time
dt = 0.01; % Time step
t = 0:dt:T; % Time vector
b = (1/20) * a; % Nonlinear stiffness coefficient
m = 1; % Mass (constant in this case)
x0_values = [0.1, 1, 10]; % Different initial displacements
y0 = 0; % Initial velocity
% Initialize a figure
figure(4);
hold on
% Loop through each initial displacement value
for x0 = x0_values
N = length(t); % Number of time steps
% Initialize arrays for displacement and velocity
x = zeros(1, N);
y = zeros(1, N);
% Set initial conditions
x(1) = x0;
y(1) = y0;
% Simulate the oscillator’s response
for i = 2:N
% Calculate the acceleration and velocity changes using equations of motion
f = -(v/m) * y(i-1) – (a/m) * x(i-1) + (b/m) * x(i-1)^3;
g = y(i-1);
% Update velocity and displacement using Euler’s method
y(i) = y(i-1) + dt * f;
x(i) = x(i-1) + dt * g;
end
% Plot the displacement and velocity for the current initial displacement value
plot(t, x, ‘DisplayName’, [‘Displacement, x_0 = ‘, num2str(x0)]);
plot(t, y, ‘–‘, ‘DisplayName’, [‘Velocity, x_0 = ‘, num2str(x0)]);
end
% Add labels, legend, and grid to the plot
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Damped Nonlinear Oscillator Response for Different Initial Displacements’);
legend(‘show’);
grid on;
hold off; plot, plotting, mathematics, differential equations MATLAB Answers — New Questions
Non-Negative Solution with Integrator in Simulink
When solving ode in Matlab, the ode solver has an option that allows setting the solution non-negative property to be true. For instance –
x = odeset;
x.NonNegative = ones(numStates,1);
Is there an equivalent setting in Simulink? Something that can be adjusted in either model parameters or the [1/s] block?When solving ode in Matlab, the ode solver has an option that allows setting the solution non-negative property to be true. For instance –
x = odeset;
x.NonNegative = ones(numStates,1);
Is there an equivalent setting in Simulink? Something that can be adjusted in either model parameters or the [1/s] block? When solving ode in Matlab, the ode solver has an option that allows setting the solution non-negative property to be true. For instance –
x = odeset;
x.NonNegative = ones(numStates,1);
Is there an equivalent setting in Simulink? Something that can be adjusted in either model parameters or the [1/s] block? ode, odeset MATLAB Answers — New Questions
Fail to start parpool with workers more than 32
I have been attempting to enable a parallel pool with multiple workers on my local machine. The parallel pool launches normally with 12 workers, but I encounter an error when I try to increase the number to 32. Here are some reference details: Local hardware configuration: CPU(s) = 336, available memory = 694GB MATLAB version: matlab2023b The error message for the 32 workers Parallel pool test is as follows:
Error Report: Failed to initialize the interactive session.
Caused by: Error using parallel.internal.pool.AbstractInteractiveClient>iThrowIfBadParallelJobStatus The interactive communicating job failed with no message.
Interactive client bound to URL: tcp://tcpnodelay=localhost:27370/protocol/catapult and port 27370 Session failed to start when creating InteractiveClient. Error: Error using parallel.internal.pool.AbstractInteractiveClient>iThrowWithCause Failed to initialize the interactive session.
Has anyone encountered a similar issue? I believe that local hardware resources should not be a limiting factor for utilizing more workers, but why am I unable to use more than 12 workers?I have been attempting to enable a parallel pool with multiple workers on my local machine. The parallel pool launches normally with 12 workers, but I encounter an error when I try to increase the number to 32. Here are some reference details: Local hardware configuration: CPU(s) = 336, available memory = 694GB MATLAB version: matlab2023b The error message for the 32 workers Parallel pool test is as follows:
Error Report: Failed to initialize the interactive session.
Caused by: Error using parallel.internal.pool.AbstractInteractiveClient>iThrowIfBadParallelJobStatus The interactive communicating job failed with no message.
Interactive client bound to URL: tcp://tcpnodelay=localhost:27370/protocol/catapult and port 27370 Session failed to start when creating InteractiveClient. Error: Error using parallel.internal.pool.AbstractInteractiveClient>iThrowWithCause Failed to initialize the interactive session.
Has anyone encountered a similar issue? I believe that local hardware resources should not be a limiting factor for utilizing more workers, but why am I unable to use more than 12 workers? I have been attempting to enable a parallel pool with multiple workers on my local machine. The parallel pool launches normally with 12 workers, but I encounter an error when I try to increase the number to 32. Here are some reference details: Local hardware configuration: CPU(s) = 336, available memory = 694GB MATLAB version: matlab2023b The error message for the 32 workers Parallel pool test is as follows:
Error Report: Failed to initialize the interactive session.
Caused by: Error using parallel.internal.pool.AbstractInteractiveClient>iThrowIfBadParallelJobStatus The interactive communicating job failed with no message.
Interactive client bound to URL: tcp://tcpnodelay=localhost:27370/protocol/catapult and port 27370 Session failed to start when creating InteractiveClient. Error: Error using parallel.internal.pool.AbstractInteractiveClient>iThrowWithCause Failed to initialize the interactive session.
Has anyone encountered a similar issue? I believe that local hardware resources should not be a limiting factor for utilizing more workers, but why am I unable to use more than 12 workers? parallel computing toolbox, multiple workers, bugs MATLAB Answers — New Questions
How to draw an histogram?
I have two set of data in which i Know the frequencies of both. How do I draw the histograms of the two set of data on the same graph?I have two set of data in which i Know the frequencies of both. How do I draw the histograms of the two set of data on the same graph? I have two set of data in which i Know the frequencies of both. How do I draw the histograms of the two set of data on the same graph? matrix histogram MATLAB Answers — New Questions
Capture reaction time to left mouse click
Hi. I need to capture reaction time to left mouse click (for psychomotor task). A test taker inputs his age and clicks on the red circles. Outputs are reaction time and amount of red circles a test taker clicked on. I have a mistake in my code, but I don’t get where exactly it is. It captures time, but this time is too long. It’s calculated in seconds and supposed to be in the range from 0.1 to 0.5. How to fix it?
figure
axis off
AgeEdit = uicontrol(‘Style’, ‘edit’, ‘Position’, [50 20 100 20]);
Rect = rectangle(‘Position’, [0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’, ‘white’, …
‘ButtonDownFcn’, @(src, event) StartResearch(str2double(get(AgeEdit, ‘String’))));
function StartResearch(Age)
global red_count;
if (Age >= 17)
SignalsAmount = 35;
elseif (Age >= 4 && Age <= 16)
SignalsAmount=15;
else
msgbox ‘Error. Test taker must be at least 4 years old’;
end
CanInteract = 0;
Answers = zeros(1, SignalsAmount);
Signals = randi([1, 4], 1, SignalsAmount);
Rectangle = rectangle(‘Position’, [0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’, ‘white’,’ButtonDownFcn’, …
@(src, event) ReactionCounter);
for i = 1 : SignalsAmount
switch Signals(i)
case 1
Rectangle.FaceColor = ‘red’;
case 2
Rectangle.FaceColor = ‘magenta’;
case 3
Rectangle.FaceColor = ‘[0.8500 0.3250 0.0980]’;
case 4
Rectangle.FaceColor = ‘[0.6350 0.0780 0.1840]’;
end
CanInteract = 1;
random_delay=0.4+(1.5-0.5)*rand;
pause(random_delay);
Rectangle.FaceColor = ‘white’;
CanInteract = 0;
pause(random_delay);
end
ReactionTime = zeros(SignalsAmount, 1);
red_count = 0;
reaction_time = zeros(SignalsAmount, 1);
red_count=0;
%tic; % start of timing
for i = 1:SignalsAmount
if Signals(i) == 1 % if signal is red
tic
red_count = red_count + 1;
reaction_time=rectangle(‘Position’,[0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’,’white’,’ButtonDownFcn’,…
@(scr,event) ReactionTime(str2double(get(‘ButtonDownFcn’))));
reaction_time = toc;
reaction_time=num2str(reaction_time);
end
end
average_reaction_time =sum(reaction_time)/red_count;
delete(Rectangle);
ShowResult;
msgbox(‘Test is over’);
% reaction_time = reaction_time + 0.0001 + 0.9*rand();
function ReactionCounter
if ((CanInteract == 1))
Answers(i) = 1;
CanInteract = 0;
end
end
function [CorrectReactions, IncorrectReactions] = ComputeResults(Answers, Signals)
CorrectReactions = 0;
IncorrectReactions = 0;
NormalizedSignals = NormalizeSignals(Signals);
for j = 1: length(NormalizedSignals)
if(NormalizedSignals(j) == Answers(j))
CorrectReactions = CorrectReactions + 1;
else
IncorrectReactions = IncorrectReactions + 1;
end
end
end
function Signals = NormalizeSignals(Signals)
for n = 1 : length(Signals)
if (Signals(n) == 1)
Signals(n) = 1;
else
Signals(n) = 0;
end
end
endHi. I need to capture reaction time to left mouse click (for psychomotor task). A test taker inputs his age and clicks on the red circles. Outputs are reaction time and amount of red circles a test taker clicked on. I have a mistake in my code, but I don’t get where exactly it is. It captures time, but this time is too long. It’s calculated in seconds and supposed to be in the range from 0.1 to 0.5. How to fix it?
figure
axis off
AgeEdit = uicontrol(‘Style’, ‘edit’, ‘Position’, [50 20 100 20]);
Rect = rectangle(‘Position’, [0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’, ‘white’, …
‘ButtonDownFcn’, @(src, event) StartResearch(str2double(get(AgeEdit, ‘String’))));
function StartResearch(Age)
global red_count;
if (Age >= 17)
SignalsAmount = 35;
elseif (Age >= 4 && Age <= 16)
SignalsAmount=15;
else
msgbox ‘Error. Test taker must be at least 4 years old’;
end
CanInteract = 0;
Answers = zeros(1, SignalsAmount);
Signals = randi([1, 4], 1, SignalsAmount);
Rectangle = rectangle(‘Position’, [0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’, ‘white’,’ButtonDownFcn’, …
@(src, event) ReactionCounter);
for i = 1 : SignalsAmount
switch Signals(i)
case 1
Rectangle.FaceColor = ‘red’;
case 2
Rectangle.FaceColor = ‘magenta’;
case 3
Rectangle.FaceColor = ‘[0.8500 0.3250 0.0980]’;
case 4
Rectangle.FaceColor = ‘[0.6350 0.0780 0.1840]’;
end
CanInteract = 1;
random_delay=0.4+(1.5-0.5)*rand;
pause(random_delay);
Rectangle.FaceColor = ‘white’;
CanInteract = 0;
pause(random_delay);
end
ReactionTime = zeros(SignalsAmount, 1);
red_count = 0;
reaction_time = zeros(SignalsAmount, 1);
red_count=0;
%tic; % start of timing
for i = 1:SignalsAmount
if Signals(i) == 1 % if signal is red
tic
red_count = red_count + 1;
reaction_time=rectangle(‘Position’,[0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’,’white’,’ButtonDownFcn’,…
@(scr,event) ReactionTime(str2double(get(‘ButtonDownFcn’))));
reaction_time = toc;
reaction_time=num2str(reaction_time);
end
end
average_reaction_time =sum(reaction_time)/red_count;
delete(Rectangle);
ShowResult;
msgbox(‘Test is over’);
% reaction_time = reaction_time + 0.0001 + 0.9*rand();
function ReactionCounter
if ((CanInteract == 1))
Answers(i) = 1;
CanInteract = 0;
end
end
function [CorrectReactions, IncorrectReactions] = ComputeResults(Answers, Signals)
CorrectReactions = 0;
IncorrectReactions = 0;
NormalizedSignals = NormalizeSignals(Signals);
for j = 1: length(NormalizedSignals)
if(NormalizedSignals(j) == Answers(j))
CorrectReactions = CorrectReactions + 1;
else
IncorrectReactions = IncorrectReactions + 1;
end
end
end
function Signals = NormalizeSignals(Signals)
for n = 1 : length(Signals)
if (Signals(n) == 1)
Signals(n) = 1;
else
Signals(n) = 0;
end
end
end Hi. I need to capture reaction time to left mouse click (for psychomotor task). A test taker inputs his age and clicks on the red circles. Outputs are reaction time and amount of red circles a test taker clicked on. I have a mistake in my code, but I don’t get where exactly it is. It captures time, but this time is too long. It’s calculated in seconds and supposed to be in the range from 0.1 to 0.5. How to fix it?
figure
axis off
AgeEdit = uicontrol(‘Style’, ‘edit’, ‘Position’, [50 20 100 20]);
Rect = rectangle(‘Position’, [0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’, ‘white’, …
‘ButtonDownFcn’, @(src, event) StartResearch(str2double(get(AgeEdit, ‘String’))));
function StartResearch(Age)
global red_count;
if (Age >= 17)
SignalsAmount = 35;
elseif (Age >= 4 && Age <= 16)
SignalsAmount=15;
else
msgbox ‘Error. Test taker must be at least 4 years old’;
end
CanInteract = 0;
Answers = zeros(1, SignalsAmount);
Signals = randi([1, 4], 1, SignalsAmount);
Rectangle = rectangle(‘Position’, [0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’, ‘white’,’ButtonDownFcn’, …
@(src, event) ReactionCounter);
for i = 1 : SignalsAmount
switch Signals(i)
case 1
Rectangle.FaceColor = ‘red’;
case 2
Rectangle.FaceColor = ‘magenta’;
case 3
Rectangle.FaceColor = ‘[0.8500 0.3250 0.0980]’;
case 4
Rectangle.FaceColor = ‘[0.6350 0.0780 0.1840]’;
end
CanInteract = 1;
random_delay=0.4+(1.5-0.5)*rand;
pause(random_delay);
Rectangle.FaceColor = ‘white’;
CanInteract = 0;
pause(random_delay);
end
ReactionTime = zeros(SignalsAmount, 1);
red_count = 0;
reaction_time = zeros(SignalsAmount, 1);
red_count=0;
%tic; % start of timing
for i = 1:SignalsAmount
if Signals(i) == 1 % if signal is red
tic
red_count = red_count + 1;
reaction_time=rectangle(‘Position’,[0.2 0.2 0.6 0.6], ‘Curvature’, [1 1], ‘FaceColor’,’white’,’ButtonDownFcn’,…
@(scr,event) ReactionTime(str2double(get(‘ButtonDownFcn’))));
reaction_time = toc;
reaction_time=num2str(reaction_time);
end
end
average_reaction_time =sum(reaction_time)/red_count;
delete(Rectangle);
ShowResult;
msgbox(‘Test is over’);
% reaction_time = reaction_time + 0.0001 + 0.9*rand();
function ReactionCounter
if ((CanInteract == 1))
Answers(i) = 1;
CanInteract = 0;
end
end
function [CorrectReactions, IncorrectReactions] = ComputeResults(Answers, Signals)
CorrectReactions = 0;
IncorrectReactions = 0;
NormalizedSignals = NormalizeSignals(Signals);
for j = 1: length(NormalizedSignals)
if(NormalizedSignals(j) == Answers(j))
CorrectReactions = CorrectReactions + 1;
else
IncorrectReactions = IncorrectReactions + 1;
end
end
end
function Signals = NormalizeSignals(Signals)
for n = 1 : length(Signals)
if (Signals(n) == 1)
Signals(n) = 1;
else
Signals(n) = 0;
end
end
end matlab, reaction time MATLAB Answers — New Questions
Input Dimensions for Seq layer of 1D CNN
So I have my X_Train data as 5000×800 . Each column represent 1 second of time and each row represent a time stance which means i have 5000 time instances in each second.. for my Y_Train I have 800×1 labels, (for binary classification) each given label is for 1 second of data. Now the problem is I am contiously getting errors of mismatch in predictions and target 5000(T) and (800T). Each second is a single channel with 5000 instances, so i have to enter it in this format each input 1 channel(1second) with 5000 instances and the label has to match. I am using 1D Conv layer and SequenceInputLayer. Please help me how I can reshape my data or take input dimensions?So I have my X_Train data as 5000×800 . Each column represent 1 second of time and each row represent a time stance which means i have 5000 time instances in each second.. for my Y_Train I have 800×1 labels, (for binary classification) each given label is for 1 second of data. Now the problem is I am contiously getting errors of mismatch in predictions and target 5000(T) and (800T). Each second is a single channel with 5000 instances, so i have to enter it in this format each input 1 channel(1second) with 5000 instances and the label has to match. I am using 1D Conv layer and SequenceInputLayer. Please help me how I can reshape my data or take input dimensions? So I have my X_Train data as 5000×800 . Each column represent 1 second of time and each row represent a time stance which means i have 5000 time instances in each second.. for my Y_Train I have 800×1 labels, (for binary classification) each given label is for 1 second of data. Now the problem is I am contiously getting errors of mismatch in predictions and target 5000(T) and (800T). Each second is a single channel with 5000 instances, so i have to enter it in this format each input 1 channel(1second) with 5000 instances and the label has to match. I am using 1D Conv layer and SequenceInputLayer. Please help me how I can reshape my data or take input dimensions? sequence layer input, 1d cnn MATLAB Answers — New Questions
When integrating acceleration do you need to convert velocity?
I am using data from class that is wave data from a boat.
I am taking the accleration data and demeaning it, filtering it, then using cumtrapz twice to get to displacement. Here is my code for one of the axies:
low_x = low_x – mean(low_x);
[B,A] = butter(8,(5/250));
low_xF = filter(B,A,low_x);
vel_x = (386.09) * cumtrapz(.002,low_xF);
vel_x = vel_x – mean(vel_x);
dis_x = cumtrapz(.002,vel_x);
dis_x = dis_x – mean(dis_x);
My output for displacement is saying my boat is going in the air by 1000 inches with only .04gs. I was wondering if I am doing some type of conversion incorrectly. Any help would be appericated.I am using data from class that is wave data from a boat.
I am taking the accleration data and demeaning it, filtering it, then using cumtrapz twice to get to displacement. Here is my code for one of the axies:
low_x = low_x – mean(low_x);
[B,A] = butter(8,(5/250));
low_xF = filter(B,A,low_x);
vel_x = (386.09) * cumtrapz(.002,low_xF);
vel_x = vel_x – mean(vel_x);
dis_x = cumtrapz(.002,vel_x);
dis_x = dis_x – mean(dis_x);
My output for displacement is saying my boat is going in the air by 1000 inches with only .04gs. I was wondering if I am doing some type of conversion incorrectly. Any help would be appericated. I am using data from class that is wave data from a boat.
I am taking the accleration data and demeaning it, filtering it, then using cumtrapz twice to get to displacement. Here is my code for one of the axies:
low_x = low_x – mean(low_x);
[B,A] = butter(8,(5/250));
low_xF = filter(B,A,low_x);
vel_x = (386.09) * cumtrapz(.002,low_xF);
vel_x = vel_x – mean(vel_x);
dis_x = cumtrapz(.002,vel_x);
dis_x = dis_x – mean(dis_x);
My output for displacement is saying my boat is going in the air by 1000 inches with only .04gs. I was wondering if I am doing some type of conversion incorrectly. Any help would be appericated. convert, cumtrapz MATLAB Answers — New Questions
I am trying to solve a system of three differential equations simultaneously
I am attempting to sovle three differental equations simultaneously. The end goal is to plot the trajectory of (R2, R1) on an x,y plot.
Equation 1: dR1/dt = k1(a1*Rw – R1)
Equation 2: dR2/dt = k2(a2*Rw – R2)
Equation 3: (Xw*dRw)/dt = (Rwin-Rw)*u – (X1(dR1))/dt – (X2(dR2))/dt
ideally I would like to generate code to solve these three equations to where I could define the variables as needed but if this helps,
u=0:1
R1=6
R2=5.5
Rw=-0.5
a1=1.001
a2=0.9998
X1=X2 (these are mole fractions)
K1/K2 = 5 (these are rate constants)
Xw = 0.01 to 0.999 with steps of 0.01, 0.1, 0.2, 0.333, 0.5, 0.666, 0.8, 0.999
Atttached is the original paper for the equations and the way I would like to graph them for reference. The three ways I want to graph the data are "Closed" system, "Buffered" system, and Open System.
Thank you!! If this question belongs somwhere else please let me know.I am attempting to sovle three differental equations simultaneously. The end goal is to plot the trajectory of (R2, R1) on an x,y plot.
Equation 1: dR1/dt = k1(a1*Rw – R1)
Equation 2: dR2/dt = k2(a2*Rw – R2)
Equation 3: (Xw*dRw)/dt = (Rwin-Rw)*u – (X1(dR1))/dt – (X2(dR2))/dt
ideally I would like to generate code to solve these three equations to where I could define the variables as needed but if this helps,
u=0:1
R1=6
R2=5.5
Rw=-0.5
a1=1.001
a2=0.9998
X1=X2 (these are mole fractions)
K1/K2 = 5 (these are rate constants)
Xw = 0.01 to 0.999 with steps of 0.01, 0.1, 0.2, 0.333, 0.5, 0.666, 0.8, 0.999
Atttached is the original paper for the equations and the way I would like to graph them for reference. The three ways I want to graph the data are "Closed" system, "Buffered" system, and Open System.
Thank you!! If this question belongs somwhere else please let me know. I am attempting to sovle three differental equations simultaneously. The end goal is to plot the trajectory of (R2, R1) on an x,y plot.
Equation 1: dR1/dt = k1(a1*Rw – R1)
Equation 2: dR2/dt = k2(a2*Rw – R2)
Equation 3: (Xw*dRw)/dt = (Rwin-Rw)*u – (X1(dR1))/dt – (X2(dR2))/dt
ideally I would like to generate code to solve these three equations to where I could define the variables as needed but if this helps,
u=0:1
R1=6
R2=5.5
Rw=-0.5
a1=1.001
a2=0.9998
X1=X2 (these are mole fractions)
K1/K2 = 5 (these are rate constants)
Xw = 0.01 to 0.999 with steps of 0.01, 0.1, 0.2, 0.333, 0.5, 0.666, 0.8, 0.999
Atttached is the original paper for the equations and the way I would like to graph them for reference. The three ways I want to graph the data are "Closed" system, "Buffered" system, and Open System.
Thank you!! If this question belongs somwhere else please let me know. differential equations MATLAB Answers — New Questions
3D plotting of the bounding box around few boxes
hi,
im trying to plot a bounding box around the final arrangement of boxes but im not getting the ideal output.
this is how the final arrangement of the boxes looks:
expected output:
the output im getting:
this is the flow of my code:
i get the vertices of the 5 boxes in the final arrangement and parse them to a spreadsheet.
clc;
clear;
close all;
%% Problem Definition
model = CreateModel(); % Create Bin Packing Model
CostFunction = @(x) BinPackingCost(x, model); % Objective Function
nVar = model.n * 4; % Each item now has a dimension setting (x, y, z, orientation)
VarSize = [1 nVar]; % Decision Variables Matrix Size
VarMin = 0; % Lower Bound of Decision Variables
VarMax = 1; % Upper Bound of Decision Variables
%% PSO Parameters
MaxIt = 1000; % Maximum Number of Iterations
nPop = 50; % Population Size (Swarm Size)
w = 1; % Inertia Weight
wdamp = 0.99; % Inertia Weight Damping Ratio
c1 = 1.5; % Personal Learning Coefficient
c2 = 2.0; % Global Learning Coefficient
VelMax = 0.1 * (VarMax – VarMin); % Velocity Limits
VelMin = -VelMax;
%% Initialization
particle = repmat(struct(‘Position’, [], ‘Cost’, [], ‘Sol’, [], ‘Velocity’, [], ‘Best’, struct()), nPop, 1);
GlobalBest.Cost = inf;
for i = 1:nPop
% Initialize position with additional orientation indices
particle(i).Position = unifrnd(VarMin, VarMax, VarSize);
% Ensure orientation indices are integers between 1 and 6
particle(i).Position(4:4:end) = randi(6, 1, model.n);
% Velocity and other initialization as before
particle(i).Velocity = zeros(VarSize);
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
particle(i).Best.Sol = particle(i).Sol;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
BestCost = zeros(MaxIt, 1);
%% PSO Main Loop
for it = 1:MaxIt
for i = 1:nPop
particle(i).Velocity = w * particle(i).Velocity …
+ c1 * rand(VarSize) .* (particle(i).Best.Position – particle(i).Position) …
+ c2 * rand(VarSize) .* (GlobalBest.Position – particle(i).Position);
particle(i).Velocity = max(particle(i).Velocity, VelMin);
particle(i).Velocity = min(particle(i).Velocity, VelMax);
particle(i).Position = particle(i).Position + particle(i).Velocity;
particle(i).Position = max(particle(i).Position, VarMin);
particle(i).Position = min(particle(i).Position, VarMax);
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
if particle(i).Cost < particle(i).Best.Cost
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
particle(i).Best.Sol = particle(i).Sol;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
end
BestCost(it) = GlobalBest.Cost;
disp([‘Iteration ‘ num2str(it) ‘: Best Cost = ‘ num2str(BestCost(it))]);
w = w * wdamp;
end
%% Results
figure;
plot(BestCost, ‘LineWidth’, 2);
xlabel(‘Iteration’);
ylabel(‘Best Cost’);
title(‘Convergence of PSO’);
grid on;
%% Bin Configuration Visualization and Vertex Calculation
plotBins(GlobalBest.Sol, model);
vertices = cell(model.n, 1);
for i = GlobalBest.Sol.B{1}
item_dims = model.items(i, :);
orientation = GlobalBest.Position(4*i);
item_pos = GlobalBest.Position(4*i-3:4*i-1);
% Rotate dimensions based on orientation
switch orientation
case 1 % (L, W, H)
rotated_dims = item_dims;
case 2 % (L, H, W)
rotated_dims = [item_dims(1), item_dims(3), item_dims(2)];
case 3 % (W, L, H)
rotated_dims = [item_dims(2), item_dims(1), item_dims(3)];
case 4 % (W, H, L)
rotated_dims = [item_dims(2), item_dims(3), item_dims(1)];
case 5 % (H, L, W)
rotated_dims = [item_dims(3), item_dims(1), item_dims(2)];
case 6 % (H, W, L)
rotated_dims = [item_dims(3), item_dims(2), item_dims(1)];
end
[X, Y, Z] = getBoxVertices(rotated_dims, item_pos);
vertices{i} = [X; Y; Z];
end
%% Exporting Vertex Data to CSV
% Create a cell array to hold the data for the CSV file (This part remains the same)
csv_data = cell(model.n + 1, 1);
csv_data{1} = {‘PresentId’, ‘x1’, ‘y1’, ‘z1’, ‘x2’, ‘y2’, ‘z2’, ‘x3’, ‘y3’, ‘z3’, ‘x4’, ‘y4’, ‘z4’, ‘x5’, ‘y5’, ‘z5’, ‘x6’, ‘y6’, ‘z6’, ‘x7’, ‘y7’, ‘z7’, ‘x8’, ‘y8’, ‘z8’};
% Fill the cell array with vertex data for each item (This part remains the same)
for i = 1:model.n
item_vertices = vertices{i}’; % Transpose to get rows as vertices
csv_data{i+1} = [i, item_vertices(:)’]; % Add item ID and flatten vertex coordinates
end
% Open the file for writing
fileID = fopen(‘vertex_data.csv’,’w’);
% Write header row (remains the same)
fprintf(fileID,’%s,’,csv_data{1}{:});
fprintf(fileID,’n’);
% Write data rows (corrected loop)
for i = 2:size(csv_data,1)
row_data = csv_data{i}; % Get the cell array for the current row
for j = 1:length(row_data)
fprintf(fileID,’%d,’,round(row_data(j))); % Round values to nearest integer
end
fprintf(fileID,’n’);
end
% Close the file (remains the same)
fclose(fileID);
2. i use another function to plot the bounding bos from the data from spreadsheet.
%get the coordinates
solutionFile = ‘vertex_data.csv’;
solutionData = readmatrix(solutionFile);
% get the two bounding box corners (min(x),min(y),min(z)) and (max(x),max(y),max(z))
p1 = min(reshape(min(solutionData(:,2:end),[],1),3,[]).’,[],1);
p8 = max(reshape(max(solutionData(:,2:end),[],1),3,[]).’,[],1);
coordinates = solutionData(:, 2:end);
% append the bounding box coordinates to the end of the coordinates matrix:
p_bb = [p1,p1,p1,p8,p1,p8,p8,p8];
p_bb([5 9 13]) = p8([2 3 1]);
p_bb([10 18 20]) = p1([1 3 2]);
coordinates(end+1,:) = p_bb;
N = size(coordinates,1);
colors = [0 1 0; 0 0 1; 1 0 0; 1 1 0; 1 0 1];
colors = repmat(colors,ceil(N/size(colors,1)),1);
% make the bounding box a special color:
colors(N,:) = [0.8 0.8 0.8];
figure
F = [1 2 4 3; 5 6 8 7; 1 2 6 5; 4 3 7 8; 2 6 8 4; 1 5 7 3];
for ii = 1:N
C = reshape(coordinates(ii, :), 3, []).’;
patch( …
‘Vertices’,C, …
‘Faces’,F, …
‘FaceColor’,’flat’, …
‘FaceVertexCData’,colors(ii,:), …
‘FaceAlpha’,0.5);
end
view(3)
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
zlabel(‘Z-axis’);
title(‘Visualization of Boxes’);
grid on;
i have attached all my .m files for reference. i need help on how to plot bounding box according to the boxes arrangement.hi,
im trying to plot a bounding box around the final arrangement of boxes but im not getting the ideal output.
this is how the final arrangement of the boxes looks:
expected output:
the output im getting:
this is the flow of my code:
i get the vertices of the 5 boxes in the final arrangement and parse them to a spreadsheet.
clc;
clear;
close all;
%% Problem Definition
model = CreateModel(); % Create Bin Packing Model
CostFunction = @(x) BinPackingCost(x, model); % Objective Function
nVar = model.n * 4; % Each item now has a dimension setting (x, y, z, orientation)
VarSize = [1 nVar]; % Decision Variables Matrix Size
VarMin = 0; % Lower Bound of Decision Variables
VarMax = 1; % Upper Bound of Decision Variables
%% PSO Parameters
MaxIt = 1000; % Maximum Number of Iterations
nPop = 50; % Population Size (Swarm Size)
w = 1; % Inertia Weight
wdamp = 0.99; % Inertia Weight Damping Ratio
c1 = 1.5; % Personal Learning Coefficient
c2 = 2.0; % Global Learning Coefficient
VelMax = 0.1 * (VarMax – VarMin); % Velocity Limits
VelMin = -VelMax;
%% Initialization
particle = repmat(struct(‘Position’, [], ‘Cost’, [], ‘Sol’, [], ‘Velocity’, [], ‘Best’, struct()), nPop, 1);
GlobalBest.Cost = inf;
for i = 1:nPop
% Initialize position with additional orientation indices
particle(i).Position = unifrnd(VarMin, VarMax, VarSize);
% Ensure orientation indices are integers between 1 and 6
particle(i).Position(4:4:end) = randi(6, 1, model.n);
% Velocity and other initialization as before
particle(i).Velocity = zeros(VarSize);
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
particle(i).Best.Sol = particle(i).Sol;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
BestCost = zeros(MaxIt, 1);
%% PSO Main Loop
for it = 1:MaxIt
for i = 1:nPop
particle(i).Velocity = w * particle(i).Velocity …
+ c1 * rand(VarSize) .* (particle(i).Best.Position – particle(i).Position) …
+ c2 * rand(VarSize) .* (GlobalBest.Position – particle(i).Position);
particle(i).Velocity = max(particle(i).Velocity, VelMin);
particle(i).Velocity = min(particle(i).Velocity, VelMax);
particle(i).Position = particle(i).Position + particle(i).Velocity;
particle(i).Position = max(particle(i).Position, VarMin);
particle(i).Position = min(particle(i).Position, VarMax);
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
if particle(i).Cost < particle(i).Best.Cost
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
particle(i).Best.Sol = particle(i).Sol;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
end
BestCost(it) = GlobalBest.Cost;
disp([‘Iteration ‘ num2str(it) ‘: Best Cost = ‘ num2str(BestCost(it))]);
w = w * wdamp;
end
%% Results
figure;
plot(BestCost, ‘LineWidth’, 2);
xlabel(‘Iteration’);
ylabel(‘Best Cost’);
title(‘Convergence of PSO’);
grid on;
%% Bin Configuration Visualization and Vertex Calculation
plotBins(GlobalBest.Sol, model);
vertices = cell(model.n, 1);
for i = GlobalBest.Sol.B{1}
item_dims = model.items(i, :);
orientation = GlobalBest.Position(4*i);
item_pos = GlobalBest.Position(4*i-3:4*i-1);
% Rotate dimensions based on orientation
switch orientation
case 1 % (L, W, H)
rotated_dims = item_dims;
case 2 % (L, H, W)
rotated_dims = [item_dims(1), item_dims(3), item_dims(2)];
case 3 % (W, L, H)
rotated_dims = [item_dims(2), item_dims(1), item_dims(3)];
case 4 % (W, H, L)
rotated_dims = [item_dims(2), item_dims(3), item_dims(1)];
case 5 % (H, L, W)
rotated_dims = [item_dims(3), item_dims(1), item_dims(2)];
case 6 % (H, W, L)
rotated_dims = [item_dims(3), item_dims(2), item_dims(1)];
end
[X, Y, Z] = getBoxVertices(rotated_dims, item_pos);
vertices{i} = [X; Y; Z];
end
%% Exporting Vertex Data to CSV
% Create a cell array to hold the data for the CSV file (This part remains the same)
csv_data = cell(model.n + 1, 1);
csv_data{1} = {‘PresentId’, ‘x1’, ‘y1’, ‘z1’, ‘x2’, ‘y2’, ‘z2’, ‘x3’, ‘y3’, ‘z3’, ‘x4’, ‘y4’, ‘z4’, ‘x5’, ‘y5’, ‘z5’, ‘x6’, ‘y6’, ‘z6’, ‘x7’, ‘y7’, ‘z7’, ‘x8’, ‘y8’, ‘z8’};
% Fill the cell array with vertex data for each item (This part remains the same)
for i = 1:model.n
item_vertices = vertices{i}’; % Transpose to get rows as vertices
csv_data{i+1} = [i, item_vertices(:)’]; % Add item ID and flatten vertex coordinates
end
% Open the file for writing
fileID = fopen(‘vertex_data.csv’,’w’);
% Write header row (remains the same)
fprintf(fileID,’%s,’,csv_data{1}{:});
fprintf(fileID,’n’);
% Write data rows (corrected loop)
for i = 2:size(csv_data,1)
row_data = csv_data{i}; % Get the cell array for the current row
for j = 1:length(row_data)
fprintf(fileID,’%d,’,round(row_data(j))); % Round values to nearest integer
end
fprintf(fileID,’n’);
end
% Close the file (remains the same)
fclose(fileID);
2. i use another function to plot the bounding bos from the data from spreadsheet.
%get the coordinates
solutionFile = ‘vertex_data.csv’;
solutionData = readmatrix(solutionFile);
% get the two bounding box corners (min(x),min(y),min(z)) and (max(x),max(y),max(z))
p1 = min(reshape(min(solutionData(:,2:end),[],1),3,[]).’,[],1);
p8 = max(reshape(max(solutionData(:,2:end),[],1),3,[]).’,[],1);
coordinates = solutionData(:, 2:end);
% append the bounding box coordinates to the end of the coordinates matrix:
p_bb = [p1,p1,p1,p8,p1,p8,p8,p8];
p_bb([5 9 13]) = p8([2 3 1]);
p_bb([10 18 20]) = p1([1 3 2]);
coordinates(end+1,:) = p_bb;
N = size(coordinates,1);
colors = [0 1 0; 0 0 1; 1 0 0; 1 1 0; 1 0 1];
colors = repmat(colors,ceil(N/size(colors,1)),1);
% make the bounding box a special color:
colors(N,:) = [0.8 0.8 0.8];
figure
F = [1 2 4 3; 5 6 8 7; 1 2 6 5; 4 3 7 8; 2 6 8 4; 1 5 7 3];
for ii = 1:N
C = reshape(coordinates(ii, :), 3, []).’;
patch( …
‘Vertices’,C, …
‘Faces’,F, …
‘FaceColor’,’flat’, …
‘FaceVertexCData’,colors(ii,:), …
‘FaceAlpha’,0.5);
end
view(3)
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
zlabel(‘Z-axis’);
title(‘Visualization of Boxes’);
grid on;
i have attached all my .m files for reference. i need help on how to plot bounding box according to the boxes arrangement. hi,
im trying to plot a bounding box around the final arrangement of boxes but im not getting the ideal output.
this is how the final arrangement of the boxes looks:
expected output:
the output im getting:
this is the flow of my code:
i get the vertices of the 5 boxes in the final arrangement and parse them to a spreadsheet.
clc;
clear;
close all;
%% Problem Definition
model = CreateModel(); % Create Bin Packing Model
CostFunction = @(x) BinPackingCost(x, model); % Objective Function
nVar = model.n * 4; % Each item now has a dimension setting (x, y, z, orientation)
VarSize = [1 nVar]; % Decision Variables Matrix Size
VarMin = 0; % Lower Bound of Decision Variables
VarMax = 1; % Upper Bound of Decision Variables
%% PSO Parameters
MaxIt = 1000; % Maximum Number of Iterations
nPop = 50; % Population Size (Swarm Size)
w = 1; % Inertia Weight
wdamp = 0.99; % Inertia Weight Damping Ratio
c1 = 1.5; % Personal Learning Coefficient
c2 = 2.0; % Global Learning Coefficient
VelMax = 0.1 * (VarMax – VarMin); % Velocity Limits
VelMin = -VelMax;
%% Initialization
particle = repmat(struct(‘Position’, [], ‘Cost’, [], ‘Sol’, [], ‘Velocity’, [], ‘Best’, struct()), nPop, 1);
GlobalBest.Cost = inf;
for i = 1:nPop
% Initialize position with additional orientation indices
particle(i).Position = unifrnd(VarMin, VarMax, VarSize);
% Ensure orientation indices are integers between 1 and 6
particle(i).Position(4:4:end) = randi(6, 1, model.n);
% Velocity and other initialization as before
particle(i).Velocity = zeros(VarSize);
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
particle(i).Best.Sol = particle(i).Sol;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
BestCost = zeros(MaxIt, 1);
%% PSO Main Loop
for it = 1:MaxIt
for i = 1:nPop
particle(i).Velocity = w * particle(i).Velocity …
+ c1 * rand(VarSize) .* (particle(i).Best.Position – particle(i).Position) …
+ c2 * rand(VarSize) .* (GlobalBest.Position – particle(i).Position);
particle(i).Velocity = max(particle(i).Velocity, VelMin);
particle(i).Velocity = min(particle(i).Velocity, VelMax);
particle(i).Position = particle(i).Position + particle(i).Velocity;
particle(i).Position = max(particle(i).Position, VarMin);
particle(i).Position = min(particle(i).Position, VarMax);
[particle(i).Cost, particle(i).Sol] = CostFunction(particle(i).Position);
if particle(i).Cost < particle(i).Best.Cost
particle(i).Best.Position = particle(i).Position;
particle(i).Best.Cost = particle(i).Cost;
particle(i).Best.Sol = particle(i).Sol;
if particle(i).Best.Cost < GlobalBest.Cost
GlobalBest = particle(i).Best;
end
end
end
BestCost(it) = GlobalBest.Cost;
disp([‘Iteration ‘ num2str(it) ‘: Best Cost = ‘ num2str(BestCost(it))]);
w = w * wdamp;
end
%% Results
figure;
plot(BestCost, ‘LineWidth’, 2);
xlabel(‘Iteration’);
ylabel(‘Best Cost’);
title(‘Convergence of PSO’);
grid on;
%% Bin Configuration Visualization and Vertex Calculation
plotBins(GlobalBest.Sol, model);
vertices = cell(model.n, 1);
for i = GlobalBest.Sol.B{1}
item_dims = model.items(i, :);
orientation = GlobalBest.Position(4*i);
item_pos = GlobalBest.Position(4*i-3:4*i-1);
% Rotate dimensions based on orientation
switch orientation
case 1 % (L, W, H)
rotated_dims = item_dims;
case 2 % (L, H, W)
rotated_dims = [item_dims(1), item_dims(3), item_dims(2)];
case 3 % (W, L, H)
rotated_dims = [item_dims(2), item_dims(1), item_dims(3)];
case 4 % (W, H, L)
rotated_dims = [item_dims(2), item_dims(3), item_dims(1)];
case 5 % (H, L, W)
rotated_dims = [item_dims(3), item_dims(1), item_dims(2)];
case 6 % (H, W, L)
rotated_dims = [item_dims(3), item_dims(2), item_dims(1)];
end
[X, Y, Z] = getBoxVertices(rotated_dims, item_pos);
vertices{i} = [X; Y; Z];
end
%% Exporting Vertex Data to CSV
% Create a cell array to hold the data for the CSV file (This part remains the same)
csv_data = cell(model.n + 1, 1);
csv_data{1} = {‘PresentId’, ‘x1’, ‘y1’, ‘z1’, ‘x2’, ‘y2’, ‘z2’, ‘x3’, ‘y3’, ‘z3’, ‘x4’, ‘y4’, ‘z4’, ‘x5’, ‘y5’, ‘z5’, ‘x6’, ‘y6’, ‘z6’, ‘x7’, ‘y7’, ‘z7’, ‘x8’, ‘y8’, ‘z8’};
% Fill the cell array with vertex data for each item (This part remains the same)
for i = 1:model.n
item_vertices = vertices{i}’; % Transpose to get rows as vertices
csv_data{i+1} = [i, item_vertices(:)’]; % Add item ID and flatten vertex coordinates
end
% Open the file for writing
fileID = fopen(‘vertex_data.csv’,’w’);
% Write header row (remains the same)
fprintf(fileID,’%s,’,csv_data{1}{:});
fprintf(fileID,’n’);
% Write data rows (corrected loop)
for i = 2:size(csv_data,1)
row_data = csv_data{i}; % Get the cell array for the current row
for j = 1:length(row_data)
fprintf(fileID,’%d,’,round(row_data(j))); % Round values to nearest integer
end
fprintf(fileID,’n’);
end
% Close the file (remains the same)
fclose(fileID);
2. i use another function to plot the bounding bos from the data from spreadsheet.
%get the coordinates
solutionFile = ‘vertex_data.csv’;
solutionData = readmatrix(solutionFile);
% get the two bounding box corners (min(x),min(y),min(z)) and (max(x),max(y),max(z))
p1 = min(reshape(min(solutionData(:,2:end),[],1),3,[]).’,[],1);
p8 = max(reshape(max(solutionData(:,2:end),[],1),3,[]).’,[],1);
coordinates = solutionData(:, 2:end);
% append the bounding box coordinates to the end of the coordinates matrix:
p_bb = [p1,p1,p1,p8,p1,p8,p8,p8];
p_bb([5 9 13]) = p8([2 3 1]);
p_bb([10 18 20]) = p1([1 3 2]);
coordinates(end+1,:) = p_bb;
N = size(coordinates,1);
colors = [0 1 0; 0 0 1; 1 0 0; 1 1 0; 1 0 1];
colors = repmat(colors,ceil(N/size(colors,1)),1);
% make the bounding box a special color:
colors(N,:) = [0.8 0.8 0.8];
figure
F = [1 2 4 3; 5 6 8 7; 1 2 6 5; 4 3 7 8; 2 6 8 4; 1 5 7 3];
for ii = 1:N
C = reshape(coordinates(ii, :), 3, []).’;
patch( …
‘Vertices’,C, …
‘Faces’,F, …
‘FaceColor’,’flat’, …
‘FaceVertexCData’,colors(ii,:), …
‘FaceAlpha’,0.5);
end
view(3)
xlabel(‘X-axis’);
ylabel(‘Y-axis’);
zlabel(‘Z-axis’);
title(‘Visualization of Boxes’);
grid on;
i have attached all my .m files for reference. i need help on how to plot bounding box according to the boxes arrangement. 3d plots, matlab, plots, toolbox MATLAB Answers — New Questions
How to prevent plots from resizing in making GIFs
I am trying to implement two plots changing side-by-side as a GIF, but I’m noticing that the plots keep changing size and move around which makes the animation a bit jarring. Does anyone know what I could do to fix this?
Here is the code I’m using to generate the GIFs (the entire code is rather long so this is just the portion dedicated to plotting):
I initialize (outside the for loop) with
figure
subplot(1,2,1)
hold on
p1 = plot(dom_plot,u_sol, ‘r’);
xlim([-pi pi])
axis square
drawnow
subplot(1,2,2)
hold on
plot(k, norm(uv), ‘b.’, ‘markersize’, 10)
axis square
drawnow
And then within the for loop I update it as:
subplot(1,2,1)
p1 = plot(dom_plot, real(u_sol), ‘r’);
cla(p1)
axis([-pi, pi, -max_plot, max_plot])
drawnow
axis square
subplot(1,2,2)
plot(uv_0(end), norm(uv_0(1:end-1)), ‘b.’, ‘markersize’, 10)
drawnow
axis square
exportgraphics(gcf,’w_4_2_animation.gif’,’Append’,true);
Below is an example of what one of these animations looks like. Any help would be much appreciated; thank you!I am trying to implement two plots changing side-by-side as a GIF, but I’m noticing that the plots keep changing size and move around which makes the animation a bit jarring. Does anyone know what I could do to fix this?
Here is the code I’m using to generate the GIFs (the entire code is rather long so this is just the portion dedicated to plotting):
I initialize (outside the for loop) with
figure
subplot(1,2,1)
hold on
p1 = plot(dom_plot,u_sol, ‘r’);
xlim([-pi pi])
axis square
drawnow
subplot(1,2,2)
hold on
plot(k, norm(uv), ‘b.’, ‘markersize’, 10)
axis square
drawnow
And then within the for loop I update it as:
subplot(1,2,1)
p1 = plot(dom_plot, real(u_sol), ‘r’);
cla(p1)
axis([-pi, pi, -max_plot, max_plot])
drawnow
axis square
subplot(1,2,2)
plot(uv_0(end), norm(uv_0(1:end-1)), ‘b.’, ‘markersize’, 10)
drawnow
axis square
exportgraphics(gcf,’w_4_2_animation.gif’,’Append’,true);
Below is an example of what one of these animations looks like. Any help would be much appreciated; thank you! I am trying to implement two plots changing side-by-side as a GIF, but I’m noticing that the plots keep changing size and move around which makes the animation a bit jarring. Does anyone know what I could do to fix this?
Here is the code I’m using to generate the GIFs (the entire code is rather long so this is just the portion dedicated to plotting):
I initialize (outside the for loop) with
figure
subplot(1,2,1)
hold on
p1 = plot(dom_plot,u_sol, ‘r’);
xlim([-pi pi])
axis square
drawnow
subplot(1,2,2)
hold on
plot(k, norm(uv), ‘b.’, ‘markersize’, 10)
axis square
drawnow
And then within the for loop I update it as:
subplot(1,2,1)
p1 = plot(dom_plot, real(u_sol), ‘r’);
cla(p1)
axis([-pi, pi, -max_plot, max_plot])
drawnow
axis square
subplot(1,2,2)
plot(uv_0(end), norm(uv_0(1:end-1)), ‘b.’, ‘markersize’, 10)
drawnow
axis square
exportgraphics(gcf,’w_4_2_animation.gif’,’Append’,true);
Below is an example of what one of these animations looks like. Any help would be much appreciated; thank you! gifs, animation, gif, animations, figures, 3d plots MATLAB Answers — New Questions
How to return a vector output when a vector input is given to a function_handle representing a constant function?
I want to define a function handle that represents the constant function , pass an n-length vector input, and get out an n-length vector whose values are . But there’s a catch. My code is like:
% Usual Case
syms x; syms t;
u = symfun(x^2,x);
u_x = diff(u,x);
u_x = matlabFunction(u_x);
u_x([0 1 2])
ans = [0 2 4];
So, I input a vector, and I get back a vector, which I would consider the "expected" behavior. But it might happen that the input function happens to have a constant derivative, like
% Exceptional Case
syms x; syms t;
u = symfun(x,x);
u_x = diff(u,x);
u_x = matlabFunction(u_x);
u_x([0 1 2])
ans = 1
Now, I put in a vector and suddenly MATLAB returns a scalar.
So if I only ever had the exceptional case, I would just do something like u_x(0) * ones(1,3) to get my desired vector of constants. But actually, I almost never have the exceptional case; most of the time the input function does not have a constant derivative, and so inputing a vector into the differentiated function returns a vector already.
What I want is for MATLAB to do what I would consider the obvious thing: If I input a vector, I get back a vector, even if the function_handle represents a constant function…how do I do?
Thanks!I want to define a function handle that represents the constant function , pass an n-length vector input, and get out an n-length vector whose values are . But there’s a catch. My code is like:
% Usual Case
syms x; syms t;
u = symfun(x^2,x);
u_x = diff(u,x);
u_x = matlabFunction(u_x);
u_x([0 1 2])
ans = [0 2 4];
So, I input a vector, and I get back a vector, which I would consider the "expected" behavior. But it might happen that the input function happens to have a constant derivative, like
% Exceptional Case
syms x; syms t;
u = symfun(x,x);
u_x = diff(u,x);
u_x = matlabFunction(u_x);
u_x([0 1 2])
ans = 1
Now, I put in a vector and suddenly MATLAB returns a scalar.
So if I only ever had the exceptional case, I would just do something like u_x(0) * ones(1,3) to get my desired vector of constants. But actually, I almost never have the exceptional case; most of the time the input function does not have a constant derivative, and so inputing a vector into the differentiated function returns a vector already.
What I want is for MATLAB to do what I would consider the obvious thing: If I input a vector, I get back a vector, even if the function_handle represents a constant function…how do I do?
Thanks! I want to define a function handle that represents the constant function , pass an n-length vector input, and get out an n-length vector whose values are . But there’s a catch. My code is like:
% Usual Case
syms x; syms t;
u = symfun(x^2,x);
u_x = diff(u,x);
u_x = matlabFunction(u_x);
u_x([0 1 2])
ans = [0 2 4];
So, I input a vector, and I get back a vector, which I would consider the "expected" behavior. But it might happen that the input function happens to have a constant derivative, like
% Exceptional Case
syms x; syms t;
u = symfun(x,x);
u_x = diff(u,x);
u_x = matlabFunction(u_x);
u_x([0 1 2])
ans = 1
Now, I put in a vector and suddenly MATLAB returns a scalar.
So if I only ever had the exceptional case, I would just do something like u_x(0) * ones(1,3) to get my desired vector of constants. But actually, I almost never have the exceptional case; most of the time the input function does not have a constant derivative, and so inputing a vector into the differentiated function returns a vector already.
What I want is for MATLAB to do what I would consider the obvious thing: If I input a vector, I get back a vector, even if the function_handle represents a constant function…how do I do?
Thanks! pde, symbolicfunctions, functionhandles MATLAB Answers — New Questions
How to make a scatter plot where each point is colored according to a given ID and the xlabel ticks are determined by the associated string.
The data I am trying to plot is in an Nx3 table where the label for each columns are ‘Value’, ‘Condition’ and ‘ID’. I want to plot the values in ‘Value’, group them according to ‘Condition’ and color them based on ‘ID’ so something like swarmchart I guess I am trying to do.
To get something to work with, this is an example of how my data could look like. How do I plot this?
Value Condition ID
—————————– —- ——-
0.0608000000000000 ‘B’ "ID 1"
0.0476000000000000 ‘B’ "ID 2"
0.0483000000000000 ‘B’ "ID 3"
0.298800000000000 ‘B’ "ID 4"
0.0377000000000000 ‘B’ "ID 5"The data I am trying to plot is in an Nx3 table where the label for each columns are ‘Value’, ‘Condition’ and ‘ID’. I want to plot the values in ‘Value’, group them according to ‘Condition’ and color them based on ‘ID’ so something like swarmchart I guess I am trying to do.
To get something to work with, this is an example of how my data could look like. How do I plot this?
Value Condition ID
—————————– —- ——-
0.0608000000000000 ‘B’ "ID 1"
0.0476000000000000 ‘B’ "ID 2"
0.0483000000000000 ‘B’ "ID 3"
0.298800000000000 ‘B’ "ID 4"
0.0377000000000000 ‘B’ "ID 5" The data I am trying to plot is in an Nx3 table where the label for each columns are ‘Value’, ‘Condition’ and ‘ID’. I want to plot the values in ‘Value’, group them according to ‘Condition’ and color them based on ‘ID’ so something like swarmchart I guess I am trying to do.
To get something to work with, this is an example of how my data could look like. How do I plot this?
Value Condition ID
—————————– —- ——-
0.0608000000000000 ‘B’ "ID 1"
0.0476000000000000 ‘B’ "ID 2"
0.0483000000000000 ‘B’ "ID 3"
0.298800000000000 ‘B’ "ID 4"
0.0377000000000000 ‘B’ "ID 5" plotting, matlab MATLAB Answers — New Questions
How to add hyperlinks to property names in the class display?
I am attempting to create a custom display for my class where the object properties names would be displayed as hyperlinks. When clicked, a hyperlink would display the value of the corresponding property in the Command Window. I want the same default display of the object but with the properties names as the hyperlinks.
My end goal is to seamlessly traverse through an object that has many "child" properties, e.g., objectName.Prop1.Prop2.Prop3.Prop4. My intended strategy is to use mouse clicks instead of having to type and use multiple tab-completes.
How can I do that?I am attempting to create a custom display for my class where the object properties names would be displayed as hyperlinks. When clicked, a hyperlink would display the value of the corresponding property in the Command Window. I want the same default display of the object but with the properties names as the hyperlinks.
My end goal is to seamlessly traverse through an object that has many "child" properties, e.g., objectName.Prop1.Prop2.Prop3.Prop4. My intended strategy is to use mouse clicks instead of having to type and use multiple tab-completes.
How can I do that? I am attempting to create a custom display for my class where the object properties names would be displayed as hyperlinks. When clicked, a hyperlink would display the value of the corresponding property in the Command Window. I want the same default display of the object but with the properties names as the hyperlinks.
My end goal is to seamlessly traverse through an object that has many "child" properties, e.g., objectName.Prop1.Prop2.Prop3.Prop4. My intended strategy is to use mouse clicks instead of having to type and use multiple tab-completes.
How can I do that? customdisplay, hyperlink, object, property, class, display MATLAB Answers — New Questions
Wrong sine plot when styling it
I was playing with the tutorial of Matlab. I’ve written this code:
x = linspace(0, 2*pi);
y = sin(x);
plot(x, y)
And I obtain the right plot:
But then I use the following command:
plot(x, y, "r–")
And I obtain this weird plot:
What I’m doing wrong?I was playing with the tutorial of Matlab. I’ve written this code:
x = linspace(0, 2*pi);
y = sin(x);
plot(x, y)
And I obtain the right plot:
But then I use the following command:
plot(x, y, "r–")
And I obtain this weird plot:
What I’m doing wrong? I was playing with the tutorial of Matlab. I’ve written this code:
x = linspace(0, 2*pi);
y = sin(x);
plot(x, y)
And I obtain the right plot:
But then I use the following command:
plot(x, y, "r–")
And I obtain this weird plot:
What I’m doing wrong? plot, error MATLAB Answers — New Questions
How to rearrange String Data within table relative to one Column of Data.
Hello,
I have a table with 80X10. The first Variable (Var 1) has text Data, Variable 8 (Relavent Data), Variable 9 (parameter List), Variable 10 (GPP_Names). Var1 to Var8 Imported from File A and Var 9, Var10 (Parameter_List & Gpp_Names) Imported from another.
Both Contatinated (horzcat) and put together in one table Common_Data_1. As in the attached picture.
Var 1 & Var 9 (Parameter_List) are exactly same text. But I am unable to arrange it to match each other.
Var9 (Parameter_List) & Var 10 (Gpp_Names) are alligned Perfectly.
I would like to extract Var 1,Var8, Parameter_List,GPP_Names data that perfectly aligned.
1) Should I match the text pattern before Concatinating them into one Table?
2) How could I use sortrows or rowfun or other functions to arrange this data?
Any help or suggestion would be of great help.
Thanks
SaiHello,
I have a table with 80X10. The first Variable (Var 1) has text Data, Variable 8 (Relavent Data), Variable 9 (parameter List), Variable 10 (GPP_Names). Var1 to Var8 Imported from File A and Var 9, Var10 (Parameter_List & Gpp_Names) Imported from another.
Both Contatinated (horzcat) and put together in one table Common_Data_1. As in the attached picture.
Var 1 & Var 9 (Parameter_List) are exactly same text. But I am unable to arrange it to match each other.
Var9 (Parameter_List) & Var 10 (Gpp_Names) are alligned Perfectly.
I would like to extract Var 1,Var8, Parameter_List,GPP_Names data that perfectly aligned.
1) Should I match the text pattern before Concatinating them into one Table?
2) How could I use sortrows or rowfun or other functions to arrange this data?
Any help or suggestion would be of great help.
Thanks
Sai Hello,
I have a table with 80X10. The first Variable (Var 1) has text Data, Variable 8 (Relavent Data), Variable 9 (parameter List), Variable 10 (GPP_Names). Var1 to Var8 Imported from File A and Var 9, Var10 (Parameter_List & Gpp_Names) Imported from another.
Both Contatinated (horzcat) and put together in one table Common_Data_1. As in the attached picture.
Var 1 & Var 9 (Parameter_List) are exactly same text. But I am unable to arrange it to match each other.
Var9 (Parameter_List) & Var 10 (Gpp_Names) are alligned Perfectly.
I would like to extract Var 1,Var8, Parameter_List,GPP_Names data that perfectly aligned.
1) Should I match the text pattern before Concatinating them into one Table?
2) How could I use sortrows or rowfun or other functions to arrange this data?
Any help or suggestion would be of great help.
Thanks
Sai text match alligment, table, sortrows, rowfunc MATLAB Answers — New Questions