Tag Archives: matlab
Where can I find MATLAB license files?
Where can I find MATLAB license files? Where can I find MATLAB license files? Where can I find MATLAB license files? MATLAB Answers — New Questions
Issues with HDL coder IFFT/FFT Processing with 4×1 Vectors and Data Reordering
I have created an OFDM system where, at the transmitter (Tx) side, I perform IFFT, add a cyclic prefix (CP), and then on the receiver (Rx) side, I perform FFT followed by channel estimation and equalization.
However, I encountered an issue. When I pass scalar values through the IFFT and FFT blocks, everything works fine, and the constellation graph appears as expected. However, my goal is to process data in 4×1 vectors to increase the sampling rate. After processing 4×1 vectors, the constellation graph does not appear correctly, and it seems the data is not in the expected order after the IFFT block.
My question is: when converting data to the time domain with IFFT, does the order of the data change? For example, I expect the data to go through as {0,1,2,3}, {4,5,6,7}, {8,9,10,11}, {12,13,14,15}, etc. But after IFFT, should I expect it to be {0,4,8,12}, {1,5,9,13}, and so on? If this is the case, should I introduce a reordering step after the IFFT to restore the data to its original order?
Additionally, could there be issues related to bit-reversed order, or other similar problems such as "output/input in bit-reversed order"? If you could clarify the meaning of this and how it might affect my system, I would greatly appreciate it.
For your reference, I am using HDL Coder and leveraging the HDL optimized IFFT/FFT blocks in my design.
Finally, I would be grateful if you could provide any resources or further explanations on the index order and the steps needed to process data in vector form, including any additional adjustments I need to make for IFFT/FFT operations.
Thank you very much for your time and assistance. I look forward to your response.I have created an OFDM system where, at the transmitter (Tx) side, I perform IFFT, add a cyclic prefix (CP), and then on the receiver (Rx) side, I perform FFT followed by channel estimation and equalization.
However, I encountered an issue. When I pass scalar values through the IFFT and FFT blocks, everything works fine, and the constellation graph appears as expected. However, my goal is to process data in 4×1 vectors to increase the sampling rate. After processing 4×1 vectors, the constellation graph does not appear correctly, and it seems the data is not in the expected order after the IFFT block.
My question is: when converting data to the time domain with IFFT, does the order of the data change? For example, I expect the data to go through as {0,1,2,3}, {4,5,6,7}, {8,9,10,11}, {12,13,14,15}, etc. But after IFFT, should I expect it to be {0,4,8,12}, {1,5,9,13}, and so on? If this is the case, should I introduce a reordering step after the IFFT to restore the data to its original order?
Additionally, could there be issues related to bit-reversed order, or other similar problems such as "output/input in bit-reversed order"? If you could clarify the meaning of this and how it might affect my system, I would greatly appreciate it.
For your reference, I am using HDL Coder and leveraging the HDL optimized IFFT/FFT blocks in my design.
Finally, I would be grateful if you could provide any resources or further explanations on the index order and the steps needed to process data in vector form, including any additional adjustments I need to make for IFFT/FFT operations.
Thank you very much for your time and assistance. I look forward to your response. I have created an OFDM system where, at the transmitter (Tx) side, I perform IFFT, add a cyclic prefix (CP), and then on the receiver (Rx) side, I perform FFT followed by channel estimation and equalization.
However, I encountered an issue. When I pass scalar values through the IFFT and FFT blocks, everything works fine, and the constellation graph appears as expected. However, my goal is to process data in 4×1 vectors to increase the sampling rate. After processing 4×1 vectors, the constellation graph does not appear correctly, and it seems the data is not in the expected order after the IFFT block.
My question is: when converting data to the time domain with IFFT, does the order of the data change? For example, I expect the data to go through as {0,1,2,3}, {4,5,6,7}, {8,9,10,11}, {12,13,14,15}, etc. But after IFFT, should I expect it to be {0,4,8,12}, {1,5,9,13}, and so on? If this is the case, should I introduce a reordering step after the IFFT to restore the data to its original order?
Additionally, could there be issues related to bit-reversed order, or other similar problems such as "output/input in bit-reversed order"? If you could clarify the meaning of this and how it might affect my system, I would greatly appreciate it.
For your reference, I am using HDL Coder and leveraging the HDL optimized IFFT/FFT blocks in my design.
Finally, I would be grateful if you could provide any resources or further explanations on the index order and the steps needed to process data in vector form, including any additional adjustments I need to make for IFFT/FFT operations.
Thank you very much for your time and assistance. I look forward to your response. hdl coder, ifft, fft MATLAB Answers — New Questions
Matlab App: Get cursor position in axis continuously, keep plot interactivity
Hi there,
I’m trying to create a matlab app in which users can create geometric objects and use them for some calculations later.
These are displayed in a 3D axis, rotated slightly. I am trying to create user functions to draw lines inside that axis. For this, I wan to implement continuously displayed x,y coordinates, or crosshairs or similar, as well as data snapping. Users will only draw 2D objects on the x,y plane. I still want users to be able to rotate the plot, zoom and pan normally with the mouse.
If I use a WindowButtonMotionFcn, then I lose plot interactivity with the mouse. If I use other means of getting the cursor position, like java.awt.MouseInfo.getPointerInfo().getLocation() and getpixelposition() or similar gui coordinate functions, I have to deal with a rotated camera and axis transformation. This makes "hit detection" on the data very cumbersome.
Using axes.CurrentPoint seems useless, because it only updates when the mouse is clicked, not continuously.
Any ideas on how to do this?Hi there,
I’m trying to create a matlab app in which users can create geometric objects and use them for some calculations later.
These are displayed in a 3D axis, rotated slightly. I am trying to create user functions to draw lines inside that axis. For this, I wan to implement continuously displayed x,y coordinates, or crosshairs or similar, as well as data snapping. Users will only draw 2D objects on the x,y plane. I still want users to be able to rotate the plot, zoom and pan normally with the mouse.
If I use a WindowButtonMotionFcn, then I lose plot interactivity with the mouse. If I use other means of getting the cursor position, like java.awt.MouseInfo.getPointerInfo().getLocation() and getpixelposition() or similar gui coordinate functions, I have to deal with a rotated camera and axis transformation. This makes "hit detection" on the data very cumbersome.
Using axes.CurrentPoint seems useless, because it only updates when the mouse is clicked, not continuously.
Any ideas on how to do this? Hi there,
I’m trying to create a matlab app in which users can create geometric objects and use them for some calculations later.
These are displayed in a 3D axis, rotated slightly. I am trying to create user functions to draw lines inside that axis. For this, I wan to implement continuously displayed x,y coordinates, or crosshairs or similar, as well as data snapping. Users will only draw 2D objects on the x,y plane. I still want users to be able to rotate the plot, zoom and pan normally with the mouse.
If I use a WindowButtonMotionFcn, then I lose plot interactivity with the mouse. If I use other means of getting the cursor position, like java.awt.MouseInfo.getPointerInfo().getLocation() and getpixelposition() or similar gui coordinate functions, I have to deal with a rotated camera and axis transformation. This makes "hit detection" on the data very cumbersome.
Using axes.CurrentPoint seems useless, because it only updates when the mouse is clicked, not continuously.
Any ideas on how to do this? appdesigner, app designer, windowbuttonmotionfcn, axes, matlab gui MATLAB Answers — New Questions
Got error in resample function
I am a beginner of Matlab and I was trying to resample y by this resample function
but i got an error: " Incorrect number or types of inputs or outputs for function resample. "
please tell me what is the problem if you know. thanks a lot.
load handel.mat
y = y(:);
Fs = 8192;
fc = 2e5;
Fs_new = ceil( (Fs/2 + fc) / Fs * 2 ) * Fs;
y_resampled = resample(y,Fs_new,Fs);I am a beginner of Matlab and I was trying to resample y by this resample function
but i got an error: " Incorrect number or types of inputs or outputs for function resample. "
please tell me what is the problem if you know. thanks a lot.
load handel.mat
y = y(:);
Fs = 8192;
fc = 2e5;
Fs_new = ceil( (Fs/2 + fc) / Fs * 2 ) * Fs;
y_resampled = resample(y,Fs_new,Fs); I am a beginner of Matlab and I was trying to resample y by this resample function
but i got an error: " Incorrect number or types of inputs or outputs for function resample. "
please tell me what is the problem if you know. thanks a lot.
load handel.mat
y = y(:);
Fs = 8192;
fc = 2e5;
Fs_new = ceil( (Fs/2 + fc) / Fs * 2 ) * Fs;
y_resampled = resample(y,Fs_new,Fs); resample, matlab, error MATLAB Answers — New Questions
How to generate custom unoptimized code within a system composer software architecture model?
C-function code generation appears to work differently when generating code inside of a system composer software architecture model isntead of a standalone simulink model. I am trying to insert certain processer primitaves (mutexes) into my simulink model such that it is incorporated into the autogenerated code. It is a few simple lines of c++ code, so I opted to use the C-function block. In both cases, I have specified in the c-function dialogue window "Generate code as-is (optimizations off)"
Inside of an export-function simulink model, I created a c-function block that includes a comment and then a simple line of code, which generates correctly:
However, if I copy this exact same c-function into an export-function model within a system composer software architecture model, it no longer generates my my specified code. Instead, it generates function calls but does not define the functions anywhere. (Even doing a simple text search of my entire workspace only shows that the function call shown below gets generated).C-function code generation appears to work differently when generating code inside of a system composer software architecture model isntead of a standalone simulink model. I am trying to insert certain processer primitaves (mutexes) into my simulink model such that it is incorporated into the autogenerated code. It is a few simple lines of c++ code, so I opted to use the C-function block. In both cases, I have specified in the c-function dialogue window "Generate code as-is (optimizations off)"
Inside of an export-function simulink model, I created a c-function block that includes a comment and then a simple line of code, which generates correctly:
However, if I copy this exact same c-function into an export-function model within a system composer software architecture model, it no longer generates my my specified code. Instead, it generates function calls but does not define the functions anywhere. (Even doing a simple text search of my entire workspace only shows that the function call shown below gets generated). C-function code generation appears to work differently when generating code inside of a system composer software architecture model isntead of a standalone simulink model. I am trying to insert certain processer primitaves (mutexes) into my simulink model such that it is incorporated into the autogenerated code. It is a few simple lines of c++ code, so I opted to use the C-function block. In both cases, I have specified in the c-function dialogue window "Generate code as-is (optimizations off)"
Inside of an export-function simulink model, I created a c-function block that includes a comment and then a simple line of code, which generates correctly:
However, if I copy this exact same c-function into an export-function model within a system composer software architecture model, it no longer generates my my specified code. Instead, it generates function calls but does not define the functions anywhere. (Even doing a simple text search of my entire workspace only shows that the function call shown below gets generated). software architecture models, c-functions, export-function models, embedded coder, system composer MATLAB Answers — New Questions
When using a writetable to write a table file containing data in datetime format to Excel, the saved datetime data in Excel is not in the same format as the datetime data
The table data is as follows:
Use the following writetable function code to save data to Excel,the exported result is shown in the following figure:
The time display is incomplete.
How to set the exported time format to be the same as the original data?
writetable(T, filePath);The table data is as follows:
Use the following writetable function code to save data to Excel,the exported result is shown in the following figure:
The time display is incomplete.
How to set the exported time format to be the same as the original data?
writetable(T, filePath); The table data is as follows:
Use the following writetable function code to save data to Excel,the exported result is shown in the following figure:
The time display is incomplete.
How to set the exported time format to be the same as the original data?
writetable(T, filePath); writetable,datetime,excel MATLAB Answers — New Questions
Plot along line from. PDE solution
The code below solves a 1-D, transient heat transfer problem set up as in general PDE format. The solution is plotted in color across the domain from 0 to 0.1 after 10 seconds have elapsed. What is the best way to plot the temperature across the length of this domain at this final time?
Thanks
clear all;
%% Create transient thermal model
thermalmodel = createpde(1);
R1= [3,4,0,0.1,0.1,0,0,0,1,1]’;
gd= [R1];
sf= ‘R1’;
ns = char(‘R1’);
ns = ns’;
dl = decsg(gd,sf,ns);
%% Create & plot geometry
geometryFromEdges(thermalmodel,dl);
pdegplot(thermalmodel,"EdgeLabels","on","FaceLabels","on")
xlim([0 0.1])
ylim([-1 1])
% axis equal
%% Generate and plot mesh
generateMesh(thermalmodel)
figure
pdemesh(thermalmodel)
title("Mesh with Quadratic Triangular Elements")
%% Apply BCs
% Edge 4 is left edge; Edge 2 is right side
applyBoundaryCondition(thermalmodel, "dirichlet",Edge=[4],u=100);
applyBoundaryCondition(thermalmodel, "dirichlet",Edge=[2],u=20);
%% Apply thermal properties [copper]
rho= 8933 %
cp= 385 %
rhocp= rho*cp %
k= 401 % W/mK
%% Define uniform volumetric heat generation rate
Qgen= 0 % W/m3
%% Define coefficients for generic Governing Equation to be solved
m= 0
a= 0
d= rhocp
c= [k]
f= [Qgen]
specifyCoefficients(thermalmodel, m=0, d=rhocp, c=k, a=0, f=f);
%% Apply initial condition
setInitialConditions(thermalmodel, 20);
%% Define time limits
tlist= 0: 1: 10;
thermalresults= solvepde(thermalmodel, tlist);
% Plot results
sol = thermalresults.NodalSolution;
subplot(2,2,1)
pdeplot(thermalmodel,"XYData",sol(:,11), …
"Contour","on",…
"ColorMap","jet")The code below solves a 1-D, transient heat transfer problem set up as in general PDE format. The solution is plotted in color across the domain from 0 to 0.1 after 10 seconds have elapsed. What is the best way to plot the temperature across the length of this domain at this final time?
Thanks
clear all;
%% Create transient thermal model
thermalmodel = createpde(1);
R1= [3,4,0,0.1,0.1,0,0,0,1,1]’;
gd= [R1];
sf= ‘R1’;
ns = char(‘R1’);
ns = ns’;
dl = decsg(gd,sf,ns);
%% Create & plot geometry
geometryFromEdges(thermalmodel,dl);
pdegplot(thermalmodel,"EdgeLabels","on","FaceLabels","on")
xlim([0 0.1])
ylim([-1 1])
% axis equal
%% Generate and plot mesh
generateMesh(thermalmodel)
figure
pdemesh(thermalmodel)
title("Mesh with Quadratic Triangular Elements")
%% Apply BCs
% Edge 4 is left edge; Edge 2 is right side
applyBoundaryCondition(thermalmodel, "dirichlet",Edge=[4],u=100);
applyBoundaryCondition(thermalmodel, "dirichlet",Edge=[2],u=20);
%% Apply thermal properties [copper]
rho= 8933 %
cp= 385 %
rhocp= rho*cp %
k= 401 % W/mK
%% Define uniform volumetric heat generation rate
Qgen= 0 % W/m3
%% Define coefficients for generic Governing Equation to be solved
m= 0
a= 0
d= rhocp
c= [k]
f= [Qgen]
specifyCoefficients(thermalmodel, m=0, d=rhocp, c=k, a=0, f=f);
%% Apply initial condition
setInitialConditions(thermalmodel, 20);
%% Define time limits
tlist= 0: 1: 10;
thermalresults= solvepde(thermalmodel, tlist);
% Plot results
sol = thermalresults.NodalSolution;
subplot(2,2,1)
pdeplot(thermalmodel,"XYData",sol(:,11), …
"Contour","on",…
"ColorMap","jet") The code below solves a 1-D, transient heat transfer problem set up as in general PDE format. The solution is plotted in color across the domain from 0 to 0.1 after 10 seconds have elapsed. What is the best way to plot the temperature across the length of this domain at this final time?
Thanks
clear all;
%% Create transient thermal model
thermalmodel = createpde(1);
R1= [3,4,0,0.1,0.1,0,0,0,1,1]’;
gd= [R1];
sf= ‘R1’;
ns = char(‘R1’);
ns = ns’;
dl = decsg(gd,sf,ns);
%% Create & plot geometry
geometryFromEdges(thermalmodel,dl);
pdegplot(thermalmodel,"EdgeLabels","on","FaceLabels","on")
xlim([0 0.1])
ylim([-1 1])
% axis equal
%% Generate and plot mesh
generateMesh(thermalmodel)
figure
pdemesh(thermalmodel)
title("Mesh with Quadratic Triangular Elements")
%% Apply BCs
% Edge 4 is left edge; Edge 2 is right side
applyBoundaryCondition(thermalmodel, "dirichlet",Edge=[4],u=100);
applyBoundaryCondition(thermalmodel, "dirichlet",Edge=[2],u=20);
%% Apply thermal properties [copper]
rho= 8933 %
cp= 385 %
rhocp= rho*cp %
k= 401 % W/mK
%% Define uniform volumetric heat generation rate
Qgen= 0 % W/m3
%% Define coefficients for generic Governing Equation to be solved
m= 0
a= 0
d= rhocp
c= [k]
f= [Qgen]
specifyCoefficients(thermalmodel, m=0, d=rhocp, c=k, a=0, f=f);
%% Apply initial condition
setInitialConditions(thermalmodel, 20);
%% Define time limits
tlist= 0: 1: 10;
thermalresults= solvepde(thermalmodel, tlist);
% Plot results
sol = thermalresults.NodalSolution;
subplot(2,2,1)
pdeplot(thermalmodel,"XYData",sol(:,11), …
"Contour","on",…
"ColorMap","jet") plotting MATLAB Answers — New Questions
How to use cell value as a variable or How to convert cell to double?
I have data in excel, I am reading that data in MATLAB. I want to use text in excel as a variable name to assign fixed set of data values which also in same excel. but I am facing the problem as the text from excel has class cell.
So, how can I use cell values (Time, Temperatue….etc) as a variable in MATLAB?I have data in excel, I am reading that data in MATLAB. I want to use text in excel as a variable name to assign fixed set of data values which also in same excel. but I am facing the problem as the text from excel has class cell.
So, how can I use cell values (Time, Temperatue….etc) as a variable in MATLAB? I have data in excel, I am reading that data in MATLAB. I want to use text in excel as a variable name to assign fixed set of data values which also in same excel. but I am facing the problem as the text from excel has class cell.
So, how can I use cell values (Time, Temperatue….etc) as a variable in MATLAB? cell, variable, evil, eval, antipattern, anti-pattern MATLAB Answers — New Questions
Code generation and stateflow transition variant
Hello,
Is the code generation tunable with a transition variant, set with "Variant Activation Time = Code compile" with r2024b?
Indeed, I have a compilation warning with my generated code. The code generation creates a static function with #if inside the function:
This way, the compilation gives a compilation warning saying that there is a function defined but not used.
If you have a solution, I am interested.
Regards,
JeanHello,
Is the code generation tunable with a transition variant, set with "Variant Activation Time = Code compile" with r2024b?
Indeed, I have a compilation warning with my generated code. The code generation creates a static function with #if inside the function:
This way, the compilation gives a compilation warning saying that there is a function defined but not used.
If you have a solution, I am interested.
Regards,
Jean Hello,
Is the code generation tunable with a transition variant, set with "Variant Activation Time = Code compile" with r2024b?
Indeed, I have a compilation warning with my generated code. The code generation creates a static function with #if inside the function:
This way, the compilation gives a compilation warning saying that there is a function defined but not used.
If you have a solution, I am interested.
Regards,
Jean variant, code generation MATLAB Answers — New Questions
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