Category: Matlab
Category Archives: Matlab
Discrepancy in Peak Temperature Between Simulation and Experiment in 4s3p NCA Battery Pack
Hi everyone,
I’m currently working on the simulation of a 4s3p battery pack using Molicel INR-21700-P45B cells (NCA chemistry). The pack undergoes full charge and discharge cycles (from 3.0 V to 4.2 V per cell) under natural convection conditions, for 10 cycles at both 1C and 1.5C rates.
The charge protocol includes CCCV charging, followed by a 30-minute rest, then CC discharging, and another 30-minute rest. In the simulation, the peak temperature during discharging is higher than during charging. However, in our experimental results, the opposite is observed—the peak temperature is higher during charging.
For the simulation, we used the OCV curve of a single cell multiplied by 4 for the 4s configuration.
Has anyone encountered a similar issue or could provide insights into why the simulated thermal behavior might differ from experimental results?Hi everyone,
I’m currently working on the simulation of a 4s3p battery pack using Molicel INR-21700-P45B cells (NCA chemistry). The pack undergoes full charge and discharge cycles (from 3.0 V to 4.2 V per cell) under natural convection conditions, for 10 cycles at both 1C and 1.5C rates.
The charge protocol includes CCCV charging, followed by a 30-minute rest, then CC discharging, and another 30-minute rest. In the simulation, the peak temperature during discharging is higher than during charging. However, in our experimental results, the opposite is observed—the peak temperature is higher during charging.
For the simulation, we used the OCV curve of a single cell multiplied by 4 for the 4s configuration.
Has anyone encountered a similar issue or could provide insights into why the simulated thermal behavior might differ from experimental results? Hi everyone,
I’m currently working on the simulation of a 4s3p battery pack using Molicel INR-21700-P45B cells (NCA chemistry). The pack undergoes full charge and discharge cycles (from 3.0 V to 4.2 V per cell) under natural convection conditions, for 10 cycles at both 1C and 1.5C rates.
The charge protocol includes CCCV charging, followed by a 30-minute rest, then CC discharging, and another 30-minute rest. In the simulation, the peak temperature during discharging is higher than during charging. However, in our experimental results, the opposite is observed—the peak temperature is higher during charging.
For the simulation, we used the OCV curve of a single cell multiplied by 4 for the 4s configuration.
Has anyone encountered a similar issue or could provide insights into why the simulated thermal behavior might differ from experimental results? simscape, simulation MATLAB Answers — New Questions
errors when generating certain motions of Revolute Joint in simMechanics
The model:
<</matlabcentral/answers/uploaded_files/27438/3.PNG>>
The simMechanics system is as follow:
<</matlabcentral/answers/uploaded_files/27436/1.PNG>>
simin is input from workspace and is the motion of Revolute Joint as the time goes on.
<</matlabcentral/answers/uploaded_files/27437/2.PNG>>
But it shows some kind of error:
In the dynamically coupled component containing Revolute Joint Revolute_Joint, there are fewer joint primitive degrees of freedom with automatically computed force or torque (0) than with motion from inputs (1). The prescribed motion trajectories in this component may not be achievable. Solve this problem by reducing the number of joint primitives with motion from inputs or increasing the number of joint primitives with automatically computed force or torque. Resolve this issue in order to simulate the model.
Does anybody knows what’s wrong and what should I do to solve the problem.The model:
<</matlabcentral/answers/uploaded_files/27438/3.PNG>>
The simMechanics system is as follow:
<</matlabcentral/answers/uploaded_files/27436/1.PNG>>
simin is input from workspace and is the motion of Revolute Joint as the time goes on.
<</matlabcentral/answers/uploaded_files/27437/2.PNG>>
But it shows some kind of error:
In the dynamically coupled component containing Revolute Joint Revolute_Joint, there are fewer joint primitive degrees of freedom with automatically computed force or torque (0) than with motion from inputs (1). The prescribed motion trajectories in this component may not be achievable. Solve this problem by reducing the number of joint primitives with motion from inputs or increasing the number of joint primitives with automatically computed force or torque. Resolve this issue in order to simulate the model.
Does anybody knows what’s wrong and what should I do to solve the problem. The model:
<</matlabcentral/answers/uploaded_files/27438/3.PNG>>
The simMechanics system is as follow:
<</matlabcentral/answers/uploaded_files/27436/1.PNG>>
simin is input from workspace and is the motion of Revolute Joint as the time goes on.
<</matlabcentral/answers/uploaded_files/27437/2.PNG>>
But it shows some kind of error:
In the dynamically coupled component containing Revolute Joint Revolute_Joint, there are fewer joint primitive degrees of freedom with automatically computed force or torque (0) than with motion from inputs (1). The prescribed motion trajectories in this component may not be achievable. Solve this problem by reducing the number of joint primitives with motion from inputs or increasing the number of joint primitives with automatically computed force or torque. Resolve this issue in order to simulate the model.
Does anybody knows what’s wrong and what should I do to solve the problem. simulink, simmechanics MATLAB Answers — New Questions
how can I add a point in figure?
Hi,
I want to add a point to this figure. Can you please tell me how to do that ?
the point that I want to add to my figure is: x=70.00; y= 0.30. Thanks for your time.Hi,
I want to add a point to this figure. Can you please tell me how to do that ?
the point that I want to add to my figure is: x=70.00; y= 0.30. Thanks for your time. Hi,
I want to add a point to this figure. Can you please tell me how to do that ?
the point that I want to add to my figure is: x=70.00; y= 0.30. Thanks for your time. matlab, figure MATLAB Answers — New Questions
Nonlinear Curve fitting with integrals
I encountered a nonlinear fitting problem, and the fitting formula is shown in Equation (1), which includes two infinite integrals (in practice, the integration range can be set from 0.01E-6 to 200E-6).
In these formulas, except for x and y being vectors, all other variables are scalars, and Rmedian and sigma are the parameters to be fitted.
I found a related post and tried to write the code based on it, but it keeps reporting errors. The error message seems to indicate that the vector dimensions are inconsistent, preventing the operation from proceeding. However, these functions are all calculations for individual scalars.
Error using /
Matrix dimensions must agree.
Error in dsdmain>@(r)1/(2*r*sigma*sqrt(2*pi))*exp(-(log(2*r)-log(2*Rmean)^2)/(2*sigma^2)) (line 13)
gauss = @(r) 1/(2*r*sigma*sqrt(2*pi))* exp( -(log(2*r)-log(2*Rmean)^2)/(2*sigma^2) );
My question is: Can I refer to the content of this post to solve my problem? If yes, what does this error message mean? If not, how should I resolve my problem? (Note: The range of Rmedian is 1E-6 to 5E-6)
After modifying the code according to Walter Roberson and Torsten’s suggestion, the program no longer throws errors. But no matter how I set the initial values on my end, it always prompts:
Initial point is a local minimum.
Optimization completed because the size of the gradient at the initial point
is less than the default value of the optimality tolerance.
<stopping criteria details>
theta = initial point
1.0e-05 *
0.2000
0.1000
Optimization completed: The final point is the initial point.
The first-order optimality measure, 0.000000e+00, is less than
options.OptimalityTolerance = 1.000000e-06.
Optimization Metric Options
relative first-order optimality = 0.00e+00 OptimalityTolerance = 1e-06 (default)
I have checked all the formulas and the units of the variables, and I didn’t find any problems.
————————————– Beblow is my code for issue reproduction ———————————————————-
function testmain()
clc
function Kvec = model(param,xdata)
% Vector of Kd for every xdata:
Kvec = zeros(size(xdata));
Rmean = param(1);
Rstd = param(2);
for i = 1:length(xdata)
model = @(r) unified(xdata(i),r,Rmean,Rstd,delta,Delta,D,lambda);
Kvec(i) = integral(model,0.01E-6,200E-6);
end
end
function s = unified(g,R,Rmean,Rstd,delta,Delta,D,lambda)
%unified Unified fitting model for DSD
% exponentional combined
factor = 1./(2*R*Rstd*sqrt(2*pi)) *2 ; % int(P(r)) = 0.5,1/0.5=2
p1 = -(log(2*R)-log(2*Rmean)).^2/(2*Rstd^2);
c = -2*2.675E8^2*g.^2/D;
tmp = 0;
for il = 1:length(lambda)
a2 = (lambda(il)./R).^2;
an4 = (R/lambda(il)).^4;
Psi = 2+exp(-a2*D*(Delta-delta))-2*exp(-a2*D*delta)-2*exp(-a2*D*Delta)+exp(-a2*D*(Delta+delta));
tmp = tmp+an4./(a2.*R.*R-2).*(2*delta-Psi./(a2*D));
end
p2 = c*tmp;
s = factor.*exp(p1+p2);
end
Delta = 0.075;
delta = 0.002;
D = 0.098E-9;
lambda = [2.0816 5.9404 9.2058 12.4044 15.5792 18.7426 21.8997 25.0528 28.2034 31.3521];
g = [ 0.300616, 0.53884, 0.771392, 1.009616, 1.24784, 1.480392, 1.718616, 1.95684, 2.189392, 2.427616, 2.66584, 2.898392 ];
xdata = g;
ydata = [100, 91.16805426, 80.52955192, 67.97705378, 55.1009735,41.87307917, 30.39638776, 21.13515607, 13.7125649, 8.33083767, 5.146756077, 2.79768609];
ydata = ydata/ydata(1); % normalize
% Inital guess for parameters:
Rmean0 = 2E-6;
Rstd0 = 1E-6;
p0 = [Rmean0;Rstd0];
% lsqcurvefit is in the optimization toolbox.
% fit, from the curve fitting toolbox may be an alternative
theta = lsqcurvefit(@model,p0,xdata,ydata,[0.01E-6;0.1E-6],[10E-6,2E-6])
endI encountered a nonlinear fitting problem, and the fitting formula is shown in Equation (1), which includes two infinite integrals (in practice, the integration range can be set from 0.01E-6 to 200E-6).
In these formulas, except for x and y being vectors, all other variables are scalars, and Rmedian and sigma are the parameters to be fitted.
I found a related post and tried to write the code based on it, but it keeps reporting errors. The error message seems to indicate that the vector dimensions are inconsistent, preventing the operation from proceeding. However, these functions are all calculations for individual scalars.
Error using /
Matrix dimensions must agree.
Error in dsdmain>@(r)1/(2*r*sigma*sqrt(2*pi))*exp(-(log(2*r)-log(2*Rmean)^2)/(2*sigma^2)) (line 13)
gauss = @(r) 1/(2*r*sigma*sqrt(2*pi))* exp( -(log(2*r)-log(2*Rmean)^2)/(2*sigma^2) );
My question is: Can I refer to the content of this post to solve my problem? If yes, what does this error message mean? If not, how should I resolve my problem? (Note: The range of Rmedian is 1E-6 to 5E-6)
After modifying the code according to Walter Roberson and Torsten’s suggestion, the program no longer throws errors. But no matter how I set the initial values on my end, it always prompts:
Initial point is a local minimum.
Optimization completed because the size of the gradient at the initial point
is less than the default value of the optimality tolerance.
<stopping criteria details>
theta = initial point
1.0e-05 *
0.2000
0.1000
Optimization completed: The final point is the initial point.
The first-order optimality measure, 0.000000e+00, is less than
options.OptimalityTolerance = 1.000000e-06.
Optimization Metric Options
relative first-order optimality = 0.00e+00 OptimalityTolerance = 1e-06 (default)
I have checked all the formulas and the units of the variables, and I didn’t find any problems.
————————————– Beblow is my code for issue reproduction ———————————————————-
function testmain()
clc
function Kvec = model(param,xdata)
% Vector of Kd for every xdata:
Kvec = zeros(size(xdata));
Rmean = param(1);
Rstd = param(2);
for i = 1:length(xdata)
model = @(r) unified(xdata(i),r,Rmean,Rstd,delta,Delta,D,lambda);
Kvec(i) = integral(model,0.01E-6,200E-6);
end
end
function s = unified(g,R,Rmean,Rstd,delta,Delta,D,lambda)
%unified Unified fitting model for DSD
% exponentional combined
factor = 1./(2*R*Rstd*sqrt(2*pi)) *2 ; % int(P(r)) = 0.5,1/0.5=2
p1 = -(log(2*R)-log(2*Rmean)).^2/(2*Rstd^2);
c = -2*2.675E8^2*g.^2/D;
tmp = 0;
for il = 1:length(lambda)
a2 = (lambda(il)./R).^2;
an4 = (R/lambda(il)).^4;
Psi = 2+exp(-a2*D*(Delta-delta))-2*exp(-a2*D*delta)-2*exp(-a2*D*Delta)+exp(-a2*D*(Delta+delta));
tmp = tmp+an4./(a2.*R.*R-2).*(2*delta-Psi./(a2*D));
end
p2 = c*tmp;
s = factor.*exp(p1+p2);
end
Delta = 0.075;
delta = 0.002;
D = 0.098E-9;
lambda = [2.0816 5.9404 9.2058 12.4044 15.5792 18.7426 21.8997 25.0528 28.2034 31.3521];
g = [ 0.300616, 0.53884, 0.771392, 1.009616, 1.24784, 1.480392, 1.718616, 1.95684, 2.189392, 2.427616, 2.66584, 2.898392 ];
xdata = g;
ydata = [100, 91.16805426, 80.52955192, 67.97705378, 55.1009735,41.87307917, 30.39638776, 21.13515607, 13.7125649, 8.33083767, 5.146756077, 2.79768609];
ydata = ydata/ydata(1); % normalize
% Inital guess for parameters:
Rmean0 = 2E-6;
Rstd0 = 1E-6;
p0 = [Rmean0;Rstd0];
% lsqcurvefit is in the optimization toolbox.
% fit, from the curve fitting toolbox may be an alternative
theta = lsqcurvefit(@model,p0,xdata,ydata,[0.01E-6;0.1E-6],[10E-6,2E-6])
end I encountered a nonlinear fitting problem, and the fitting formula is shown in Equation (1), which includes two infinite integrals (in practice, the integration range can be set from 0.01E-6 to 200E-6).
In these formulas, except for x and y being vectors, all other variables are scalars, and Rmedian and sigma are the parameters to be fitted.
I found a related post and tried to write the code based on it, but it keeps reporting errors. The error message seems to indicate that the vector dimensions are inconsistent, preventing the operation from proceeding. However, these functions are all calculations for individual scalars.
Error using /
Matrix dimensions must agree.
Error in dsdmain>@(r)1/(2*r*sigma*sqrt(2*pi))*exp(-(log(2*r)-log(2*Rmean)^2)/(2*sigma^2)) (line 13)
gauss = @(r) 1/(2*r*sigma*sqrt(2*pi))* exp( -(log(2*r)-log(2*Rmean)^2)/(2*sigma^2) );
My question is: Can I refer to the content of this post to solve my problem? If yes, what does this error message mean? If not, how should I resolve my problem? (Note: The range of Rmedian is 1E-6 to 5E-6)
After modifying the code according to Walter Roberson and Torsten’s suggestion, the program no longer throws errors. But no matter how I set the initial values on my end, it always prompts:
Initial point is a local minimum.
Optimization completed because the size of the gradient at the initial point
is less than the default value of the optimality tolerance.
<stopping criteria details>
theta = initial point
1.0e-05 *
0.2000
0.1000
Optimization completed: The final point is the initial point.
The first-order optimality measure, 0.000000e+00, is less than
options.OptimalityTolerance = 1.000000e-06.
Optimization Metric Options
relative first-order optimality = 0.00e+00 OptimalityTolerance = 1e-06 (default)
I have checked all the formulas and the units of the variables, and I didn’t find any problems.
————————————– Beblow is my code for issue reproduction ———————————————————-
function testmain()
clc
function Kvec = model(param,xdata)
% Vector of Kd for every xdata:
Kvec = zeros(size(xdata));
Rmean = param(1);
Rstd = param(2);
for i = 1:length(xdata)
model = @(r) unified(xdata(i),r,Rmean,Rstd,delta,Delta,D,lambda);
Kvec(i) = integral(model,0.01E-6,200E-6);
end
end
function s = unified(g,R,Rmean,Rstd,delta,Delta,D,lambda)
%unified Unified fitting model for DSD
% exponentional combined
factor = 1./(2*R*Rstd*sqrt(2*pi)) *2 ; % int(P(r)) = 0.5,1/0.5=2
p1 = -(log(2*R)-log(2*Rmean)).^2/(2*Rstd^2);
c = -2*2.675E8^2*g.^2/D;
tmp = 0;
for il = 1:length(lambda)
a2 = (lambda(il)./R).^2;
an4 = (R/lambda(il)).^4;
Psi = 2+exp(-a2*D*(Delta-delta))-2*exp(-a2*D*delta)-2*exp(-a2*D*Delta)+exp(-a2*D*(Delta+delta));
tmp = tmp+an4./(a2.*R.*R-2).*(2*delta-Psi./(a2*D));
end
p2 = c*tmp;
s = factor.*exp(p1+p2);
end
Delta = 0.075;
delta = 0.002;
D = 0.098E-9;
lambda = [2.0816 5.9404 9.2058 12.4044 15.5792 18.7426 21.8997 25.0528 28.2034 31.3521];
g = [ 0.300616, 0.53884, 0.771392, 1.009616, 1.24784, 1.480392, 1.718616, 1.95684, 2.189392, 2.427616, 2.66584, 2.898392 ];
xdata = g;
ydata = [100, 91.16805426, 80.52955192, 67.97705378, 55.1009735,41.87307917, 30.39638776, 21.13515607, 13.7125649, 8.33083767, 5.146756077, 2.79768609];
ydata = ydata/ydata(1); % normalize
% Inital guess for parameters:
Rmean0 = 2E-6;
Rstd0 = 1E-6;
p0 = [Rmean0;Rstd0];
% lsqcurvefit is in the optimization toolbox.
% fit, from the curve fitting toolbox may be an alternative
theta = lsqcurvefit(@model,p0,xdata,ydata,[0.01E-6;0.1E-6],[10E-6,2E-6])
end curve fitting, integral MATLAB Answers — New Questions
Is comm.FMDemodulator a product detection method?
I looked at the algorithm of comm.FMDemodulator, and I have a question: comm.FMDemodulator does not require the input of the carrier frequency (fc). So how does it perform the step ys(t)=Y(t)e−j2πfcty_s(t) = Y(t) e^{-j 2pi f_c t}ys(t)=Y(t)e−j2πfct? Or is it using another method, such as phase demodulation?I looked at the algorithm of comm.FMDemodulator, and I have a question: comm.FMDemodulator does not require the input of the carrier frequency (fc). So how does it perform the step ys(t)=Y(t)e−j2πfcty_s(t) = Y(t) e^{-j 2pi f_c t}ys(t)=Y(t)e−j2πfct? Or is it using another method, such as phase demodulation? I looked at the algorithm of comm.FMDemodulator, and I have a question: comm.FMDemodulator does not require the input of the carrier frequency (fc). So how does it perform the step ys(t)=Y(t)e−j2πfcty_s(t) = Y(t) e^{-j 2pi f_c t}ys(t)=Y(t)e−j2πfct? Or is it using another method, such as phase demodulation? fmdemod MATLAB Answers — New Questions
Clarification on Simulink Sample Rate vs HDL Coder Target Frequency
Hello,
I have a question regarding the relationship between Simulink sample rate and HDL Coder target frequency.
Is it okay if the Simulink sample rate is equal to the target frequency specified in HDL Coder?
I’ve often heard that the hardware clock rate (target frequency) should generally be at least 2× the sample rate to ensure proper timing and pipelining. But in Simulink and HDL Coder, I’m unsure how strict this rule is.
Specifically:
If I set my Simulink sample rate to 120 MSPS and also specify 120 MHz as the HDL Coder target frequency, is this configuration valid?
Or should the target frequency always be greater than the sample rate, even in fully pipelined or parallel architectures?
I’d really appreciate any clarification on how these two values interact and whether matching them could lead to timing issues during synthesis or implementation.
Thanks in advance!Hello,
I have a question regarding the relationship between Simulink sample rate and HDL Coder target frequency.
Is it okay if the Simulink sample rate is equal to the target frequency specified in HDL Coder?
I’ve often heard that the hardware clock rate (target frequency) should generally be at least 2× the sample rate to ensure proper timing and pipelining. But in Simulink and HDL Coder, I’m unsure how strict this rule is.
Specifically:
If I set my Simulink sample rate to 120 MSPS and also specify 120 MHz as the HDL Coder target frequency, is this configuration valid?
Or should the target frequency always be greater than the sample rate, even in fully pipelined or parallel architectures?
I’d really appreciate any clarification on how these two values interact and whether matching them could lead to timing issues during synthesis or implementation.
Thanks in advance! Hello,
I have a question regarding the relationship between Simulink sample rate and HDL Coder target frequency.
Is it okay if the Simulink sample rate is equal to the target frequency specified in HDL Coder?
I’ve often heard that the hardware clock rate (target frequency) should generally be at least 2× the sample rate to ensure proper timing and pipelining. But in Simulink and HDL Coder, I’m unsure how strict this rule is.
Specifically:
If I set my Simulink sample rate to 120 MSPS and also specify 120 MHz as the HDL Coder target frequency, is this configuration valid?
Or should the target frequency always be greater than the sample rate, even in fully pipelined or parallel architectures?
I’d really appreciate any clarification on how these two values interact and whether matching them could lead to timing issues during synthesis or implementation.
Thanks in advance! simulink, sample rate, hdl coder, target frequency MATLAB Answers — New Questions
How to shift lines to their correction positions (I need to correct figure)
I need to correct figure (3) in the following script to be similar in the attached file (with automatic way)
clc; close all; clear;
% Load the Excel data
filename = ‘ThreeFaultModel_Modified.xlsx’;
data = xlsread(filename, ‘Sheet1’);
% Extract relevant columns
x = data(:, 1); % Distance (x in km)
Field = data(:, 2); % Earth filed (Field in unit)
%==============================================================%
% Input number of layers and densities
num_blocks = input(‘Enter the number of blocks: ‘);
block_densities = zeros(1, num_blocks);
for i = 1:num_blocks
block_densities(i) = input([‘Enter the density of block ‘, num2str(i), ‘ (kg/m^3): ‘]);
end
%==============================================================%
% Constants
G = 0.00676;
Lower_density = 2.67; % in kg/m^3
%==============================================================%
% Calculate inverted depth profile for each layer
z_inv = zeros(length(x), num_blocks);
for i = 1:num_blocks
density_contrast = block_densities(i) – Lower_density;
if density_contrast ~= 0
z_inv(:, i) = Field ./ (2 * pi * G * density_contrast);
else
z_inv(:, i) = NaN; % Avoid division by zero
end
end
%==============================================================%
% Compute vertical gradient (VG) of inverted depth (clean)
VG = diff(z_inv(:, 1)) ./ diff(x);
%==============================================================%
% Set fault threshold and find f indices based on d changes
f_threshold = 0.5; % Threshold for identifying significant d changes
f_indices = find(abs(diff(z_inv(:, 1))) > f_threshold);
%==============================================================%
% Initialize f locations and dip arrays
%==============================================================%
f_locations = x(f_indices); % Automatically determined f locations
f_dip_angles = nan(size(f_indices)); % Placeholder for calculated dip
% Calculate dip for each identified f
for i = 1:length(f_indices)
idx = f_indices(i);
if idx < length(x)
f_dip_angles(i) = atand(abs(z_inv(idx + 1, 1) – z_inv(idx, 1)) / (x(idx + 1) – x(idx)));
else
f_dip_angles(i) = atand(abs(z_inv(idx, 1) – z_inv(idx – 1, 1)) / (x(idx) – x(idx – 1)));
end
end
%==============================================================%
% Displacement of faults
%==============================================================%
D_faults = zeros(size(f_dip_angles));
for i = 1:length(f_indices)
idx = f_indices(i);
dip_angle_rad = deg2rad(f_dip_angles(i)); % Convert dip to radians
D_faults(i) = abs(z_inv(idx + 1, 1) – z_inv(idx, 1)) / sin(dip_angle_rad);
end
% Assign displacement values
D1 = D_faults(1); % NF displacemen
D2 = D_faults(2); % VF displacement
D3 = D_faults(3); % RF displacement
%==============================================================%
% Processing Data for Interpretation
%==============================================================%
A = [x Field z_inv]; % New Data Obtained
col_names = {‘x’, ‘Field’};
for i = 1:num_blocks
col_names{end+1} = [‘z’, num2str(i)];
end
dataM = array2table(A, ‘VariableNames’, col_names);
t1 = dataM;
[nr, nc] = size(t1);
t1_bottoms = t1;
for jj = 3:nc
for ii = 1:nr-1
if t1_bottoms{ii, jj} ~= t1_bottoms{ii+1, jj}
t1_bottoms{ii, jj} = NaN;
end
end
end
%==============================================================%
% Identifying NaN rows
%==============================================================%
nans = isnan(t1_bottoms{:, 3:end});
nan_rows = find(any(nans, 2));
xc = t1_bottoms{nan_rows, 1}; % Corrected x-coordinates
yc = zeros(numel(nan_rows), 1); % y-coordinates for NaN rows
for ii = 1:numel(nan_rows)
idx = find(~nans(nan_rows(ii), :), 1, ‘last’);
if isempty(idx)
yc(ii) = 0;
else
yc(ii) = t1_bottoms{nan_rows(ii), idx+2};
end
end
%==============================================================%
% Plot f Interpretation
%==============================================================%
figure(1)
plot(A(:, 1), A(:, 3:end))
hold on
grid on
set(gca, ‘YDir’, ‘reverse’)
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
title(‘Interpretation of profile data model’)
%==============================================================%
figure(2)
hold on
plot(t1_bottoms{:, 1}, t1_bottoms{:, 3:end}, ‘LineWidth’, 1)
set(gca, ‘YDir’, ‘reverse’)
box on
grid on
xlabel(‘Distance (km)’);
ylabel(‘Ds (km)’);
title(‘New interpretation of profile data’)
%==============================================================%
% Plot the interpreted d profiles
figure(3)
hold on
% Plot the interpreted d profiles
plot(t1_bottoms{:, 1}, t1_bottoms{:, 3:end}, ‘LineWidth’, 1)
yl = get(gca, ‘YLim’); % Get Y-axis limits
% Define f locations and corresponding dip
f_locations = [7.00, 14.00, 23.00];
d_angles = [58.47, 90.00, -69.79];
for ii = 1:numel(f_locations)
% Find the nearest x index for each fault location
[~, idx] = min(abs(t1_bottoms{:, 1} – f_locations(ii)));
% Get the starting x and y coordinates (fault starts at the surface)
x_f = t1_bottoms{idx, 1};
y_f = yl(1); % Start at the surface (0 km depth)
% Check if the dip angle is 90° (vf)
if d_angles(ii) == 90
x_r = [x_f x_f]; % Vertical line
y_r = [yl(1), yl(2)]; % From surface to de limit
else
% Convert dip to slope (m = tan(angle))
m = tand(d_angles(ii));
% Define the x range for fault line
% x_r = linspace(x_f – 5, x_f + 5, 100); % Extend 5 km on each side
x_r = x;
y_r = y_f – m * (x_r – x_f); % Line equation (+ m)
% Clip y_range within the plot limits
y_r(y_r > yl(2)) = yl(2);
y_r(y_r < yl(1)) = yl(1);
end
% Plot the fault lines in black (matching the image)
plot(x_r, y_r, ‘k’, ‘LineWidth’, 3)
% Display dip angles as text near the faults
% text(x_f, y_f + 1, sprintf(‘\theta = %.2f°’, d_angles(ii)), …
% ‘Color’, ‘k’, ‘FontSize’, 10, ‘FontWeight’, ‘bold’, ‘HorizontalAlignment’, ‘right’)
end
set(gca, ‘YDir’, ‘reverse’) % Reverse Y-axis for depth representation
box on
grid on
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
title(‘New Interpretation of Profile Data’)
%==============================================================%
% Plotting results
figure;
subplot(3,1,1);
plot(x, Field, ‘r’, ‘LineWidth’, 2);
title(‘Field Profile’);
xlabel(‘Distance (km)’);
ylabel(‘Field (unit)’);
grid on;
subplot(3,1,2);
plot(x(1:end-1), VG, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Distance (km)’);
ylabel(‘VG (munit/km)’);
title(‘VG Gradient’);
grid on;
subplot(3,1,3);
hold on;
for i = 1:num_blocks
plot(x, z_inv(:, i), ‘LineWidth’, 2);
end
title(‘Inverted D Profile for Each Block’);
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
set(gca, ‘YDir’, ‘reverse’);
grid on;
%==============================================================%
% Display results
fprintf(‘F Analysis Results:n’);
fprintf(‘Location (km) | Dip (degrees) | D_faults (km)n’);
for i = 1:length(f_locations)
fprintf(‘%10.2f | %17.2f | %10.2fn’, f_locations(i), f_dip_angles(i), D_faults(i));
end
% Ensure both variables are column vectors of the same size
f_locations = f_locations(:); % Convert to column vector
f_dip_angles = f_dip_angles(:); % Convert to column vector
% Concatenate and write to Excel
xlswrite(‘f_analysis_results.xlsx’, [f_locations, f_dip_angles]);
% Save results to Excel (only if fs are detected)
if ~isempty(f_locations)
xlswrite(‘f_analysis_results.xlsx’, [f_locations, f_dip_angles]);
else
warning(‘No significant fs detected.’);
endI need to correct figure (3) in the following script to be similar in the attached file (with automatic way)
clc; close all; clear;
% Load the Excel data
filename = ‘ThreeFaultModel_Modified.xlsx’;
data = xlsread(filename, ‘Sheet1’);
% Extract relevant columns
x = data(:, 1); % Distance (x in km)
Field = data(:, 2); % Earth filed (Field in unit)
%==============================================================%
% Input number of layers and densities
num_blocks = input(‘Enter the number of blocks: ‘);
block_densities = zeros(1, num_blocks);
for i = 1:num_blocks
block_densities(i) = input([‘Enter the density of block ‘, num2str(i), ‘ (kg/m^3): ‘]);
end
%==============================================================%
% Constants
G = 0.00676;
Lower_density = 2.67; % in kg/m^3
%==============================================================%
% Calculate inverted depth profile for each layer
z_inv = zeros(length(x), num_blocks);
for i = 1:num_blocks
density_contrast = block_densities(i) – Lower_density;
if density_contrast ~= 0
z_inv(:, i) = Field ./ (2 * pi * G * density_contrast);
else
z_inv(:, i) = NaN; % Avoid division by zero
end
end
%==============================================================%
% Compute vertical gradient (VG) of inverted depth (clean)
VG = diff(z_inv(:, 1)) ./ diff(x);
%==============================================================%
% Set fault threshold and find f indices based on d changes
f_threshold = 0.5; % Threshold for identifying significant d changes
f_indices = find(abs(diff(z_inv(:, 1))) > f_threshold);
%==============================================================%
% Initialize f locations and dip arrays
%==============================================================%
f_locations = x(f_indices); % Automatically determined f locations
f_dip_angles = nan(size(f_indices)); % Placeholder for calculated dip
% Calculate dip for each identified f
for i = 1:length(f_indices)
idx = f_indices(i);
if idx < length(x)
f_dip_angles(i) = atand(abs(z_inv(idx + 1, 1) – z_inv(idx, 1)) / (x(idx + 1) – x(idx)));
else
f_dip_angles(i) = atand(abs(z_inv(idx, 1) – z_inv(idx – 1, 1)) / (x(idx) – x(idx – 1)));
end
end
%==============================================================%
% Displacement of faults
%==============================================================%
D_faults = zeros(size(f_dip_angles));
for i = 1:length(f_indices)
idx = f_indices(i);
dip_angle_rad = deg2rad(f_dip_angles(i)); % Convert dip to radians
D_faults(i) = abs(z_inv(idx + 1, 1) – z_inv(idx, 1)) / sin(dip_angle_rad);
end
% Assign displacement values
D1 = D_faults(1); % NF displacemen
D2 = D_faults(2); % VF displacement
D3 = D_faults(3); % RF displacement
%==============================================================%
% Processing Data for Interpretation
%==============================================================%
A = [x Field z_inv]; % New Data Obtained
col_names = {‘x’, ‘Field’};
for i = 1:num_blocks
col_names{end+1} = [‘z’, num2str(i)];
end
dataM = array2table(A, ‘VariableNames’, col_names);
t1 = dataM;
[nr, nc] = size(t1);
t1_bottoms = t1;
for jj = 3:nc
for ii = 1:nr-1
if t1_bottoms{ii, jj} ~= t1_bottoms{ii+1, jj}
t1_bottoms{ii, jj} = NaN;
end
end
end
%==============================================================%
% Identifying NaN rows
%==============================================================%
nans = isnan(t1_bottoms{:, 3:end});
nan_rows = find(any(nans, 2));
xc = t1_bottoms{nan_rows, 1}; % Corrected x-coordinates
yc = zeros(numel(nan_rows), 1); % y-coordinates for NaN rows
for ii = 1:numel(nan_rows)
idx = find(~nans(nan_rows(ii), :), 1, ‘last’);
if isempty(idx)
yc(ii) = 0;
else
yc(ii) = t1_bottoms{nan_rows(ii), idx+2};
end
end
%==============================================================%
% Plot f Interpretation
%==============================================================%
figure(1)
plot(A(:, 1), A(:, 3:end))
hold on
grid on
set(gca, ‘YDir’, ‘reverse’)
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
title(‘Interpretation of profile data model’)
%==============================================================%
figure(2)
hold on
plot(t1_bottoms{:, 1}, t1_bottoms{:, 3:end}, ‘LineWidth’, 1)
set(gca, ‘YDir’, ‘reverse’)
box on
grid on
xlabel(‘Distance (km)’);
ylabel(‘Ds (km)’);
title(‘New interpretation of profile data’)
%==============================================================%
% Plot the interpreted d profiles
figure(3)
hold on
% Plot the interpreted d profiles
plot(t1_bottoms{:, 1}, t1_bottoms{:, 3:end}, ‘LineWidth’, 1)
yl = get(gca, ‘YLim’); % Get Y-axis limits
% Define f locations and corresponding dip
f_locations = [7.00, 14.00, 23.00];
d_angles = [58.47, 90.00, -69.79];
for ii = 1:numel(f_locations)
% Find the nearest x index for each fault location
[~, idx] = min(abs(t1_bottoms{:, 1} – f_locations(ii)));
% Get the starting x and y coordinates (fault starts at the surface)
x_f = t1_bottoms{idx, 1};
y_f = yl(1); % Start at the surface (0 km depth)
% Check if the dip angle is 90° (vf)
if d_angles(ii) == 90
x_r = [x_f x_f]; % Vertical line
y_r = [yl(1), yl(2)]; % From surface to de limit
else
% Convert dip to slope (m = tan(angle))
m = tand(d_angles(ii));
% Define the x range for fault line
% x_r = linspace(x_f – 5, x_f + 5, 100); % Extend 5 km on each side
x_r = x;
y_r = y_f – m * (x_r – x_f); % Line equation (+ m)
% Clip y_range within the plot limits
y_r(y_r > yl(2)) = yl(2);
y_r(y_r < yl(1)) = yl(1);
end
% Plot the fault lines in black (matching the image)
plot(x_r, y_r, ‘k’, ‘LineWidth’, 3)
% Display dip angles as text near the faults
% text(x_f, y_f + 1, sprintf(‘\theta = %.2f°’, d_angles(ii)), …
% ‘Color’, ‘k’, ‘FontSize’, 10, ‘FontWeight’, ‘bold’, ‘HorizontalAlignment’, ‘right’)
end
set(gca, ‘YDir’, ‘reverse’) % Reverse Y-axis for depth representation
box on
grid on
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
title(‘New Interpretation of Profile Data’)
%==============================================================%
% Plotting results
figure;
subplot(3,1,1);
plot(x, Field, ‘r’, ‘LineWidth’, 2);
title(‘Field Profile’);
xlabel(‘Distance (km)’);
ylabel(‘Field (unit)’);
grid on;
subplot(3,1,2);
plot(x(1:end-1), VG, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Distance (km)’);
ylabel(‘VG (munit/km)’);
title(‘VG Gradient’);
grid on;
subplot(3,1,3);
hold on;
for i = 1:num_blocks
plot(x, z_inv(:, i), ‘LineWidth’, 2);
end
title(‘Inverted D Profile for Each Block’);
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
set(gca, ‘YDir’, ‘reverse’);
grid on;
%==============================================================%
% Display results
fprintf(‘F Analysis Results:n’);
fprintf(‘Location (km) | Dip (degrees) | D_faults (km)n’);
for i = 1:length(f_locations)
fprintf(‘%10.2f | %17.2f | %10.2fn’, f_locations(i), f_dip_angles(i), D_faults(i));
end
% Ensure both variables are column vectors of the same size
f_locations = f_locations(:); % Convert to column vector
f_dip_angles = f_dip_angles(:); % Convert to column vector
% Concatenate and write to Excel
xlswrite(‘f_analysis_results.xlsx’, [f_locations, f_dip_angles]);
% Save results to Excel (only if fs are detected)
if ~isempty(f_locations)
xlswrite(‘f_analysis_results.xlsx’, [f_locations, f_dip_angles]);
else
warning(‘No significant fs detected.’);
end I need to correct figure (3) in the following script to be similar in the attached file (with automatic way)
clc; close all; clear;
% Load the Excel data
filename = ‘ThreeFaultModel_Modified.xlsx’;
data = xlsread(filename, ‘Sheet1’);
% Extract relevant columns
x = data(:, 1); % Distance (x in km)
Field = data(:, 2); % Earth filed (Field in unit)
%==============================================================%
% Input number of layers and densities
num_blocks = input(‘Enter the number of blocks: ‘);
block_densities = zeros(1, num_blocks);
for i = 1:num_blocks
block_densities(i) = input([‘Enter the density of block ‘, num2str(i), ‘ (kg/m^3): ‘]);
end
%==============================================================%
% Constants
G = 0.00676;
Lower_density = 2.67; % in kg/m^3
%==============================================================%
% Calculate inverted depth profile for each layer
z_inv = zeros(length(x), num_blocks);
for i = 1:num_blocks
density_contrast = block_densities(i) – Lower_density;
if density_contrast ~= 0
z_inv(:, i) = Field ./ (2 * pi * G * density_contrast);
else
z_inv(:, i) = NaN; % Avoid division by zero
end
end
%==============================================================%
% Compute vertical gradient (VG) of inverted depth (clean)
VG = diff(z_inv(:, 1)) ./ diff(x);
%==============================================================%
% Set fault threshold and find f indices based on d changes
f_threshold = 0.5; % Threshold for identifying significant d changes
f_indices = find(abs(diff(z_inv(:, 1))) > f_threshold);
%==============================================================%
% Initialize f locations and dip arrays
%==============================================================%
f_locations = x(f_indices); % Automatically determined f locations
f_dip_angles = nan(size(f_indices)); % Placeholder for calculated dip
% Calculate dip for each identified f
for i = 1:length(f_indices)
idx = f_indices(i);
if idx < length(x)
f_dip_angles(i) = atand(abs(z_inv(idx + 1, 1) – z_inv(idx, 1)) / (x(idx + 1) – x(idx)));
else
f_dip_angles(i) = atand(abs(z_inv(idx, 1) – z_inv(idx – 1, 1)) / (x(idx) – x(idx – 1)));
end
end
%==============================================================%
% Displacement of faults
%==============================================================%
D_faults = zeros(size(f_dip_angles));
for i = 1:length(f_indices)
idx = f_indices(i);
dip_angle_rad = deg2rad(f_dip_angles(i)); % Convert dip to radians
D_faults(i) = abs(z_inv(idx + 1, 1) – z_inv(idx, 1)) / sin(dip_angle_rad);
end
% Assign displacement values
D1 = D_faults(1); % NF displacemen
D2 = D_faults(2); % VF displacement
D3 = D_faults(3); % RF displacement
%==============================================================%
% Processing Data for Interpretation
%==============================================================%
A = [x Field z_inv]; % New Data Obtained
col_names = {‘x’, ‘Field’};
for i = 1:num_blocks
col_names{end+1} = [‘z’, num2str(i)];
end
dataM = array2table(A, ‘VariableNames’, col_names);
t1 = dataM;
[nr, nc] = size(t1);
t1_bottoms = t1;
for jj = 3:nc
for ii = 1:nr-1
if t1_bottoms{ii, jj} ~= t1_bottoms{ii+1, jj}
t1_bottoms{ii, jj} = NaN;
end
end
end
%==============================================================%
% Identifying NaN rows
%==============================================================%
nans = isnan(t1_bottoms{:, 3:end});
nan_rows = find(any(nans, 2));
xc = t1_bottoms{nan_rows, 1}; % Corrected x-coordinates
yc = zeros(numel(nan_rows), 1); % y-coordinates for NaN rows
for ii = 1:numel(nan_rows)
idx = find(~nans(nan_rows(ii), :), 1, ‘last’);
if isempty(idx)
yc(ii) = 0;
else
yc(ii) = t1_bottoms{nan_rows(ii), idx+2};
end
end
%==============================================================%
% Plot f Interpretation
%==============================================================%
figure(1)
plot(A(:, 1), A(:, 3:end))
hold on
grid on
set(gca, ‘YDir’, ‘reverse’)
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
title(‘Interpretation of profile data model’)
%==============================================================%
figure(2)
hold on
plot(t1_bottoms{:, 1}, t1_bottoms{:, 3:end}, ‘LineWidth’, 1)
set(gca, ‘YDir’, ‘reverse’)
box on
grid on
xlabel(‘Distance (km)’);
ylabel(‘Ds (km)’);
title(‘New interpretation of profile data’)
%==============================================================%
% Plot the interpreted d profiles
figure(3)
hold on
% Plot the interpreted d profiles
plot(t1_bottoms{:, 1}, t1_bottoms{:, 3:end}, ‘LineWidth’, 1)
yl = get(gca, ‘YLim’); % Get Y-axis limits
% Define f locations and corresponding dip
f_locations = [7.00, 14.00, 23.00];
d_angles = [58.47, 90.00, -69.79];
for ii = 1:numel(f_locations)
% Find the nearest x index for each fault location
[~, idx] = min(abs(t1_bottoms{:, 1} – f_locations(ii)));
% Get the starting x and y coordinates (fault starts at the surface)
x_f = t1_bottoms{idx, 1};
y_f = yl(1); % Start at the surface (0 km depth)
% Check if the dip angle is 90° (vf)
if d_angles(ii) == 90
x_r = [x_f x_f]; % Vertical line
y_r = [yl(1), yl(2)]; % From surface to de limit
else
% Convert dip to slope (m = tan(angle))
m = tand(d_angles(ii));
% Define the x range for fault line
% x_r = linspace(x_f – 5, x_f + 5, 100); % Extend 5 km on each side
x_r = x;
y_r = y_f – m * (x_r – x_f); % Line equation (+ m)
% Clip y_range within the plot limits
y_r(y_r > yl(2)) = yl(2);
y_r(y_r < yl(1)) = yl(1);
end
% Plot the fault lines in black (matching the image)
plot(x_r, y_r, ‘k’, ‘LineWidth’, 3)
% Display dip angles as text near the faults
% text(x_f, y_f + 1, sprintf(‘\theta = %.2f°’, d_angles(ii)), …
% ‘Color’, ‘k’, ‘FontSize’, 10, ‘FontWeight’, ‘bold’, ‘HorizontalAlignment’, ‘right’)
end
set(gca, ‘YDir’, ‘reverse’) % Reverse Y-axis for depth representation
box on
grid on
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
title(‘New Interpretation of Profile Data’)
%==============================================================%
% Plotting results
figure;
subplot(3,1,1);
plot(x, Field, ‘r’, ‘LineWidth’, 2);
title(‘Field Profile’);
xlabel(‘Distance (km)’);
ylabel(‘Field (unit)’);
grid on;
subplot(3,1,2);
plot(x(1:end-1), VG, ‘b’, ‘LineWidth’, 1.5);
xlabel(‘Distance (km)’);
ylabel(‘VG (munit/km)’);
title(‘VG Gradient’);
grid on;
subplot(3,1,3);
hold on;
for i = 1:num_blocks
plot(x, z_inv(:, i), ‘LineWidth’, 2);
end
title(‘Inverted D Profile for Each Block’);
xlabel(‘Distance (km)’);
ylabel(‘D (km)’);
set(gca, ‘YDir’, ‘reverse’);
grid on;
%==============================================================%
% Display results
fprintf(‘F Analysis Results:n’);
fprintf(‘Location (km) | Dip (degrees) | D_faults (km)n’);
for i = 1:length(f_locations)
fprintf(‘%10.2f | %17.2f | %10.2fn’, f_locations(i), f_dip_angles(i), D_faults(i));
end
% Ensure both variables are column vectors of the same size
f_locations = f_locations(:); % Convert to column vector
f_dip_angles = f_dip_angles(:); % Convert to column vector
% Concatenate and write to Excel
xlswrite(‘f_analysis_results.xlsx’, [f_locations, f_dip_angles]);
% Save results to Excel (only if fs are detected)
if ~isempty(f_locations)
xlswrite(‘f_analysis_results.xlsx’, [f_locations, f_dip_angles]);
else
warning(‘No significant fs detected.’);
end horizontal shift, vertical shift, diagonal shift MATLAB Answers — New Questions
Regarding grid generation using finite difference method (*code fixed)
Hi everyone,
I’m trying to generate a uniform grid where the red lines intersect at a 45-degree angle to the horizontal lines in blue using the finite difference method in MATLAB.
However, the resulting grid is slightly off, as shown in the attached image. Intesection angle is uniform but higher than 45-degree.
I set computational domain as and a grid is generated on physical domain with coordinates .
As I want to generate a mesh described above, I aimed to solve the following PDE :
where we have (horizontal lines). The boundary conditions are .
The above equation comes down to the following:
Based on the above equation, I discretized to finite difference form (central difference for and forward differece for ).
Plus, I found the grid collapses when I set different angles (for example 90-degree (replace )).
Am I missing something in implementation?
I need your help.
Here is my code.
% Parameter settings
eta_max = 10;
xi_max = 10;
Delta_eta = 0.1;
Delta_xi = 0.1;
tol = 1e-6;
max_iterations = 100000;
% Grid size
eta_steps = floor(eta_max / Delta_eta) + 1;
xi_steps = floor(xi_max / Delta_xi) + 1;
% Initial conditions
x = zeros(eta_steps, xi_steps);
y = repmat((0:eta_steps-1)’ * Delta_eta, 1, xi_steps);
% Boundary conditions
x(1, 🙂 = linspace(0, xi_max, xi_steps);
% Finite difference method
converged = false;
iteration = 0;
while ~converged && iteration < max_iterations
iteration = iteration + 1;
max_error = 0;
for n = 1:eta_steps – 1
for m = 2:xi_steps – 1
x_xi = (x(n, m+1) – x(n, m-1)) / (2 * Delta_xi);
y_xi = (y(n, m+1) – y(n, m-1)) / (2 * Delta_xi);
new_x = x(n, m) + Delta_eta * ((pi/4) – y_xi)/(x_xi);
error_x = abs(new_x – x(n, m));
max_error = max([max_error, error_x]);
x(n + 1, m) = new_x;
end
x(n+1, xi_steps) = x(n+1, xi_steps-1) + Delta_xi;
x(n+1, 1) = x(n+1, 2) – Delta_xi;
end
if max_error < tol
converged = true;
end
end
% Plot the results
figure; hold on; axis equal; grid on;
for m = 1:xi_steps
plot(x(:, m), y(:, m), ‘r’);
end
for n = 1:eta_steps
plot(x(n, :), y(n, :), ‘b’);
end
title([‘Iterations until convergence: ‘, num2str(iteration)]);
xlabel(‘x’); ylabel(‘y’);Hi everyone,
I’m trying to generate a uniform grid where the red lines intersect at a 45-degree angle to the horizontal lines in blue using the finite difference method in MATLAB.
However, the resulting grid is slightly off, as shown in the attached image. Intesection angle is uniform but higher than 45-degree.
I set computational domain as and a grid is generated on physical domain with coordinates .
As I want to generate a mesh described above, I aimed to solve the following PDE :
where we have (horizontal lines). The boundary conditions are .
The above equation comes down to the following:
Based on the above equation, I discretized to finite difference form (central difference for and forward differece for ).
Plus, I found the grid collapses when I set different angles (for example 90-degree (replace )).
Am I missing something in implementation?
I need your help.
Here is my code.
% Parameter settings
eta_max = 10;
xi_max = 10;
Delta_eta = 0.1;
Delta_xi = 0.1;
tol = 1e-6;
max_iterations = 100000;
% Grid size
eta_steps = floor(eta_max / Delta_eta) + 1;
xi_steps = floor(xi_max / Delta_xi) + 1;
% Initial conditions
x = zeros(eta_steps, xi_steps);
y = repmat((0:eta_steps-1)’ * Delta_eta, 1, xi_steps);
% Boundary conditions
x(1, 🙂 = linspace(0, xi_max, xi_steps);
% Finite difference method
converged = false;
iteration = 0;
while ~converged && iteration < max_iterations
iteration = iteration + 1;
max_error = 0;
for n = 1:eta_steps – 1
for m = 2:xi_steps – 1
x_xi = (x(n, m+1) – x(n, m-1)) / (2 * Delta_xi);
y_xi = (y(n, m+1) – y(n, m-1)) / (2 * Delta_xi);
new_x = x(n, m) + Delta_eta * ((pi/4) – y_xi)/(x_xi);
error_x = abs(new_x – x(n, m));
max_error = max([max_error, error_x]);
x(n + 1, m) = new_x;
end
x(n+1, xi_steps) = x(n+1, xi_steps-1) + Delta_xi;
x(n+1, 1) = x(n+1, 2) – Delta_xi;
end
if max_error < tol
converged = true;
end
end
% Plot the results
figure; hold on; axis equal; grid on;
for m = 1:xi_steps
plot(x(:, m), y(:, m), ‘r’);
end
for n = 1:eta_steps
plot(x(n, :), y(n, :), ‘b’);
end
title([‘Iterations until convergence: ‘, num2str(iteration)]);
xlabel(‘x’); ylabel(‘y’); Hi everyone,
I’m trying to generate a uniform grid where the red lines intersect at a 45-degree angle to the horizontal lines in blue using the finite difference method in MATLAB.
However, the resulting grid is slightly off, as shown in the attached image. Intesection angle is uniform but higher than 45-degree.
I set computational domain as and a grid is generated on physical domain with coordinates .
As I want to generate a mesh described above, I aimed to solve the following PDE :
where we have (horizontal lines). The boundary conditions are .
The above equation comes down to the following:
Based on the above equation, I discretized to finite difference form (central difference for and forward differece for ).
Plus, I found the grid collapses when I set different angles (for example 90-degree (replace )).
Am I missing something in implementation?
I need your help.
Here is my code.
% Parameter settings
eta_max = 10;
xi_max = 10;
Delta_eta = 0.1;
Delta_xi = 0.1;
tol = 1e-6;
max_iterations = 100000;
% Grid size
eta_steps = floor(eta_max / Delta_eta) + 1;
xi_steps = floor(xi_max / Delta_xi) + 1;
% Initial conditions
x = zeros(eta_steps, xi_steps);
y = repmat((0:eta_steps-1)’ * Delta_eta, 1, xi_steps);
% Boundary conditions
x(1, 🙂 = linspace(0, xi_max, xi_steps);
% Finite difference method
converged = false;
iteration = 0;
while ~converged && iteration < max_iterations
iteration = iteration + 1;
max_error = 0;
for n = 1:eta_steps – 1
for m = 2:xi_steps – 1
x_xi = (x(n, m+1) – x(n, m-1)) / (2 * Delta_xi);
y_xi = (y(n, m+1) – y(n, m-1)) / (2 * Delta_xi);
new_x = x(n, m) + Delta_eta * ((pi/4) – y_xi)/(x_xi);
error_x = abs(new_x – x(n, m));
max_error = max([max_error, error_x]);
x(n + 1, m) = new_x;
end
x(n+1, xi_steps) = x(n+1, xi_steps-1) + Delta_xi;
x(n+1, 1) = x(n+1, 2) – Delta_xi;
end
if max_error < tol
converged = true;
end
end
% Plot the results
figure; hold on; axis equal; grid on;
for m = 1:xi_steps
plot(x(:, m), y(:, m), ‘r’);
end
for n = 1:eta_steps
plot(x(n, :), y(n, :), ‘b’);
end
title([‘Iterations until convergence: ‘, num2str(iteration)]);
xlabel(‘x’); ylabel(‘y’); finite difference method, grid generation, mesh generation, numerical analysis, differential equations MATLAB Answers — New Questions
Matlab throwing an error in the sign in window
I installed MATLAB R2024b and on opening it, the sign in window is showing the following. I have 2023a installed and it is working fine but I am not able to open 2024b due to this. Please help!I installed MATLAB R2024b and on opening it, the sign in window is showing the following. I have 2023a installed and it is working fine but I am not able to open 2024b due to this. Please help! I installed MATLAB R2024b and on opening it, the sign in window is showing the following. I have 2023a installed and it is working fine but I am not able to open 2024b due to this. Please help! sign-in MATLAB Answers — New Questions
Why numerical solutions is not consistent with the exact solutions?
Why numerical solutions is not consistent with the exact solutions? Also the error is too large. How to modify the code to get consistent results? See the attached image for the equation of motions and their exact solutions.
clear; clc;
tic;
c1 = 0; % real constant
c2 = 0; % real constant
a = 1; % real constant
b=0.1; % two values b=0.1, b=0.01
lambda = -1./(2*(1 + 1i)); % complex or imaginary
N = 1000;
X = linspace(-10, 10, N);
T = linspace(0, 10, N);
% Calculate initial conditions
[x, ~] = meshgrid(X, 0); % t = 0 for initial conditions
%psi_init = A * exp(-1i * lambda * x);
%phi_init = B * exp(1i * lambda * x);
nq_init = -a*(b.^5*(1+(0 + c2).^2).^2 – 8*a*(0+c2).*(x+c1) – 4*a*b.^4*(0+c2).*(1+(0+c2).^2).*(x+c1) – 4*a*b.^2*(0+c2).*(x+c1).*(3+(0+c2).^2 + a.^2*(x+c1).^2) + b*(-3+(0+c2).^4 + 6*a.^2*(x+c1).^2 + a.^4*(x+c1).^4 + 2*(0+c2).^2.*(3 + a.^2*(x+c1).^2)) + 2*b.^3*(-1 + (0+c2).^4 + a.^2*(x+c1).^2 + (0+c2).^2*(4 + 3*a.^2*(x+c1).^2)));
dq_init = 1 + (0 + c2).^2 + b.^2 + (b*(0 + c2) + a*(x + c1)).^2;
q_init = (nq_init ./ (dq_init .^ 2));
ns_init = -(-3 + (0 + c2).^2 + b.^2*(-3 + (0 + c2).^2) + 4*1i*a*(x+c1) – 2*a*b*(0 + c2).*(x+c1) + a.^2*(x+c1).^2).*(exp(1i*(a*x + b*0)));
s_init = ns_init ./ dq_init;
initial_conditions = [q_init(:); s_init(:)];
t_span = T;
% Solve the differential equation numerically
options = odeset(‘RelTol’, 1e-4, ‘AbsTol’, 1e-8);
[t, u] = ode45(@(t, u) dydt(t, u, N), t_span, initial_conditions, options);
% Extract q and s from the solution
q = reshape(u(:, 1:N), [length(t), N]);
s = reshape(u(:, N+1:end), [length(t), N]);
% Calculate the exact solution over the mesh grid
[x, t] = meshgrid(X, T);
nq = -a*(b.^5*(1+(t + c2).^2).^2 – 8*a*(t+c2).*(x+c1) – 4*a*b.^4*(t+c2).*(1+(t+c2).^2).*(x+c1) – 4*a*b.^2*(t+c2).*(x+c1).*(3+(t+c2).^2 + a.^2*(x+c1).^2) + b*(-3+(t+c2).^4 + 6*a.^2*(x+c1).^2 + a.^4*(x+c1).^4 + 2*(t+c2).^2.*(3 + a.^2*(x+c1).^2)) + 2*b.^3*(-1 + (t+c2).^4 + a.^2*(x+c1).^2 + (t+c2).^2*(4 + 3*a.^2*(x+c1).^2)));
dq = 1 + (t + c2).^2 + b.^2 + (b*(t + c2) + a*(x + c1)).^2;
ns = -(-3 + (t + c2).^2 + b.^2*(-3 + (t + c2).^2) + 4*1i*a*(x+c1) – 2*a*b*(t + c2).*(x+c1) + a.^2*(x+c1).^2).*(exp(1i*(a*x + b*0)));
exact_q = (nq ./ (dq .^ 2));
exact_s = ns ./ dq;
% Compute the error
error_q = abs(q’ – exact_q);
error_s = abs(s’ – exact_s);
% Plotting the numerical solution
figure;
subplot(2, 1, 1);
surf(t, x, abs(q’));
title(‘Numerical Solution for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|q_{n+1} – q_n|’);
shading interp;
subplot(2, 1, 2);
surf(t, x, abs(s’));
title(‘Numerical Solution for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|s_{n+1} – s_n|’);
shading interp;
% 3D surface plot for exact solution
figure;
subplot(2, 1, 1);
surf(t, x, abs(exact_q’));
title(‘Exact Solution for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|q_{n+1} – q_n|’);
shading interp;
subplot(2, 1, 2);
surf(t, x, abs(exact_s’));
title(‘Exact Solution for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|s_{n+1} – s_n|’);
shading interp;
% Plot the error
figure;
subplot(2, 1, 1);
surf(t, x, error_q’);
title(‘Error for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘Error’);
shading interp;
subplot(2, 1, 2);
surf(t, x, error_s’);
title(‘Error for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘Error’);
shading interp;
% 2D error plot at specific times
figure;
times_to_plot = [0, 5, 10]; % Example times to plot error
for i = 1:length(times_to_plot)
time_idx = find(t_span >= times_to_plot(i), 1);
subplot(length(times_to_plot), 1, i);
plot(X, error_q(:, time_idx), ‘r’, X, error_s(:, time_idx), ‘b’);
title([‘Error at t = ‘, num2str(times_to_plot(i))]);
xlabel(‘x’);
ylabel(‘Error’);
legend(‘|q_{n+1} – q_n| Error’, ‘|s_{n+1} – s_n| Error’);
end
% Generate error table for fixed times from 0 to 10 in increments of 0.5
fixed_times = 0:0.5:10;
error_table_q = zeros(length(fixed_times), 1);
error_table_s = zeros(length(fixed_times), 1);
for i = 1:length(fixed_times)
time_idx = find(t_span >= fixed_times(i), 1);
error_table_q(i) = mean(error_q(:, time_idx));
error_table_s(i) = mean(error_s(:, time_idx));
end
% Display the error table
error_table = table(fixed_times’, error_table_q, error_table_s, …
‘VariableNames’, {‘Time’, ‘Error_q’, ‘Error_s’});
disp(error_table);
toc;
function dydt = dydt(~, u, N)
dydt = zeros(2*N, 1);
q = u(1:N);
s = u(N+1:2*N);
% Handle boundary conditions
for n = 3:N-2
dydt(n) = 1/2 * s(n) * conj(s(n)) – 1/2 * s(n+1) * conj(s(n+1));
dydt(N+n) = 1/2 * (q(n+1) – q(n)) * (s(n+1) – s(n));
end
endWhy numerical solutions is not consistent with the exact solutions? Also the error is too large. How to modify the code to get consistent results? See the attached image for the equation of motions and their exact solutions.
clear; clc;
tic;
c1 = 0; % real constant
c2 = 0; % real constant
a = 1; % real constant
b=0.1; % two values b=0.1, b=0.01
lambda = -1./(2*(1 + 1i)); % complex or imaginary
N = 1000;
X = linspace(-10, 10, N);
T = linspace(0, 10, N);
% Calculate initial conditions
[x, ~] = meshgrid(X, 0); % t = 0 for initial conditions
%psi_init = A * exp(-1i * lambda * x);
%phi_init = B * exp(1i * lambda * x);
nq_init = -a*(b.^5*(1+(0 + c2).^2).^2 – 8*a*(0+c2).*(x+c1) – 4*a*b.^4*(0+c2).*(1+(0+c2).^2).*(x+c1) – 4*a*b.^2*(0+c2).*(x+c1).*(3+(0+c2).^2 + a.^2*(x+c1).^2) + b*(-3+(0+c2).^4 + 6*a.^2*(x+c1).^2 + a.^4*(x+c1).^4 + 2*(0+c2).^2.*(3 + a.^2*(x+c1).^2)) + 2*b.^3*(-1 + (0+c2).^4 + a.^2*(x+c1).^2 + (0+c2).^2*(4 + 3*a.^2*(x+c1).^2)));
dq_init = 1 + (0 + c2).^2 + b.^2 + (b*(0 + c2) + a*(x + c1)).^2;
q_init = (nq_init ./ (dq_init .^ 2));
ns_init = -(-3 + (0 + c2).^2 + b.^2*(-3 + (0 + c2).^2) + 4*1i*a*(x+c1) – 2*a*b*(0 + c2).*(x+c1) + a.^2*(x+c1).^2).*(exp(1i*(a*x + b*0)));
s_init = ns_init ./ dq_init;
initial_conditions = [q_init(:); s_init(:)];
t_span = T;
% Solve the differential equation numerically
options = odeset(‘RelTol’, 1e-4, ‘AbsTol’, 1e-8);
[t, u] = ode45(@(t, u) dydt(t, u, N), t_span, initial_conditions, options);
% Extract q and s from the solution
q = reshape(u(:, 1:N), [length(t), N]);
s = reshape(u(:, N+1:end), [length(t), N]);
% Calculate the exact solution over the mesh grid
[x, t] = meshgrid(X, T);
nq = -a*(b.^5*(1+(t + c2).^2).^2 – 8*a*(t+c2).*(x+c1) – 4*a*b.^4*(t+c2).*(1+(t+c2).^2).*(x+c1) – 4*a*b.^2*(t+c2).*(x+c1).*(3+(t+c2).^2 + a.^2*(x+c1).^2) + b*(-3+(t+c2).^4 + 6*a.^2*(x+c1).^2 + a.^4*(x+c1).^4 + 2*(t+c2).^2.*(3 + a.^2*(x+c1).^2)) + 2*b.^3*(-1 + (t+c2).^4 + a.^2*(x+c1).^2 + (t+c2).^2*(4 + 3*a.^2*(x+c1).^2)));
dq = 1 + (t + c2).^2 + b.^2 + (b*(t + c2) + a*(x + c1)).^2;
ns = -(-3 + (t + c2).^2 + b.^2*(-3 + (t + c2).^2) + 4*1i*a*(x+c1) – 2*a*b*(t + c2).*(x+c1) + a.^2*(x+c1).^2).*(exp(1i*(a*x + b*0)));
exact_q = (nq ./ (dq .^ 2));
exact_s = ns ./ dq;
% Compute the error
error_q = abs(q’ – exact_q);
error_s = abs(s’ – exact_s);
% Plotting the numerical solution
figure;
subplot(2, 1, 1);
surf(t, x, abs(q’));
title(‘Numerical Solution for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|q_{n+1} – q_n|’);
shading interp;
subplot(2, 1, 2);
surf(t, x, abs(s’));
title(‘Numerical Solution for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|s_{n+1} – s_n|’);
shading interp;
% 3D surface plot for exact solution
figure;
subplot(2, 1, 1);
surf(t, x, abs(exact_q’));
title(‘Exact Solution for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|q_{n+1} – q_n|’);
shading interp;
subplot(2, 1, 2);
surf(t, x, abs(exact_s’));
title(‘Exact Solution for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|s_{n+1} – s_n|’);
shading interp;
% Plot the error
figure;
subplot(2, 1, 1);
surf(t, x, error_q’);
title(‘Error for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘Error’);
shading interp;
subplot(2, 1, 2);
surf(t, x, error_s’);
title(‘Error for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘Error’);
shading interp;
% 2D error plot at specific times
figure;
times_to_plot = [0, 5, 10]; % Example times to plot error
for i = 1:length(times_to_plot)
time_idx = find(t_span >= times_to_plot(i), 1);
subplot(length(times_to_plot), 1, i);
plot(X, error_q(:, time_idx), ‘r’, X, error_s(:, time_idx), ‘b’);
title([‘Error at t = ‘, num2str(times_to_plot(i))]);
xlabel(‘x’);
ylabel(‘Error’);
legend(‘|q_{n+1} – q_n| Error’, ‘|s_{n+1} – s_n| Error’);
end
% Generate error table for fixed times from 0 to 10 in increments of 0.5
fixed_times = 0:0.5:10;
error_table_q = zeros(length(fixed_times), 1);
error_table_s = zeros(length(fixed_times), 1);
for i = 1:length(fixed_times)
time_idx = find(t_span >= fixed_times(i), 1);
error_table_q(i) = mean(error_q(:, time_idx));
error_table_s(i) = mean(error_s(:, time_idx));
end
% Display the error table
error_table = table(fixed_times’, error_table_q, error_table_s, …
‘VariableNames’, {‘Time’, ‘Error_q’, ‘Error_s’});
disp(error_table);
toc;
function dydt = dydt(~, u, N)
dydt = zeros(2*N, 1);
q = u(1:N);
s = u(N+1:2*N);
% Handle boundary conditions
for n = 3:N-2
dydt(n) = 1/2 * s(n) * conj(s(n)) – 1/2 * s(n+1) * conj(s(n+1));
dydt(N+n) = 1/2 * (q(n+1) – q(n)) * (s(n+1) – s(n));
end
end Why numerical solutions is not consistent with the exact solutions? Also the error is too large. How to modify the code to get consistent results? See the attached image for the equation of motions and their exact solutions.
clear; clc;
tic;
c1 = 0; % real constant
c2 = 0; % real constant
a = 1; % real constant
b=0.1; % two values b=0.1, b=0.01
lambda = -1./(2*(1 + 1i)); % complex or imaginary
N = 1000;
X = linspace(-10, 10, N);
T = linspace(0, 10, N);
% Calculate initial conditions
[x, ~] = meshgrid(X, 0); % t = 0 for initial conditions
%psi_init = A * exp(-1i * lambda * x);
%phi_init = B * exp(1i * lambda * x);
nq_init = -a*(b.^5*(1+(0 + c2).^2).^2 – 8*a*(0+c2).*(x+c1) – 4*a*b.^4*(0+c2).*(1+(0+c2).^2).*(x+c1) – 4*a*b.^2*(0+c2).*(x+c1).*(3+(0+c2).^2 + a.^2*(x+c1).^2) + b*(-3+(0+c2).^4 + 6*a.^2*(x+c1).^2 + a.^4*(x+c1).^4 + 2*(0+c2).^2.*(3 + a.^2*(x+c1).^2)) + 2*b.^3*(-1 + (0+c2).^4 + a.^2*(x+c1).^2 + (0+c2).^2*(4 + 3*a.^2*(x+c1).^2)));
dq_init = 1 + (0 + c2).^2 + b.^2 + (b*(0 + c2) + a*(x + c1)).^2;
q_init = (nq_init ./ (dq_init .^ 2));
ns_init = -(-3 + (0 + c2).^2 + b.^2*(-3 + (0 + c2).^2) + 4*1i*a*(x+c1) – 2*a*b*(0 + c2).*(x+c1) + a.^2*(x+c1).^2).*(exp(1i*(a*x + b*0)));
s_init = ns_init ./ dq_init;
initial_conditions = [q_init(:); s_init(:)];
t_span = T;
% Solve the differential equation numerically
options = odeset(‘RelTol’, 1e-4, ‘AbsTol’, 1e-8);
[t, u] = ode45(@(t, u) dydt(t, u, N), t_span, initial_conditions, options);
% Extract q and s from the solution
q = reshape(u(:, 1:N), [length(t), N]);
s = reshape(u(:, N+1:end), [length(t), N]);
% Calculate the exact solution over the mesh grid
[x, t] = meshgrid(X, T);
nq = -a*(b.^5*(1+(t + c2).^2).^2 – 8*a*(t+c2).*(x+c1) – 4*a*b.^4*(t+c2).*(1+(t+c2).^2).*(x+c1) – 4*a*b.^2*(t+c2).*(x+c1).*(3+(t+c2).^2 + a.^2*(x+c1).^2) + b*(-3+(t+c2).^4 + 6*a.^2*(x+c1).^2 + a.^4*(x+c1).^4 + 2*(t+c2).^2.*(3 + a.^2*(x+c1).^2)) + 2*b.^3*(-1 + (t+c2).^4 + a.^2*(x+c1).^2 + (t+c2).^2*(4 + 3*a.^2*(x+c1).^2)));
dq = 1 + (t + c2).^2 + b.^2 + (b*(t + c2) + a*(x + c1)).^2;
ns = -(-3 + (t + c2).^2 + b.^2*(-3 + (t + c2).^2) + 4*1i*a*(x+c1) – 2*a*b*(t + c2).*(x+c1) + a.^2*(x+c1).^2).*(exp(1i*(a*x + b*0)));
exact_q = (nq ./ (dq .^ 2));
exact_s = ns ./ dq;
% Compute the error
error_q = abs(q’ – exact_q);
error_s = abs(s’ – exact_s);
% Plotting the numerical solution
figure;
subplot(2, 1, 1);
surf(t, x, abs(q’));
title(‘Numerical Solution for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|q_{n+1} – q_n|’);
shading interp;
subplot(2, 1, 2);
surf(t, x, abs(s’));
title(‘Numerical Solution for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|s_{n+1} – s_n|’);
shading interp;
% 3D surface plot for exact solution
figure;
subplot(2, 1, 1);
surf(t, x, abs(exact_q’));
title(‘Exact Solution for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|q_{n+1} – q_n|’);
shading interp;
subplot(2, 1, 2);
surf(t, x, abs(exact_s’));
title(‘Exact Solution for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘|s_{n+1} – s_n|’);
shading interp;
% Plot the error
figure;
subplot(2, 1, 1);
surf(t, x, error_q’);
title(‘Error for |q_{n+1} – q_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘Error’);
shading interp;
subplot(2, 1, 2);
surf(t, x, error_s’);
title(‘Error for |s_{n+1} – s_n|’);
xlabel(‘t’);
ylabel(‘x’);
zlabel(‘Error’);
shading interp;
% 2D error plot at specific times
figure;
times_to_plot = [0, 5, 10]; % Example times to plot error
for i = 1:length(times_to_plot)
time_idx = find(t_span >= times_to_plot(i), 1);
subplot(length(times_to_plot), 1, i);
plot(X, error_q(:, time_idx), ‘r’, X, error_s(:, time_idx), ‘b’);
title([‘Error at t = ‘, num2str(times_to_plot(i))]);
xlabel(‘x’);
ylabel(‘Error’);
legend(‘|q_{n+1} – q_n| Error’, ‘|s_{n+1} – s_n| Error’);
end
% Generate error table for fixed times from 0 to 10 in increments of 0.5
fixed_times = 0:0.5:10;
error_table_q = zeros(length(fixed_times), 1);
error_table_s = zeros(length(fixed_times), 1);
for i = 1:length(fixed_times)
time_idx = find(t_span >= fixed_times(i), 1);
error_table_q(i) = mean(error_q(:, time_idx));
error_table_s(i) = mean(error_s(:, time_idx));
end
% Display the error table
error_table = table(fixed_times’, error_table_q, error_table_s, …
‘VariableNames’, {‘Time’, ‘Error_q’, ‘Error_s’});
disp(error_table);
toc;
function dydt = dydt(~, u, N)
dydt = zeros(2*N, 1);
q = u(1:N);
s = u(N+1:2*N);
% Handle boundary conditions
for n = 3:N-2
dydt(n) = 1/2 * s(n) * conj(s(n)) – 1/2 * s(n+1) * conj(s(n+1));
dydt(N+n) = 1/2 * (q(n+1) – q(n)) * (s(n+1) – s(n));
end
end ode45, numerical integration, differential equations MATLAB Answers — New Questions
How do I remove the colored area on a part of the map?
How can I remove the colored fill (make it white) outside the selected polygon?How can I remove the colored fill (make it white) outside the selected polygon? How can I remove the colored fill (make it white) outside the selected polygon? map, masking, mask image MATLAB Answers — New Questions
Help with getting data from image at equidistant positions from the centre – to include the “off circle corners”
Hello, I have an image and I want to get the median of data at each radius value. This is shown by the yellow circles – so each circle (take the median of all pixels on it).
However, in my attemy, I missing all the corners of data that are actually at a larger radius than the image size, but not full circles. Any suggestions how to include this data.
This was my attempt:
% 1st draw circle of radius R on the flog2 plot
theta = linspace(0,360); %use n=121 for every 3 degrees (reduce from every degree for speed
centre = [cx,cy]; %circle centre
% I= Image
[X,Y]=ndgrid(1:size(I,1),1:size(I,2));
X=X-cx;Y=Y-cy;%shift coordinate grid
hold(ax1,"on");
data=[];
for i=1:cy-1
radius=i; %circle radius
data(i,1)=i;
y = radius*sind(theta)+centre(2);
x = radius*cosd(theta)+centre(1);
%Get Data on radius
L=sqrt(X.^2+Y.^2)==radius;
data(i,2) = median(I(L));
if mod(i,5)==0
plot(ax1,x,y,’y’); %draw circle
end
% Now use interp so use all pixels on circle. This is
% actually what I finally use now
[xx,yy]=pol2cart(theta,radius); % this is for the interp2 approach
x=xx+cx; y=yy+cy;
vals=median(interp2(I,x,y));
data(i,3)=vals;
end
% Now plot data
hold(ax2,"on");
plot(ax2,data(:,1),data(:,3),’y-‘,’LineWidth’,3);Hello, I have an image and I want to get the median of data at each radius value. This is shown by the yellow circles – so each circle (take the median of all pixels on it).
However, in my attemy, I missing all the corners of data that are actually at a larger radius than the image size, but not full circles. Any suggestions how to include this data.
This was my attempt:
% 1st draw circle of radius R on the flog2 plot
theta = linspace(0,360); %use n=121 for every 3 degrees (reduce from every degree for speed
centre = [cx,cy]; %circle centre
% I= Image
[X,Y]=ndgrid(1:size(I,1),1:size(I,2));
X=X-cx;Y=Y-cy;%shift coordinate grid
hold(ax1,"on");
data=[];
for i=1:cy-1
radius=i; %circle radius
data(i,1)=i;
y = radius*sind(theta)+centre(2);
x = radius*cosd(theta)+centre(1);
%Get Data on radius
L=sqrt(X.^2+Y.^2)==radius;
data(i,2) = median(I(L));
if mod(i,5)==0
plot(ax1,x,y,’y’); %draw circle
end
% Now use interp so use all pixels on circle. This is
% actually what I finally use now
[xx,yy]=pol2cart(theta,radius); % this is for the interp2 approach
x=xx+cx; y=yy+cy;
vals=median(interp2(I,x,y));
data(i,3)=vals;
end
% Now plot data
hold(ax2,"on");
plot(ax2,data(:,1),data(:,3),’y-‘,’LineWidth’,3); Hello, I have an image and I want to get the median of data at each radius value. This is shown by the yellow circles – so each circle (take the median of all pixels on it).
However, in my attemy, I missing all the corners of data that are actually at a larger radius than the image size, but not full circles. Any suggestions how to include this data.
This was my attempt:
% 1st draw circle of radius R on the flog2 plot
theta = linspace(0,360); %use n=121 for every 3 degrees (reduce from every degree for speed
centre = [cx,cy]; %circle centre
% I= Image
[X,Y]=ndgrid(1:size(I,1),1:size(I,2));
X=X-cx;Y=Y-cy;%shift coordinate grid
hold(ax1,"on");
data=[];
for i=1:cy-1
radius=i; %circle radius
data(i,1)=i;
y = radius*sind(theta)+centre(2);
x = radius*cosd(theta)+centre(1);
%Get Data on radius
L=sqrt(X.^2+Y.^2)==radius;
data(i,2) = median(I(L));
if mod(i,5)==0
plot(ax1,x,y,’y’); %draw circle
end
% Now use interp so use all pixels on circle. This is
% actually what I finally use now
[xx,yy]=pol2cart(theta,radius); % this is for the interp2 approach
x=xx+cx; y=yy+cy;
vals=median(interp2(I,x,y));
data(i,3)=vals;
end
% Now plot data
hold(ax2,"on");
plot(ax2,data(:,1),data(:,3),’y-‘,’LineWidth’,3); image, ngrid, pol2cart MATLAB Answers — New Questions
In a (possibly directed) graph, is there a simple way to find all nodes reachable for a given node?
I’ve recently started working with MATLAB graphs. In two recent problems, I have graphs which are not known to be connected every node to every other node. Is there a way to determine in one or a known number of steps, the set of nodes which can (or cannot would work) be reached from a specified node? I’ve encountered this question both with undirected (small, and I powered through) and now undirected nodes.
Just in case I’m in asking an XY question, my current directed graph is entirely unidirectional; there are no closed loops. I could trivially assign a value to each node, and know that every edge leads to a node with a strictly larger value than the node it leads from. To be even more specific if it helps, though I definitely don’t know the proper math language: the graph represents a double elimination playoff bracket, and I want to put together the possible routes for each seed on a plot to guide teams through the process, pruning out things that don’t matter to that team. Fortunately in this case, the graph is deterministic; no re-seeding occurs due to match outcomes, making such a plot useful.
My previous issue, which was small so I powered through, had an undirected graph, and I really just wanted to know whether or not the graph was continuous; that is, whether every node pair was connected by some path.I’ve recently started working with MATLAB graphs. In two recent problems, I have graphs which are not known to be connected every node to every other node. Is there a way to determine in one or a known number of steps, the set of nodes which can (or cannot would work) be reached from a specified node? I’ve encountered this question both with undirected (small, and I powered through) and now undirected nodes.
Just in case I’m in asking an XY question, my current directed graph is entirely unidirectional; there are no closed loops. I could trivially assign a value to each node, and know that every edge leads to a node with a strictly larger value than the node it leads from. To be even more specific if it helps, though I definitely don’t know the proper math language: the graph represents a double elimination playoff bracket, and I want to put together the possible routes for each seed on a plot to guide teams through the process, pruning out things that don’t matter to that team. Fortunately in this case, the graph is deterministic; no re-seeding occurs due to match outcomes, making such a plot useful.
My previous issue, which was small so I powered through, had an undirected graph, and I really just wanted to know whether or not the graph was continuous; that is, whether every node pair was connected by some path. I’ve recently started working with MATLAB graphs. In two recent problems, I have graphs which are not known to be connected every node to every other node. Is there a way to determine in one or a known number of steps, the set of nodes which can (or cannot would work) be reached from a specified node? I’ve encountered this question both with undirected (small, and I powered through) and now undirected nodes.
Just in case I’m in asking an XY question, my current directed graph is entirely unidirectional; there are no closed loops. I could trivially assign a value to each node, and know that every edge leads to a node with a strictly larger value than the node it leads from. To be even more specific if it helps, though I definitely don’t know the proper math language: the graph represents a double elimination playoff bracket, and I want to put together the possible routes for each seed on a plot to guide teams through the process, pruning out things that don’t matter to that team. Fortunately in this case, the graph is deterministic; no re-seeding occurs due to match outcomes, making such a plot useful.
My previous issue, which was small so I powered through, had an undirected graph, and I really just wanted to know whether or not the graph was continuous; that is, whether every node pair was connected by some path. graph, connected MATLAB Answers — New Questions
why my 3D image is not extruded in 3D software?
Hello, i have 3D image but when I view the image in the 3D software to be printed, the image does not extrude. here i attached my code and images. can anyone check on my code. Many thanks.
a = imread (‘stomachgray.tif’);
mask = zeros(size(a));
mask(100:end-100,100:end-100) = 1;
bw = activecontour(a,mask,1000);
c = im2double(bw);
shading flat
d = imgaussfilt3 (c,4);
colormap(bone)
h = hgtransform;
mesh(d*100, ‘Parent’, h, ‘FaceColor’, ‘r’ )
view(3)
lighting gouraud
camlight right
% Make it taller
set (gca, ‘units’, ‘cent’)
set(h, ‘Matrix’, makehgtform(‘scale’, [10 10 500]))
[X,Y] = meshgrid(1:length(h));
surf2stl(‘stomachSurf7.stl’,X,Y,d);
end
<</matlabcentral/answers/uploaded_files/64209/3d%20mtlb.JPG>>
<</matlabcentral/answers/uploaded_files/64210/3d%20view.JPG>>Hello, i have 3D image but when I view the image in the 3D software to be printed, the image does not extrude. here i attached my code and images. can anyone check on my code. Many thanks.
a = imread (‘stomachgray.tif’);
mask = zeros(size(a));
mask(100:end-100,100:end-100) = 1;
bw = activecontour(a,mask,1000);
c = im2double(bw);
shading flat
d = imgaussfilt3 (c,4);
colormap(bone)
h = hgtransform;
mesh(d*100, ‘Parent’, h, ‘FaceColor’, ‘r’ )
view(3)
lighting gouraud
camlight right
% Make it taller
set (gca, ‘units’, ‘cent’)
set(h, ‘Matrix’, makehgtform(‘scale’, [10 10 500]))
[X,Y] = meshgrid(1:length(h));
surf2stl(‘stomachSurf7.stl’,X,Y,d);
end
<</matlabcentral/answers/uploaded_files/64209/3d%20mtlb.JPG>>
<</matlabcentral/answers/uploaded_files/64210/3d%20view.JPG>> Hello, i have 3D image but when I view the image in the 3D software to be printed, the image does not extrude. here i attached my code and images. can anyone check on my code. Many thanks.
a = imread (‘stomachgray.tif’);
mask = zeros(size(a));
mask(100:end-100,100:end-100) = 1;
bw = activecontour(a,mask,1000);
c = im2double(bw);
shading flat
d = imgaussfilt3 (c,4);
colormap(bone)
h = hgtransform;
mesh(d*100, ‘Parent’, h, ‘FaceColor’, ‘r’ )
view(3)
lighting gouraud
camlight right
% Make it taller
set (gca, ‘units’, ‘cent’)
set(h, ‘Matrix’, makehgtform(‘scale’, [10 10 500]))
[X,Y] = meshgrid(1:length(h));
surf2stl(‘stomachSurf7.stl’,X,Y,d);
end
<</matlabcentral/answers/uploaded_files/64209/3d%20mtlb.JPG>>
<</matlabcentral/answers/uploaded_files/64210/3d%20view.JPG>> mesh, extrude, matlab, 3d image MATLAB Answers — New Questions
How can ı solve this triangle problem at MATLAB?
In the triangle which has edges names:a,b,c; a=9 b=18 c=25 how can ı calculate the alfa(the angles sees a) with the law of cosines? with MATLABIn the triangle which has edges names:a,b,c; a=9 b=18 c=25 how can ı calculate the alfa(the angles sees a) with the law of cosines? with MATLAB In the triangle which has edges names:a,b,c; a=9 b=18 c=25 how can ı calculate the alfa(the angles sees a) with the law of cosines? with MATLAB matlab, mathematics, homework MATLAB Answers — New Questions
I need to rotate my 3D figure
I have particle size data for differrent De(parameter) values.
I have plotted 2Dbar graphs, I want stack all figures into one 3D figure window.
I stacked everything, that looks like the image below
But I want to rotate axis in such a way that: Particle_density(Y-axis) in vertical, Particle size(X-axis) in horizontal and De (z-axis) per pendicular to the screen. It should look like this image below
I have attached my matlab code to this thread.
Please guide me, how to do this. Thanks in advanceI have particle size data for differrent De(parameter) values.
I have plotted 2Dbar graphs, I want stack all figures into one 3D figure window.
I stacked everything, that looks like the image below
But I want to rotate axis in such a way that: Particle_density(Y-axis) in vertical, Particle size(X-axis) in horizontal and De (z-axis) per pendicular to the screen. It should look like this image below
I have attached my matlab code to this thread.
Please guide me, how to do this. Thanks in advance I have particle size data for differrent De(parameter) values.
I have plotted 2Dbar graphs, I want stack all figures into one 3D figure window.
I stacked everything, that looks like the image below
But I want to rotate axis in such a way that: Particle_density(Y-axis) in vertical, Particle size(X-axis) in horizontal and De (z-axis) per pendicular to the screen. It should look like this image below
I have attached my matlab code to this thread.
Please guide me, how to do this. Thanks in advance rotation, bar, plot3 MATLAB Answers — New Questions
How to fill a volume with spheres?
Hi,
I’d like to import *.stl files of different shapes and fill the volume with overlapping spheres.
How can I do it. I already did this task for 2D shapes using bwdist. But for 3D shapes, I don’t know how to do it.
ThanksHi,
I’d like to import *.stl files of different shapes and fill the volume with overlapping spheres.
How can I do it. I already did this task for 2D shapes using bwdist. But for 3D shapes, I don’t know how to do it.
Thanks Hi,
I’d like to import *.stl files of different shapes and fill the volume with overlapping spheres.
How can I do it. I already did this task for 2D shapes using bwdist. But for 3D shapes, I don’t know how to do it.
Thanks 3d, shapes, spheres, volume filling MATLAB Answers — New Questions
how to use stlwrite function options
Hi guys, i have to make a triangulation 3D of a solid of which i have the coordinates (x,y,z) of 20ooo points and i need to export the result (so the tetrahedra) to an stl file.
How can I use properly the stlwrite function, in particular the option indicated with TRIANGULATION?
thanks a lot.Hi guys, i have to make a triangulation 3D of a solid of which i have the coordinates (x,y,z) of 20ooo points and i need to export the result (so the tetrahedra) to an stl file.
How can I use properly the stlwrite function, in particular the option indicated with TRIANGULATION?
thanks a lot. Hi guys, i have to make a triangulation 3D of a solid of which i have the coordinates (x,y,z) of 20ooo points and i need to export the result (so the tetrahedra) to an stl file.
How can I use properly the stlwrite function, in particular the option indicated with TRIANGULATION?
thanks a lot. triangulation delaunay stl .stl stlwrite MATLAB Answers — New Questions
Spider Plot with Standard Deviation as shaded region
I want to plot a spider plot where each spoke represents the average value with solid line. In addition, I want to show standard deviation as shaded region around the average plot (Average+SD and Average-SD). I have attached a figure to show the desired outcome.
Figure available at: https://www.mdpi.com/2078-2489/15/6/364
Thank you in advance.I want to plot a spider plot where each spoke represents the average value with solid line. In addition, I want to show standard deviation as shaded region around the average plot (Average+SD and Average-SD). I have attached a figure to show the desired outcome.
Figure available at: https://www.mdpi.com/2078-2489/15/6/364
Thank you in advance. I want to plot a spider plot where each spoke represents the average value with solid line. In addition, I want to show standard deviation as shaded region around the average plot (Average+SD and Average-SD). I have attached a figure to show the desired outcome.
Figure available at: https://www.mdpi.com/2078-2489/15/6/364
Thank you in advance. spider plots, standard deviation, shaded region MATLAB Answers — New Questions