Author: PuTI
Change value of stream mass flow in HYSYS using matlab
I want to set the value of stream ‘PFD136’ to flow_136. Seems I have a syntax error. Please helpI want to set the value of stream ‘PFD136’ to flow_136. Seems I have a syntax error. Please help I want to set the value of stream ‘PFD136’ to flow_136. Seems I have a syntax error. Please help hysys, hysysinterface, setvalue MATLAB Answers — New Questions
Help, how to make a buck chopper simulation using SCR only ?
i want to know how to make a buck chopper simulation in MATLAB using only SCR without mosfet/IGBT is it possible ?i want to know how to make a buck chopper simulation in MATLAB using only SCR without mosfet/IGBT is it possible ? i want to know how to make a buck chopper simulation in MATLAB using only SCR without mosfet/IGBT is it possible ? buck, chopper MATLAB Answers — New Questions
How do I contact the authors of the blog “Generative AI + Robotics = Awesome!”
The blog Generative AI + Robotics = Awesome! says "you can reach out to us directly to request trial code access" yet there is no details of whom to contact or how. I feel I may be missing something obvious. Can anybody help me to get in contact with the Authors.The blog Generative AI + Robotics = Awesome! says "you can reach out to us directly to request trial code access" yet there is no details of whom to contact or how. I feel I may be missing something obvious. Can anybody help me to get in contact with the Authors. The blog Generative AI + Robotics = Awesome! says "you can reach out to us directly to request trial code access" yet there is no details of whom to contact or how. I feel I may be missing something obvious. Can anybody help me to get in contact with the Authors. robotics vla blog. MATLAB Answers — New Questions
Simulink Hanging when I try to save a simple model
Version: MATLAB_R2025b
Laptop: Macbook Pro M3 Max
I just started learning to use MATLAB and Simulink. I am on a Macbook pro M3 Max (36GB of RAM, 14 CPU cores). MATLAB is the first program I have had on this laptop to be so slow and unresponsive.
I have found workarounds for many of the problems I faced, but when I try to save a very basic Simulink model (see photo), both MATLAB and Simulink become unresponsive (see photo) and I have to force quit and restart just to be able to do anything. Can I get some help with this?Version: MATLAB_R2025b
Laptop: Macbook Pro M3 Max
I just started learning to use MATLAB and Simulink. I am on a Macbook pro M3 Max (36GB of RAM, 14 CPU cores). MATLAB is the first program I have had on this laptop to be so slow and unresponsive.
I have found workarounds for many of the problems I faced, but when I try to save a very basic Simulink model (see photo), both MATLAB and Simulink become unresponsive (see photo) and I have to force quit and restart just to be able to do anything. Can I get some help with this? Version: MATLAB_R2025b
Laptop: Macbook Pro M3 Max
I just started learning to use MATLAB and Simulink. I am on a Macbook pro M3 Max (36GB of RAM, 14 CPU cores). MATLAB is the first program I have had on this laptop to be so slow and unresponsive.
I have found workarounds for many of the problems I faced, but when I try to save a very basic Simulink model (see photo), both MATLAB and Simulink become unresponsive (see photo) and I have to force quit and restart just to be able to do anything. Can I get some help with this? simulink, save, model MATLAB Answers — New Questions
Add Tooltip to each UI Tree Checkbox in App Designer
In App Desinger I want to add tooltips to each ui tree checkbox, so here each checkbox shall tell the user more of what is done or checked with the check exactly. Example: For "Block Colors" a tooltip might show something like "Checks if each Simulink Block has its dedicated color as defined by the company guidelines". Is there an option, as I can only find to add a tooltip to the parent CheckBoxTree but not each individual checkbox? Thank you.In App Desinger I want to add tooltips to each ui tree checkbox, so here each checkbox shall tell the user more of what is done or checked with the check exactly. Example: For "Block Colors" a tooltip might show something like "Checks if each Simulink Block has its dedicated color as defined by the company guidelines". Is there an option, as I can only find to add a tooltip to the parent CheckBoxTree but not each individual checkbox? Thank you. In App Desinger I want to add tooltips to each ui tree checkbox, so here each checkbox shall tell the user more of what is done or checked with the check exactly. Example: For "Block Colors" a tooltip might show something like "Checks if each Simulink Block has its dedicated color as defined by the company guidelines". Is there an option, as I can only find to add a tooltip to the parent CheckBoxTree but not each individual checkbox? Thank you. appdesigner, matlab gui, checkbox MATLAB Answers — New Questions
Generate Graph Nodes and add buttondown callbacks for interactivity
I’m trying to create a graph that brings up a dialogue box when one of the nodes is clicked. I use
NodeTable = table(‘Size’,[0 4],’VariableTypes’,{‘double’,’string’,’double’,’double’}, …
‘VariableNames’,{‘Code’,’Name’,’Latitude’,’Longitude’});
EdgeTable = table(‘Size’,[0 2],’VariableTypes’,{‘cell’, ‘double’}, …
‘VariableNames’,{‘EndNodes’,’Distance’});
nodetemp = inputdlg(["Node Name", "Latitude", "Longitude"], "Node Details");
%check input present
if isempty(nodetemp)== 0
%check node not present in table
if any(matches(app.NodeTable.Name,nodetemp(1),IgnoreCase=true))==false
%format table and add code in column 1
nodeinp = addvars(cell2table(transpose(nodetemp),’VariableNames’,{‘Name’,’Latitude’,’Longitude’}), app.index, ‘before’, 1,’NewVariableNames’,{‘Code’});
%update graph with node data
app.NodeTable=[app.NodeTable; nodeinp];
app.G=addnode(app.G,nodeinp);
app.map = plot(app.UIAxes,app.G,’NodeLabel’,app.G.Nodes.Name,’EdgeLabel’,app.G.Edges.Distance);%plot graph
%set node coordinates
app.map.XData = str2double(app.NodeTable.Longitude);
app.map.YData = str2double(app.NodeTable.Latitude);
app.index = app.index + 1; %increment node counter
end
end
to create the graph, add nodes and plot it. I then am attempting to use
nodes=findobj(app.map,’Marker’,’o’);
nodesLength = length(nodes);
for count=1:nodesLength
nodes(count).ButtonDownFcn=@(src,event)nodeButtonDown(app,count);
end
to get a hold of the node graphical objects and assign callbacks as advised here but the plot doesn’t seem to generate the nodes as children/separate objects like it says in all the documentation. The nodes variable just becomes a copy of the graphplot object. You’ll notice I’m using the app designer.I’m trying to create a graph that brings up a dialogue box when one of the nodes is clicked. I use
NodeTable = table(‘Size’,[0 4],’VariableTypes’,{‘double’,’string’,’double’,’double’}, …
‘VariableNames’,{‘Code’,’Name’,’Latitude’,’Longitude’});
EdgeTable = table(‘Size’,[0 2],’VariableTypes’,{‘cell’, ‘double’}, …
‘VariableNames’,{‘EndNodes’,’Distance’});
nodetemp = inputdlg(["Node Name", "Latitude", "Longitude"], "Node Details");
%check input present
if isempty(nodetemp)== 0
%check node not present in table
if any(matches(app.NodeTable.Name,nodetemp(1),IgnoreCase=true))==false
%format table and add code in column 1
nodeinp = addvars(cell2table(transpose(nodetemp),’VariableNames’,{‘Name’,’Latitude’,’Longitude’}), app.index, ‘before’, 1,’NewVariableNames’,{‘Code’});
%update graph with node data
app.NodeTable=[app.NodeTable; nodeinp];
app.G=addnode(app.G,nodeinp);
app.map = plot(app.UIAxes,app.G,’NodeLabel’,app.G.Nodes.Name,’EdgeLabel’,app.G.Edges.Distance);%plot graph
%set node coordinates
app.map.XData = str2double(app.NodeTable.Longitude);
app.map.YData = str2double(app.NodeTable.Latitude);
app.index = app.index + 1; %increment node counter
end
end
to create the graph, add nodes and plot it. I then am attempting to use
nodes=findobj(app.map,’Marker’,’o’);
nodesLength = length(nodes);
for count=1:nodesLength
nodes(count).ButtonDownFcn=@(src,event)nodeButtonDown(app,count);
end
to get a hold of the node graphical objects and assign callbacks as advised here but the plot doesn’t seem to generate the nodes as children/separate objects like it says in all the documentation. The nodes variable just becomes a copy of the graphplot object. You’ll notice I’m using the app designer. I’m trying to create a graph that brings up a dialogue box when one of the nodes is clicked. I use
NodeTable = table(‘Size’,[0 4],’VariableTypes’,{‘double’,’string’,’double’,’double’}, …
‘VariableNames’,{‘Code’,’Name’,’Latitude’,’Longitude’});
EdgeTable = table(‘Size’,[0 2],’VariableTypes’,{‘cell’, ‘double’}, …
‘VariableNames’,{‘EndNodes’,’Distance’});
nodetemp = inputdlg(["Node Name", "Latitude", "Longitude"], "Node Details");
%check input present
if isempty(nodetemp)== 0
%check node not present in table
if any(matches(app.NodeTable.Name,nodetemp(1),IgnoreCase=true))==false
%format table and add code in column 1
nodeinp = addvars(cell2table(transpose(nodetemp),’VariableNames’,{‘Name’,’Latitude’,’Longitude’}), app.index, ‘before’, 1,’NewVariableNames’,{‘Code’});
%update graph with node data
app.NodeTable=[app.NodeTable; nodeinp];
app.G=addnode(app.G,nodeinp);
app.map = plot(app.UIAxes,app.G,’NodeLabel’,app.G.Nodes.Name,’EdgeLabel’,app.G.Edges.Distance);%plot graph
%set node coordinates
app.map.XData = str2double(app.NodeTable.Longitude);
app.map.YData = str2double(app.NodeTable.Latitude);
app.index = app.index + 1; %increment node counter
end
end
to create the graph, add nodes and plot it. I then am attempting to use
nodes=findobj(app.map,’Marker’,’o’);
nodesLength = length(nodes);
for count=1:nodesLength
nodes(count).ButtonDownFcn=@(src,event)nodeButtonDown(app,count);
end
to get a hold of the node graphical objects and assign callbacks as advised here but the plot doesn’t seem to generate the nodes as children/separate objects like it says in all the documentation. The nodes variable just becomes a copy of the graphplot object. You’ll notice I’m using the app designer. axes, appdesigner, app designer, callback, graph, graphics, plot, plotting, gui, objects, find, nodes, children, interactivity, programmatic, class, assign MATLAB Answers — New Questions
I am unable to make the new vesion of spectrumAnalyzer show distortion measurements.
I have a Matlab script that has worked fine in R2021b and earlier which I still use today. It simply reads my audio on a Macbook Pro running MacOS 12 and presents a spectrum on the analyzer. Moving that script to the new R2025b and modifying the script to call the new spectrum analyzer seems to work to present the spectrum but when I select "Measurements" and "Distortion" the distortion data appears but does not seem to find the main tone and in-turn the harmonics. I am stuck using the old version of Matlab since that works. I think I may be missing a configuration command on the new analyzer that wasn’t required on the old one. The tone below is on CH1 and CH2 identically. CH2 appears in front of CH1.I have a Matlab script that has worked fine in R2021b and earlier which I still use today. It simply reads my audio on a Macbook Pro running MacOS 12 and presents a spectrum on the analyzer. Moving that script to the new R2025b and modifying the script to call the new spectrum analyzer seems to work to present the spectrum but when I select "Measurements" and "Distortion" the distortion data appears but does not seem to find the main tone and in-turn the harmonics. I am stuck using the old version of Matlab since that works. I think I may be missing a configuration command on the new analyzer that wasn’t required on the old one. The tone below is on CH1 and CH2 identically. CH2 appears in front of CH1. I have a Matlab script that has worked fine in R2021b and earlier which I still use today. It simply reads my audio on a Macbook Pro running MacOS 12 and presents a spectrum on the analyzer. Moving that script to the new R2025b and modifying the script to call the new spectrum analyzer seems to work to present the spectrum but when I select "Measurements" and "Distortion" the distortion data appears but does not seem to find the main tone and in-turn the harmonics. I am stuck using the old version of Matlab since that works. I think I may be missing a configuration command on the new analyzer that wasn’t required on the old one. The tone below is on CH1 and CH2 identically. CH2 appears in front of CH1. spectrumanalyzer MATLAB Answers — New Questions
The single function is not behaving as expected
I’m trying to use single to save disk space because my files are very large. I know it could affect the precision if my numbers have many places after the decimal point. However, it is altering my integers as well.
>> single(340580097)
ans =
340580096.00
Is this a bug?I’m trying to use single to save disk space because my files are very large. I know it could affect the precision if my numbers have many places after the decimal point. However, it is altering my integers as well.
>> single(340580097)
ans =
340580096.00
Is this a bug? I’m trying to use single to save disk space because my files are very large. I know it could affect the precision if my numbers have many places after the decimal point. However, it is altering my integers as well.
>> single(340580097)
ans =
340580096.00
Is this a bug? single MATLAB Answers — New Questions
How can I view the Speedgoat target screen and system log on my host computer?
Can I view the display connected to my Speedgoat target on my host computer to monitor the Simulink Real-Time (SLRT) simulation and take screenshots?Can I view the display connected to my Speedgoat target on my host computer to monitor the Simulink Real-Time (SLRT) simulation and take screenshots? Can I view the display connected to my Speedgoat target on my host computer to monitor the Simulink Real-Time (SLRT) simulation and take screenshots? slrt, targetscreen, statusmonitor, systemlog, console, log MATLAB Answers — New Questions
Optmize Model Hyperparameters using Directforecaster
Dear all,
Is it possible to optmize the hyperparameters when using the directforecaster function to predict times series?
clear
close
clc
Tbl = importAndPreprocessPortData;
Tbl.Year = year(Tbl.Time);
Tbl.Quarter = quarter(TEU.Time);
slidingWindowPartition = tspartition(height(Tbl),"SlidingWindow", 4, "TestSize", 24)
Mdl = directforecaster(Tbl, "TEU", "Horizon", 1:12, "Learner", "lsboost", "ResponseLags", 1:12, …
"LeadingPredictors", "all", "LeadingPredictorLags", {0:12, 0:12}, …
"Partition", slidingWindowPartition, "CategoricalPredictors", "Quarter") % I would like to optmize lsboost hyperparameters
predY = cvpredict(Mdl)Dear all,
Is it possible to optmize the hyperparameters when using the directforecaster function to predict times series?
clear
close
clc
Tbl = importAndPreprocessPortData;
Tbl.Year = year(Tbl.Time);
Tbl.Quarter = quarter(TEU.Time);
slidingWindowPartition = tspartition(height(Tbl),"SlidingWindow", 4, "TestSize", 24)
Mdl = directforecaster(Tbl, "TEU", "Horizon", 1:12, "Learner", "lsboost", "ResponseLags", 1:12, …
"LeadingPredictors", "all", "LeadingPredictorLags", {0:12, 0:12}, …
"Partition", slidingWindowPartition, "CategoricalPredictors", "Quarter") % I would like to optmize lsboost hyperparameters
predY = cvpredict(Mdl) Dear all,
Is it possible to optmize the hyperparameters when using the directforecaster function to predict times series?
clear
close
clc
Tbl = importAndPreprocessPortData;
Tbl.Year = year(Tbl.Time);
Tbl.Quarter = quarter(TEU.Time);
slidingWindowPartition = tspartition(height(Tbl),"SlidingWindow", 4, "TestSize", 24)
Mdl = directforecaster(Tbl, "TEU", "Horizon", 1:12, "Learner", "lsboost", "ResponseLags", 1:12, …
"LeadingPredictors", "all", "LeadingPredictorLags", {0:12, 0:12}, …
"Partition", slidingWindowPartition, "CategoricalPredictors", "Quarter") % I would like to optmize lsboost hyperparameters
predY = cvpredict(Mdl) directforecaster, time series MATLAB Answers — New Questions
Hi everyone, have a question about PINN.
Hi everyone, recently I started to work on PINN. I tried to apply Lie symmetries enhanced PINN (sPINN). For this purpose, I tried to train the Kdv equation in [1] with the same conditions. The problem is, in theory, sPINN must give a better approximation than classic PINN, but in my code, I think something is missing. I changed the initial condition, equation, and added the symmetry condition of the code in [2].
[1] Enforcing continuous symmetries in physics-informed neural network for solving forward and inverse problems of partial differential equations
[2] https://www.mathworks.com/help/deeplearning/ug/solve-partial-differential-equations-with-lbfgs-method-and-deep-learning.html
clear all;
close all;
clc;
%% Generate Training Data
% The first 25 is for the left/right boundary
numBoundaryConditionPoints = [128 128];
% This creates a row vector of 25 elements
x0BC1 = zeros(1,numBoundaryConditionPoints(1));
x0BC2 = ones(1,numBoundaryConditionPoints(2));
% This creates a vector of 25 equally spaced time points between 0 and 1.
t0BC1 = linspace(0,1,numBoundaryConditionPoints(1));
t0BC2 = linspace(0,1,numBoundaryConditionPoints(2));
% Calculate boundary
u0BC1 = 12*sech(-4*t0BC1).^2;
u0BC2 = 12*sech(1 – 4*t0BC2).^2;
numInitialConditionPoints = 256;
x0IC = linspace(0,1,numInitialConditionPoints);
t0IC = zeros(1,numInitialConditionPoints);
% Initial condition
u0IC = 12*sech(x0IC).^2;
% Group together the data for initial and boundary conditions.
X0 = [x0IC x0BC1 x0BC2];
T0 = [t0IC t0BC1 t0BC2];
U0 = [u0IC u0BC1 u0BC2];
% Defining the Number of Points
numInternalCollocationPoints = 10000;
% Generating Random Points in a Unit Square
points = rand(numInternalCollocationPoints,2);
dataX = 2*points(:,1);
dataT = points(:,2);
%% Define Neural Network Architecture
numBlocks = 8;
fcOutputSize = 20;
% This creates a fundamental block that will be repeated:
fcBlock = [
fullyConnectedLayer(fcOutputSize)
tanhLayer];
layers = [
featureInputLayer(2) % featureInputLayer(2): This is the input layer that accepts your features. The 2 corresponds to (x, t) coordinates.
repmat(fcBlock,[numBlocks 1]) % Creates a deep network: Input → Block 1 → Block 2 → … → Block N
fullyConnectedLayer(1)
];
% Convert the layer array to a dlnetwork object.
net = dlnetwork(layers);
% Training a PINN can result in better accuracy when the learnable parameters have data type double.
% Convert the network learnables to double using the dlupdate function.
% Note that not all neural networks support learnables of type double, for example, networks that use GPU optimizations that rely on learnables with type single.
net = dlupdate(@double,net);
%% Define Model Loss Function
% This is the core loss function that makes Physics-Informed Neural Networks (PINNs) work! It’s where the "physics" is enforced.
function [loss,gradients] = modelLoss(net,X,T,X0,T0,U0)
% Make predictions with the initial conditions.
XT = cat(1,X,T);
U = forward(net,XT);
% Calculate derivatives with respect to X and T.
X = stripdims(X);
T = stripdims(T);
U = stripdims(U);
Ux = dljacobian(U,X,1);
Ut = dljacobian(U,T,1);
% Calculate second-order derivatives with respect to X.
Uxx = dldivergence(Ux,X,1);
Uxxx = dldivergence(Uxx,X,1);
% Calculate mseF. (Physics Loss 1: The PDE)
f = Ut + U.*Ux + Uxxx;
mseF = mean(f.^2);
% Calculate mseG. (Physics Loss 2: Your new constraint)
g = 4.*Ux + Ut;% + (X.*U)./2;
mseG = mean(g.^2);
% Calculate mseU. (Data Loss: Initial + Boundary)
XT0 = cat(1,X0,T0);
U0Pred = forward(net,XT0);
mseU = l2loss(U0Pred,U0);
% Calculated loss
loss = mseF + mseU + mseG;
% Calculate gradients with respect to the learnable parameters.
gradients = dlgradient(loss,net.Learnables);
end
%% Specify the training options:
solverState = lbfgsState;
maxIterations = 500;
gradientTolerance = 1e-5;
stepTolerance = 1e-5;
%% Train Neural Network
% Convert the training data to dlarray objects.
% Specify that the inputs X and T have format "BC" (batch, channel) and that the initial conditions have format "CB" (channel, batch).
X = dlarray(dataX,"BC");
T = dlarray(dataT,"BC");
X0 = dlarray(X0,"CB");
T0 = dlarray(T0,"CB");
U0 = dlarray(U0,"CB");
% Accelerate the loss function using the dlaccelerate function.
accfun = dlaccelerate(@modelLoss);
% Create a function handle containing the loss function for the L-BFGS update step.
% In order to evaluate the dlgradient function inside the modelLoss function using automatic differentiation, use the dlfeval function.
lossFcn = @(net) dlfeval(accfun,net,X,T,X0,T0,U0);
% Initialize the TrainingProgressMonitor object.
% At each iteration, plot the loss and monitor the norm of the gradients and steps.
% Because the timer starts when you create the monitor object, make sure that you create the object close to the training loop.
monitor = trainingProgressMonitor( …
Metrics="TrainingLoss", …
Info=["Iteration" "GradientsNorm" "StepNorm"], …
XLabel="Iteration");
iteration = 0;
while iteration < maxIterations && ~monitor.Stop
iteration = iteration + 1;
[net, solverState] = lbfgsupdate(net,lossFcn,solverState);
updateInfo(monitor, …
Iteration=iteration, …
GradientsNorm=solverState.GradientsNorm, …
StepNorm=solverState.StepNorm);
recordMetrics(monitor,iteration,TrainingLoss=solverState.Loss);
monitor.Progress = 100*iteration/maxIterations;
if solverState.GradientsNorm < gradientTolerance || …
solverState.StepNorm < stepTolerance || …
solverState.LineSearchStatus == "failed"
break
end
end
%% Exact solution for your specific case
function U = solveEq(X,T)
U = 12*sech(X-4.*T).^2;
end
%% Evaluate Model Accuracy
tTest = [0.25 0.5 0.75 1];
numObservationsTest = numel(tTest);
szXTest = 1001;
XTest = linspace(0,1,szXTest);
XTest = dlarray(XTest,"CB");
% Test the model.
UPred = zeros(numObservationsTest,szXTest);
UTest = zeros(numObservationsTest,szXTest);
for i = 1:numObservationsTest
t = tTest(i);
TTest = repmat(t,[1 szXTest]);
TTest = dlarray(TTest,"CB");
XTTest = cat(1,XTest,TTest);
UPred(i,:) = forward(net,XTTest);
UTest(i,:) = solveEq(extractdata(XTest),t);
end
err = norm(UPred – UTest) / norm(UTest);
fprintf(‘Relative error: %en’, err);
figure
tiledlayout("flow")
for i = 1:numel(tTest)
nexttile
plot(XTest,UPred(i,:),"-",LineWidth=2);
hold on
plot(XTest, UTest(i,:),"–",LineWidth=2)
hold off
ylim([0, 13])
xlabel("x")
ylabel("u(x," + t + ")")
end
legend(["Prediction" "Target"])
%% Create Density Plots with Rainbow Color Range
% Create a finer grid for density plots
xGrid = linspace(0, 1, 200);
tGrid = linspace(0, 1, 100);
[XGrid, TGrid] = meshgrid(xGrid, tGrid);
% Create predicted solution matrix
UPredDensity = zeros(length(tGrid), length(xGrid));
UTestDensity = zeros(length(tGrid), length(xGrid));
% Generate predictions for each point in the grid
for i = 1:length(tGrid)
for j = 1:length(xGrid)
% Predicted solution
XPoint = dlarray(xGrid(j), "CB");
TPoint = dlarray(tGrid(i), "CB");
XTPoint = cat(1, XPoint, TPoint);
UPredDensity(i,j) = extractdata(forward(net, XTPoint));
% Exact solution
UTestDensity(i,j) = solveEq(XGrid(j), TGrid(i));
end
end
% Create density plots
figure(‘Position’, [100, 100, 1200, 500]);
% Predicted solution density plot
subplot(1,2,1);
imagesc(xGrid, tGrid, UPredDensity);
colormap(jet); % Rainbow colormap
colorbar;
axis xy; % Correct orientation (time increasing downward)
xlabel(‘x’);
ylabel(‘t’);
title(‘Predicted Solution Density’);
set(gca, ‘FontSize’, 12);
% Exact solution density plot
subplot(1,2,2);
imagesc(xGrid, tGrid, UTestDensity);
colormap(jet); % Rainbow colormap
colorbar;
axis xy; % Correct orientation (time increasing downward)
xlabel(‘x’);
ylabel(‘t’);
title(‘Exact Solution Density’);
set(gca, ‘FontSize’, 12);
% Add a main title
sgtitle(‘Solution Comparison – Density Plots’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’);
%% Line plots for specific time points (your original visualization)
figure(‘Position’, [100, 100, 1000, 800]);
tiledlayout("flow")
for i = 1:numel(tTest)
nexttile
plot(XTest,UPred(i,:),"-",LineWidth=2);
hold on
plot(XTest, UTest(i,:),"–",LineWidth=2)
hold off
ylim([0, 13])
xlabel("x")
ylabel("u(x," + tTest(i) + ")")
title(sprintf(‘t = %.2f’, tTest(i)))
end
legend(["Prediction" "Target"])
sgtitle(‘Solution Comparison – Time Slices’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’);Hi everyone, recently I started to work on PINN. I tried to apply Lie symmetries enhanced PINN (sPINN). For this purpose, I tried to train the Kdv equation in [1] with the same conditions. The problem is, in theory, sPINN must give a better approximation than classic PINN, but in my code, I think something is missing. I changed the initial condition, equation, and added the symmetry condition of the code in [2].
[1] Enforcing continuous symmetries in physics-informed neural network for solving forward and inverse problems of partial differential equations
[2] https://www.mathworks.com/help/deeplearning/ug/solve-partial-differential-equations-with-lbfgs-method-and-deep-learning.html
clear all;
close all;
clc;
%% Generate Training Data
% The first 25 is for the left/right boundary
numBoundaryConditionPoints = [128 128];
% This creates a row vector of 25 elements
x0BC1 = zeros(1,numBoundaryConditionPoints(1));
x0BC2 = ones(1,numBoundaryConditionPoints(2));
% This creates a vector of 25 equally spaced time points between 0 and 1.
t0BC1 = linspace(0,1,numBoundaryConditionPoints(1));
t0BC2 = linspace(0,1,numBoundaryConditionPoints(2));
% Calculate boundary
u0BC1 = 12*sech(-4*t0BC1).^2;
u0BC2 = 12*sech(1 – 4*t0BC2).^2;
numInitialConditionPoints = 256;
x0IC = linspace(0,1,numInitialConditionPoints);
t0IC = zeros(1,numInitialConditionPoints);
% Initial condition
u0IC = 12*sech(x0IC).^2;
% Group together the data for initial and boundary conditions.
X0 = [x0IC x0BC1 x0BC2];
T0 = [t0IC t0BC1 t0BC2];
U0 = [u0IC u0BC1 u0BC2];
% Defining the Number of Points
numInternalCollocationPoints = 10000;
% Generating Random Points in a Unit Square
points = rand(numInternalCollocationPoints,2);
dataX = 2*points(:,1);
dataT = points(:,2);
%% Define Neural Network Architecture
numBlocks = 8;
fcOutputSize = 20;
% This creates a fundamental block that will be repeated:
fcBlock = [
fullyConnectedLayer(fcOutputSize)
tanhLayer];
layers = [
featureInputLayer(2) % featureInputLayer(2): This is the input layer that accepts your features. The 2 corresponds to (x, t) coordinates.
repmat(fcBlock,[numBlocks 1]) % Creates a deep network: Input → Block 1 → Block 2 → … → Block N
fullyConnectedLayer(1)
];
% Convert the layer array to a dlnetwork object.
net = dlnetwork(layers);
% Training a PINN can result in better accuracy when the learnable parameters have data type double.
% Convert the network learnables to double using the dlupdate function.
% Note that not all neural networks support learnables of type double, for example, networks that use GPU optimizations that rely on learnables with type single.
net = dlupdate(@double,net);
%% Define Model Loss Function
% This is the core loss function that makes Physics-Informed Neural Networks (PINNs) work! It’s where the "physics" is enforced.
function [loss,gradients] = modelLoss(net,X,T,X0,T0,U0)
% Make predictions with the initial conditions.
XT = cat(1,X,T);
U = forward(net,XT);
% Calculate derivatives with respect to X and T.
X = stripdims(X);
T = stripdims(T);
U = stripdims(U);
Ux = dljacobian(U,X,1);
Ut = dljacobian(U,T,1);
% Calculate second-order derivatives with respect to X.
Uxx = dldivergence(Ux,X,1);
Uxxx = dldivergence(Uxx,X,1);
% Calculate mseF. (Physics Loss 1: The PDE)
f = Ut + U.*Ux + Uxxx;
mseF = mean(f.^2);
% Calculate mseG. (Physics Loss 2: Your new constraint)
g = 4.*Ux + Ut;% + (X.*U)./2;
mseG = mean(g.^2);
% Calculate mseU. (Data Loss: Initial + Boundary)
XT0 = cat(1,X0,T0);
U0Pred = forward(net,XT0);
mseU = l2loss(U0Pred,U0);
% Calculated loss
loss = mseF + mseU + mseG;
% Calculate gradients with respect to the learnable parameters.
gradients = dlgradient(loss,net.Learnables);
end
%% Specify the training options:
solverState = lbfgsState;
maxIterations = 500;
gradientTolerance = 1e-5;
stepTolerance = 1e-5;
%% Train Neural Network
% Convert the training data to dlarray objects.
% Specify that the inputs X and T have format "BC" (batch, channel) and that the initial conditions have format "CB" (channel, batch).
X = dlarray(dataX,"BC");
T = dlarray(dataT,"BC");
X0 = dlarray(X0,"CB");
T0 = dlarray(T0,"CB");
U0 = dlarray(U0,"CB");
% Accelerate the loss function using the dlaccelerate function.
accfun = dlaccelerate(@modelLoss);
% Create a function handle containing the loss function for the L-BFGS update step.
% In order to evaluate the dlgradient function inside the modelLoss function using automatic differentiation, use the dlfeval function.
lossFcn = @(net) dlfeval(accfun,net,X,T,X0,T0,U0);
% Initialize the TrainingProgressMonitor object.
% At each iteration, plot the loss and monitor the norm of the gradients and steps.
% Because the timer starts when you create the monitor object, make sure that you create the object close to the training loop.
monitor = trainingProgressMonitor( …
Metrics="TrainingLoss", …
Info=["Iteration" "GradientsNorm" "StepNorm"], …
XLabel="Iteration");
iteration = 0;
while iteration < maxIterations && ~monitor.Stop
iteration = iteration + 1;
[net, solverState] = lbfgsupdate(net,lossFcn,solverState);
updateInfo(monitor, …
Iteration=iteration, …
GradientsNorm=solverState.GradientsNorm, …
StepNorm=solverState.StepNorm);
recordMetrics(monitor,iteration,TrainingLoss=solverState.Loss);
monitor.Progress = 100*iteration/maxIterations;
if solverState.GradientsNorm < gradientTolerance || …
solverState.StepNorm < stepTolerance || …
solverState.LineSearchStatus == "failed"
break
end
end
%% Exact solution for your specific case
function U = solveEq(X,T)
U = 12*sech(X-4.*T).^2;
end
%% Evaluate Model Accuracy
tTest = [0.25 0.5 0.75 1];
numObservationsTest = numel(tTest);
szXTest = 1001;
XTest = linspace(0,1,szXTest);
XTest = dlarray(XTest,"CB");
% Test the model.
UPred = zeros(numObservationsTest,szXTest);
UTest = zeros(numObservationsTest,szXTest);
for i = 1:numObservationsTest
t = tTest(i);
TTest = repmat(t,[1 szXTest]);
TTest = dlarray(TTest,"CB");
XTTest = cat(1,XTest,TTest);
UPred(i,:) = forward(net,XTTest);
UTest(i,:) = solveEq(extractdata(XTest),t);
end
err = norm(UPred – UTest) / norm(UTest);
fprintf(‘Relative error: %en’, err);
figure
tiledlayout("flow")
for i = 1:numel(tTest)
nexttile
plot(XTest,UPred(i,:),"-",LineWidth=2);
hold on
plot(XTest, UTest(i,:),"–",LineWidth=2)
hold off
ylim([0, 13])
xlabel("x")
ylabel("u(x," + t + ")")
end
legend(["Prediction" "Target"])
%% Create Density Plots with Rainbow Color Range
% Create a finer grid for density plots
xGrid = linspace(0, 1, 200);
tGrid = linspace(0, 1, 100);
[XGrid, TGrid] = meshgrid(xGrid, tGrid);
% Create predicted solution matrix
UPredDensity = zeros(length(tGrid), length(xGrid));
UTestDensity = zeros(length(tGrid), length(xGrid));
% Generate predictions for each point in the grid
for i = 1:length(tGrid)
for j = 1:length(xGrid)
% Predicted solution
XPoint = dlarray(xGrid(j), "CB");
TPoint = dlarray(tGrid(i), "CB");
XTPoint = cat(1, XPoint, TPoint);
UPredDensity(i,j) = extractdata(forward(net, XTPoint));
% Exact solution
UTestDensity(i,j) = solveEq(XGrid(j), TGrid(i));
end
end
% Create density plots
figure(‘Position’, [100, 100, 1200, 500]);
% Predicted solution density plot
subplot(1,2,1);
imagesc(xGrid, tGrid, UPredDensity);
colormap(jet); % Rainbow colormap
colorbar;
axis xy; % Correct orientation (time increasing downward)
xlabel(‘x’);
ylabel(‘t’);
title(‘Predicted Solution Density’);
set(gca, ‘FontSize’, 12);
% Exact solution density plot
subplot(1,2,2);
imagesc(xGrid, tGrid, UTestDensity);
colormap(jet); % Rainbow colormap
colorbar;
axis xy; % Correct orientation (time increasing downward)
xlabel(‘x’);
ylabel(‘t’);
title(‘Exact Solution Density’);
set(gca, ‘FontSize’, 12);
% Add a main title
sgtitle(‘Solution Comparison – Density Plots’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’);
%% Line plots for specific time points (your original visualization)
figure(‘Position’, [100, 100, 1000, 800]);
tiledlayout("flow")
for i = 1:numel(tTest)
nexttile
plot(XTest,UPred(i,:),"-",LineWidth=2);
hold on
plot(XTest, UTest(i,:),"–",LineWidth=2)
hold off
ylim([0, 13])
xlabel("x")
ylabel("u(x," + tTest(i) + ")")
title(sprintf(‘t = %.2f’, tTest(i)))
end
legend(["Prediction" "Target"])
sgtitle(‘Solution Comparison – Time Slices’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’); Hi everyone, recently I started to work on PINN. I tried to apply Lie symmetries enhanced PINN (sPINN). For this purpose, I tried to train the Kdv equation in [1] with the same conditions. The problem is, in theory, sPINN must give a better approximation than classic PINN, but in my code, I think something is missing. I changed the initial condition, equation, and added the symmetry condition of the code in [2].
[1] Enforcing continuous symmetries in physics-informed neural network for solving forward and inverse problems of partial differential equations
[2] https://www.mathworks.com/help/deeplearning/ug/solve-partial-differential-equations-with-lbfgs-method-and-deep-learning.html
clear all;
close all;
clc;
%% Generate Training Data
% The first 25 is for the left/right boundary
numBoundaryConditionPoints = [128 128];
% This creates a row vector of 25 elements
x0BC1 = zeros(1,numBoundaryConditionPoints(1));
x0BC2 = ones(1,numBoundaryConditionPoints(2));
% This creates a vector of 25 equally spaced time points between 0 and 1.
t0BC1 = linspace(0,1,numBoundaryConditionPoints(1));
t0BC2 = linspace(0,1,numBoundaryConditionPoints(2));
% Calculate boundary
u0BC1 = 12*sech(-4*t0BC1).^2;
u0BC2 = 12*sech(1 – 4*t0BC2).^2;
numInitialConditionPoints = 256;
x0IC = linspace(0,1,numInitialConditionPoints);
t0IC = zeros(1,numInitialConditionPoints);
% Initial condition
u0IC = 12*sech(x0IC).^2;
% Group together the data for initial and boundary conditions.
X0 = [x0IC x0BC1 x0BC2];
T0 = [t0IC t0BC1 t0BC2];
U0 = [u0IC u0BC1 u0BC2];
% Defining the Number of Points
numInternalCollocationPoints = 10000;
% Generating Random Points in a Unit Square
points = rand(numInternalCollocationPoints,2);
dataX = 2*points(:,1);
dataT = points(:,2);
%% Define Neural Network Architecture
numBlocks = 8;
fcOutputSize = 20;
% This creates a fundamental block that will be repeated:
fcBlock = [
fullyConnectedLayer(fcOutputSize)
tanhLayer];
layers = [
featureInputLayer(2) % featureInputLayer(2): This is the input layer that accepts your features. The 2 corresponds to (x, t) coordinates.
repmat(fcBlock,[numBlocks 1]) % Creates a deep network: Input → Block 1 → Block 2 → … → Block N
fullyConnectedLayer(1)
];
% Convert the layer array to a dlnetwork object.
net = dlnetwork(layers);
% Training a PINN can result in better accuracy when the learnable parameters have data type double.
% Convert the network learnables to double using the dlupdate function.
% Note that not all neural networks support learnables of type double, for example, networks that use GPU optimizations that rely on learnables with type single.
net = dlupdate(@double,net);
%% Define Model Loss Function
% This is the core loss function that makes Physics-Informed Neural Networks (PINNs) work! It’s where the "physics" is enforced.
function [loss,gradients] = modelLoss(net,X,T,X0,T0,U0)
% Make predictions with the initial conditions.
XT = cat(1,X,T);
U = forward(net,XT);
% Calculate derivatives with respect to X and T.
X = stripdims(X);
T = stripdims(T);
U = stripdims(U);
Ux = dljacobian(U,X,1);
Ut = dljacobian(U,T,1);
% Calculate second-order derivatives with respect to X.
Uxx = dldivergence(Ux,X,1);
Uxxx = dldivergence(Uxx,X,1);
% Calculate mseF. (Physics Loss 1: The PDE)
f = Ut + U.*Ux + Uxxx;
mseF = mean(f.^2);
% Calculate mseG. (Physics Loss 2: Your new constraint)
g = 4.*Ux + Ut;% + (X.*U)./2;
mseG = mean(g.^2);
% Calculate mseU. (Data Loss: Initial + Boundary)
XT0 = cat(1,X0,T0);
U0Pred = forward(net,XT0);
mseU = l2loss(U0Pred,U0);
% Calculated loss
loss = mseF + mseU + mseG;
% Calculate gradients with respect to the learnable parameters.
gradients = dlgradient(loss,net.Learnables);
end
%% Specify the training options:
solverState = lbfgsState;
maxIterations = 500;
gradientTolerance = 1e-5;
stepTolerance = 1e-5;
%% Train Neural Network
% Convert the training data to dlarray objects.
% Specify that the inputs X and T have format "BC" (batch, channel) and that the initial conditions have format "CB" (channel, batch).
X = dlarray(dataX,"BC");
T = dlarray(dataT,"BC");
X0 = dlarray(X0,"CB");
T0 = dlarray(T0,"CB");
U0 = dlarray(U0,"CB");
% Accelerate the loss function using the dlaccelerate function.
accfun = dlaccelerate(@modelLoss);
% Create a function handle containing the loss function for the L-BFGS update step.
% In order to evaluate the dlgradient function inside the modelLoss function using automatic differentiation, use the dlfeval function.
lossFcn = @(net) dlfeval(accfun,net,X,T,X0,T0,U0);
% Initialize the TrainingProgressMonitor object.
% At each iteration, plot the loss and monitor the norm of the gradients and steps.
% Because the timer starts when you create the monitor object, make sure that you create the object close to the training loop.
monitor = trainingProgressMonitor( …
Metrics="TrainingLoss", …
Info=["Iteration" "GradientsNorm" "StepNorm"], …
XLabel="Iteration");
iteration = 0;
while iteration < maxIterations && ~monitor.Stop
iteration = iteration + 1;
[net, solverState] = lbfgsupdate(net,lossFcn,solverState);
updateInfo(monitor, …
Iteration=iteration, …
GradientsNorm=solverState.GradientsNorm, …
StepNorm=solverState.StepNorm);
recordMetrics(monitor,iteration,TrainingLoss=solverState.Loss);
monitor.Progress = 100*iteration/maxIterations;
if solverState.GradientsNorm < gradientTolerance || …
solverState.StepNorm < stepTolerance || …
solverState.LineSearchStatus == "failed"
break
end
end
%% Exact solution for your specific case
function U = solveEq(X,T)
U = 12*sech(X-4.*T).^2;
end
%% Evaluate Model Accuracy
tTest = [0.25 0.5 0.75 1];
numObservationsTest = numel(tTest);
szXTest = 1001;
XTest = linspace(0,1,szXTest);
XTest = dlarray(XTest,"CB");
% Test the model.
UPred = zeros(numObservationsTest,szXTest);
UTest = zeros(numObservationsTest,szXTest);
for i = 1:numObservationsTest
t = tTest(i);
TTest = repmat(t,[1 szXTest]);
TTest = dlarray(TTest,"CB");
XTTest = cat(1,XTest,TTest);
UPred(i,:) = forward(net,XTTest);
UTest(i,:) = solveEq(extractdata(XTest),t);
end
err = norm(UPred – UTest) / norm(UTest);
fprintf(‘Relative error: %en’, err);
figure
tiledlayout("flow")
for i = 1:numel(tTest)
nexttile
plot(XTest,UPred(i,:),"-",LineWidth=2);
hold on
plot(XTest, UTest(i,:),"–",LineWidth=2)
hold off
ylim([0, 13])
xlabel("x")
ylabel("u(x," + t + ")")
end
legend(["Prediction" "Target"])
%% Create Density Plots with Rainbow Color Range
% Create a finer grid for density plots
xGrid = linspace(0, 1, 200);
tGrid = linspace(0, 1, 100);
[XGrid, TGrid] = meshgrid(xGrid, tGrid);
% Create predicted solution matrix
UPredDensity = zeros(length(tGrid), length(xGrid));
UTestDensity = zeros(length(tGrid), length(xGrid));
% Generate predictions for each point in the grid
for i = 1:length(tGrid)
for j = 1:length(xGrid)
% Predicted solution
XPoint = dlarray(xGrid(j), "CB");
TPoint = dlarray(tGrid(i), "CB");
XTPoint = cat(1, XPoint, TPoint);
UPredDensity(i,j) = extractdata(forward(net, XTPoint));
% Exact solution
UTestDensity(i,j) = solveEq(XGrid(j), TGrid(i));
end
end
% Create density plots
figure(‘Position’, [100, 100, 1200, 500]);
% Predicted solution density plot
subplot(1,2,1);
imagesc(xGrid, tGrid, UPredDensity);
colormap(jet); % Rainbow colormap
colorbar;
axis xy; % Correct orientation (time increasing downward)
xlabel(‘x’);
ylabel(‘t’);
title(‘Predicted Solution Density’);
set(gca, ‘FontSize’, 12);
% Exact solution density plot
subplot(1,2,2);
imagesc(xGrid, tGrid, UTestDensity);
colormap(jet); % Rainbow colormap
colorbar;
axis xy; % Correct orientation (time increasing downward)
xlabel(‘x’);
ylabel(‘t’);
title(‘Exact Solution Density’);
set(gca, ‘FontSize’, 12);
% Add a main title
sgtitle(‘Solution Comparison – Density Plots’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’);
%% Line plots for specific time points (your original visualization)
figure(‘Position’, [100, 100, 1000, 800]);
tiledlayout("flow")
for i = 1:numel(tTest)
nexttile
plot(XTest,UPred(i,:),"-",LineWidth=2);
hold on
plot(XTest, UTest(i,:),"–",LineWidth=2)
hold off
ylim([0, 13])
xlabel("x")
ylabel("u(x," + tTest(i) + ")")
title(sprintf(‘t = %.2f’, tTest(i)))
end
legend(["Prediction" "Target"])
sgtitle(‘Solution Comparison – Time Slices’, ‘FontSize’, 14, ‘FontWeight’, ‘bold’); pinn, deep learning, neural network, neural networks, pde, physics-informed neural network MATLAB Answers — New Questions
How to open variables window in the same place with workspace?
I have used MATLAB for a long time, and I am happy with it. I used to open the workspace windows and the variables windows in the same place (demonstrated in the figure) in R2024 and before. But since version R2025, I cannot do this anymore. Can someone help me solve this problem? I really enjoy it when I can see my workspace and variable at the same time, without switching between them; that is complicated.I have used MATLAB for a long time, and I am happy with it. I used to open the workspace windows and the variables windows in the same place (demonstrated in the figure) in R2024 and before. But since version R2025, I cannot do this anymore. Can someone help me solve this problem? I really enjoy it when I can see my workspace and variable at the same time, without switching between them; that is complicated. I have used MATLAB for a long time, and I am happy with it. I used to open the workspace windows and the variables windows in the same place (demonstrated in the figure) in R2024 and before. But since version R2025, I cannot do this anymore. Can someone help me solve this problem? I really enjoy it when I can see my workspace and variable at the same time, without switching between them; that is complicated. user interface, matlab compiler, workspace, variables MATLAB Answers — New Questions
Generating Toeplitz Matrix which Matches the Convolution Shape Same
Given a filter vH I’m looking for vectors vR and vC such that:
toeplitz(vC, vR) * vX = conv(vX, vH, ‘same’);
For instance, for vH = [1, 2, 3, 4] and length(vX) = 7; the matrix is given by:
mH =
3 2 1 0 0 0 0
4 3 2 1 0 0 0
0 4 3 2 1 0 0
0 0 4 3 2 1 0
0 0 0 4 3 2 1
0 0 0 0 4 3 2
0 0 0 0 0 4 3Given a filter vH I’m looking for vectors vR and vC such that:
toeplitz(vC, vR) * vX = conv(vX, vH, ‘same’);
For instance, for vH = [1, 2, 3, 4] and length(vX) = 7; the matrix is given by:
mH =
3 2 1 0 0 0 0
4 3 2 1 0 0 0
0 4 3 2 1 0 0
0 0 4 3 2 1 0
0 0 0 4 3 2 1
0 0 0 0 4 3 2
0 0 0 0 0 4 3 Given a filter vH I’m looking for vectors vR and vC such that:
toeplitz(vC, vR) * vX = conv(vX, vH, ‘same’);
For instance, for vH = [1, 2, 3, 4] and length(vX) = 7; the matrix is given by:
mH =
3 2 1 0 0 0 0
4 3 2 1 0 0 0
0 4 3 2 1 0 0
0 0 4 3 2 1 0
0 0 0 4 3 2 1
0 0 0 0 4 3 2
0 0 0 0 0 4 3 convolution, matrix, toeplitz, convolution-matrix MATLAB Answers — New Questions
How to analyze reaction time and slicing accuracy data from a simple game like Slice Master in MATLAB?
Hi everyone, I’ve been experimenting with a reflex-based game called Slice Master to study human reaction times and precision. I can export gameplay logs that include timestamps for each slice, slice angle, and whether the slice was “perfect” or not.
My goal is to import this data into MATLAB and:
Compute reaction times between successive slices.
Plot a histogram of slice-to-slice reaction times.
Analyze the distribution of slice angles (e.g., deviation from ideal).
Identify “runs” of perfect slices (longest streak, average streak length).
Possibly apply a smoothing filter or clustering to reaction times to detect outliers or performance shifts.
What MATLAB functions / toolboxes would you recommend for these tasks? And what is the best way to structure this kind of gameplay data for analysis (e.g., timetable, table, struct)? Any example code snippets or guidance would be greatly appreciated!Hi everyone, I’ve been experimenting with a reflex-based game called Slice Master to study human reaction times and precision. I can export gameplay logs that include timestamps for each slice, slice angle, and whether the slice was “perfect” or not.
My goal is to import this data into MATLAB and:
Compute reaction times between successive slices.
Plot a histogram of slice-to-slice reaction times.
Analyze the distribution of slice angles (e.g., deviation from ideal).
Identify “runs” of perfect slices (longest streak, average streak length).
Possibly apply a smoothing filter or clustering to reaction times to detect outliers or performance shifts.
What MATLAB functions / toolboxes would you recommend for these tasks? And what is the best way to structure this kind of gameplay data for analysis (e.g., timetable, table, struct)? Any example code snippets or guidance would be greatly appreciated! Hi everyone, I’ve been experimenting with a reflex-based game called Slice Master to study human reaction times and precision. I can export gameplay logs that include timestamps for each slice, slice angle, and whether the slice was “perfect” or not.
My goal is to import this data into MATLAB and:
Compute reaction times between successive slices.
Plot a histogram of slice-to-slice reaction times.
Analyze the distribution of slice angles (e.g., deviation from ideal).
Identify “runs” of perfect slices (longest streak, average streak length).
Possibly apply a smoothing filter or clustering to reaction times to detect outliers or performance shifts.
What MATLAB functions / toolboxes would you recommend for these tasks? And what is the best way to structure this kind of gameplay data for analysis (e.g., timetable, table, struct)? Any example code snippets or guidance would be greatly appreciated! matrix, game MATLAB Answers — New Questions
FFT problem: FFT -> some manipulation -> IFFT results in one-element shift
I am trying to take some random noise (produced by a different script), Fourier transform it, multiply it by a filter, and then do an inverse Fourier transform to get some random noise data back. When I was testing my script with a filter which has a value of 1 for all frequencies (i.e. should give back the original data after IFFT), I realized all of the resulting values are shifted by 1 element. I.e., if I plot the original vs multiplied (‘calibrated’) noise it looks like this:
but then if I just circshift one of the arrays, either the noise given or the post-FT noise, by 1 (in opposite directions), it looks like this:
(and the values of the two arrays are equal to within 1e-15 tolerance, which is good enough for my purpose). I suspect the problem is how I’m setting up my frequency arrays/interpolating my actual function I need to multiply by, but I’m pretty much stuck after that–any suggestions would be appreciated.
More in-depth info
Full script is attached (spaghetti code beware, apologies in advance), but it has a lot of plots/troubleshooting, so here is the relevant code:
%%read files
[tempFile, tempPath] = uigetfile(‘*.csv’, ‘Select the calibration data file’);
calData = readmatrix(fullfile(tempPath, tempFile));
[tempFile2, tempPath2] = uigetfile(‘*.txt’, ‘Select the random noise’);
randNoise = readmatrix(fullfile(tempPath2, tempFile2));
%% Sort and format calibration daya
%sort calibration data by period
clDatSorted=sortrows(calData,[1]);
%extract data
periods = clDatSorted(:,1);
ampsRequired = clDatSorted(:,2);
%mirror the function in the negative frequency domain due to the nature of
%the FT function
ampsRequired = [flip(ampsRequired);ampsRequired];
periods = [flip(periods)*-1;periods];
freqs = 1./periods;
%% Fourier transform the random noise and plot
fourierNoise = fft(randNoise);
fourierNoise = fftshift(fourierNoise); %fftshift used here to center zero-frequency value
Ts = inputdlg(‘What is the sample period?’); %sample period; user defined because of the way the script to generate my noise is set up
Ts=str2num(Ts{1}); %convert to a number
f= ((-length(fourierNoise)/2):((length(fourierNoise)/2)-1))*fs/length(fourierNoise);
%% interpolate calibration function
%this is going to be important because my calibration function is manually
%obtained so I will need to extrapolate *and* interpolate, unfortunately–I
%can’t just give it a smooth function due to the nature of the data
interpolatedCal=interp1(freqs(2:end-1),ampsRequired(2:end-1),f,’linear’,’extrap’);
%% calibrate
calibratedFourierNoise = interpolatedCal .* fourierNoise’;
calibratedNoise = ifft(ifftshift(calibratedFourierNoise));
if size(calibratedNoise)~=size(randNoise)
calibratedNoise = flip(calibratedNoise); %to fix row-column swaps–I know this needs a better fix
end
And
ismembertol(circshift(randNoise,[0, 1]),calibratedNoise,1e-15)
produces 1’s everywhere.
I think the line where I define my frequency:
f= ((-length(fourierNoise)/2):((length(fourierNoise)/2)-1))*fs/length(fourierNoise);
is the root of the problem but I’ve tried playing around with it and keep encountering the same issue.
In particular, if I do
[p,fp] = pspectrum(randNoise);
the maximum frequency it gives me is 3.14 for this data, and I’m assuming that the max frequency for the Fourier transform is 1/2 the number of random noise values per second–I feel like this is an issue with my lack of deep understanding of Fourier theory tbh, but I can’t pinpoint the exact issue.
Full script/test calibration file with ones everywhere (i.e. flat filter)/sample noise/sample calibration (with ones everywhere as used for the test in sampleCalOneEverywhere and as the filter I’ll aactually be using in sampleCal1) are attached.
(Not super relevant but the final filter will be an empirically-obtained low-pass filter with some added stuff.)I am trying to take some random noise (produced by a different script), Fourier transform it, multiply it by a filter, and then do an inverse Fourier transform to get some random noise data back. When I was testing my script with a filter which has a value of 1 for all frequencies (i.e. should give back the original data after IFFT), I realized all of the resulting values are shifted by 1 element. I.e., if I plot the original vs multiplied (‘calibrated’) noise it looks like this:
but then if I just circshift one of the arrays, either the noise given or the post-FT noise, by 1 (in opposite directions), it looks like this:
(and the values of the two arrays are equal to within 1e-15 tolerance, which is good enough for my purpose). I suspect the problem is how I’m setting up my frequency arrays/interpolating my actual function I need to multiply by, but I’m pretty much stuck after that–any suggestions would be appreciated.
More in-depth info
Full script is attached (spaghetti code beware, apologies in advance), but it has a lot of plots/troubleshooting, so here is the relevant code:
%%read files
[tempFile, tempPath] = uigetfile(‘*.csv’, ‘Select the calibration data file’);
calData = readmatrix(fullfile(tempPath, tempFile));
[tempFile2, tempPath2] = uigetfile(‘*.txt’, ‘Select the random noise’);
randNoise = readmatrix(fullfile(tempPath2, tempFile2));
%% Sort and format calibration daya
%sort calibration data by period
clDatSorted=sortrows(calData,[1]);
%extract data
periods = clDatSorted(:,1);
ampsRequired = clDatSorted(:,2);
%mirror the function in the negative frequency domain due to the nature of
%the FT function
ampsRequired = [flip(ampsRequired);ampsRequired];
periods = [flip(periods)*-1;periods];
freqs = 1./periods;
%% Fourier transform the random noise and plot
fourierNoise = fft(randNoise);
fourierNoise = fftshift(fourierNoise); %fftshift used here to center zero-frequency value
Ts = inputdlg(‘What is the sample period?’); %sample period; user defined because of the way the script to generate my noise is set up
Ts=str2num(Ts{1}); %convert to a number
f= ((-length(fourierNoise)/2):((length(fourierNoise)/2)-1))*fs/length(fourierNoise);
%% interpolate calibration function
%this is going to be important because my calibration function is manually
%obtained so I will need to extrapolate *and* interpolate, unfortunately–I
%can’t just give it a smooth function due to the nature of the data
interpolatedCal=interp1(freqs(2:end-1),ampsRequired(2:end-1),f,’linear’,’extrap’);
%% calibrate
calibratedFourierNoise = interpolatedCal .* fourierNoise’;
calibratedNoise = ifft(ifftshift(calibratedFourierNoise));
if size(calibratedNoise)~=size(randNoise)
calibratedNoise = flip(calibratedNoise); %to fix row-column swaps–I know this needs a better fix
end
And
ismembertol(circshift(randNoise,[0, 1]),calibratedNoise,1e-15)
produces 1’s everywhere.
I think the line where I define my frequency:
f= ((-length(fourierNoise)/2):((length(fourierNoise)/2)-1))*fs/length(fourierNoise);
is the root of the problem but I’ve tried playing around with it and keep encountering the same issue.
In particular, if I do
[p,fp] = pspectrum(randNoise);
the maximum frequency it gives me is 3.14 for this data, and I’m assuming that the max frequency for the Fourier transform is 1/2 the number of random noise values per second–I feel like this is an issue with my lack of deep understanding of Fourier theory tbh, but I can’t pinpoint the exact issue.
Full script/test calibration file with ones everywhere (i.e. flat filter)/sample noise/sample calibration (with ones everywhere as used for the test in sampleCalOneEverywhere and as the filter I’ll aactually be using in sampleCal1) are attached.
(Not super relevant but the final filter will be an empirically-obtained low-pass filter with some added stuff.) I am trying to take some random noise (produced by a different script), Fourier transform it, multiply it by a filter, and then do an inverse Fourier transform to get some random noise data back. When I was testing my script with a filter which has a value of 1 for all frequencies (i.e. should give back the original data after IFFT), I realized all of the resulting values are shifted by 1 element. I.e., if I plot the original vs multiplied (‘calibrated’) noise it looks like this:
but then if I just circshift one of the arrays, either the noise given or the post-FT noise, by 1 (in opposite directions), it looks like this:
(and the values of the two arrays are equal to within 1e-15 tolerance, which is good enough for my purpose). I suspect the problem is how I’m setting up my frequency arrays/interpolating my actual function I need to multiply by, but I’m pretty much stuck after that–any suggestions would be appreciated.
More in-depth info
Full script is attached (spaghetti code beware, apologies in advance), but it has a lot of plots/troubleshooting, so here is the relevant code:
%%read files
[tempFile, tempPath] = uigetfile(‘*.csv’, ‘Select the calibration data file’);
calData = readmatrix(fullfile(tempPath, tempFile));
[tempFile2, tempPath2] = uigetfile(‘*.txt’, ‘Select the random noise’);
randNoise = readmatrix(fullfile(tempPath2, tempFile2));
%% Sort and format calibration daya
%sort calibration data by period
clDatSorted=sortrows(calData,[1]);
%extract data
periods = clDatSorted(:,1);
ampsRequired = clDatSorted(:,2);
%mirror the function in the negative frequency domain due to the nature of
%the FT function
ampsRequired = [flip(ampsRequired);ampsRequired];
periods = [flip(periods)*-1;periods];
freqs = 1./periods;
%% Fourier transform the random noise and plot
fourierNoise = fft(randNoise);
fourierNoise = fftshift(fourierNoise); %fftshift used here to center zero-frequency value
Ts = inputdlg(‘What is the sample period?’); %sample period; user defined because of the way the script to generate my noise is set up
Ts=str2num(Ts{1}); %convert to a number
f= ((-length(fourierNoise)/2):((length(fourierNoise)/2)-1))*fs/length(fourierNoise);
%% interpolate calibration function
%this is going to be important because my calibration function is manually
%obtained so I will need to extrapolate *and* interpolate, unfortunately–I
%can’t just give it a smooth function due to the nature of the data
interpolatedCal=interp1(freqs(2:end-1),ampsRequired(2:end-1),f,’linear’,’extrap’);
%% calibrate
calibratedFourierNoise = interpolatedCal .* fourierNoise’;
calibratedNoise = ifft(ifftshift(calibratedFourierNoise));
if size(calibratedNoise)~=size(randNoise)
calibratedNoise = flip(calibratedNoise); %to fix row-column swaps–I know this needs a better fix
end
And
ismembertol(circshift(randNoise,[0, 1]),calibratedNoise,1e-15)
produces 1’s everywhere.
I think the line where I define my frequency:
f= ((-length(fourierNoise)/2):((length(fourierNoise)/2)-1))*fs/length(fourierNoise);
is the root of the problem but I’ve tried playing around with it and keep encountering the same issue.
In particular, if I do
[p,fp] = pspectrum(randNoise);
the maximum frequency it gives me is 3.14 for this data, and I’m assuming that the max frequency for the Fourier transform is 1/2 the number of random noise values per second–I feel like this is an issue with my lack of deep understanding of Fourier theory tbh, but I can’t pinpoint the exact issue.
Full script/test calibration file with ones everywhere (i.e. flat filter)/sample noise/sample calibration (with ones everywhere as used for the test in sampleCalOneEverywhere and as the filter I’ll aactually be using in sampleCal1) are attached.
(Not super relevant but the final filter will be an empirically-obtained low-pass filter with some added stuff.) fft, ifft, fourier transforms MATLAB Answers — New Questions
some manipulation -> IFFT results in one-element shift” />
Why am I unable to validate my LSF cluster profile in the Parallel Computing Toolbox?
I have MATLAB Parallel Server set up on a cluster running LSF. When I attempt to validate the cluster profile it fails.I have MATLAB Parallel Server set up on a cluster running LSF. When I attempt to validate the cluster profile it fails. I have MATLAB Parallel Server set up on a cluster running LSF. When I attempt to validate the cluster profile it fails. MATLAB Answers — New Questions
Maple toolbox for MATLAB
Is there anybody who is actively using latest version 2025 Maple toolbox (as a part of Maple) with MATLAB R2025b? I am not able to install the Maple toolbox on MATLAB R2025b on Linux (installation process hangs).
I need to use the Maple toolbox for complicated symbolic computing which is not possible to perform via MATLAB symbolic toolbox (many symbolic matrix exponentials of 6×6 symbolic matrices, which takes on Matlab symbolic toolbox enormous CPU time).Is there anybody who is actively using latest version 2025 Maple toolbox (as a part of Maple) with MATLAB R2025b? I am not able to install the Maple toolbox on MATLAB R2025b on Linux (installation process hangs).
I need to use the Maple toolbox for complicated symbolic computing which is not possible to perform via MATLAB symbolic toolbox (many symbolic matrix exponentials of 6×6 symbolic matrices, which takes on Matlab symbolic toolbox enormous CPU time). Is there anybody who is actively using latest version 2025 Maple toolbox (as a part of Maple) with MATLAB R2025b? I am not able to install the Maple toolbox on MATLAB R2025b on Linux (installation process hangs).
I need to use the Maple toolbox for complicated symbolic computing which is not possible to perform via MATLAB symbolic toolbox (many symbolic matrix exponentials of 6×6 symbolic matrices, which takes on Matlab symbolic toolbox enormous CPU time). maple MATLAB Answers — New Questions
insAccelerometer Documentation h(x)
I am currently working on building an Extended Kalman Filter with Accelerometer measurements and looked into the implementation of the h(x) measurement equation.
In the documentation and in the file this equation is, when estimating the acceleration in the state, h(x)=g_sensor+a_sensor+bias which is equal to h(x)=bias+R_sensor->navigation*(g_navigation+a_navigation). However, in the actual implementation of the measurement(sensor, filt) function h(x) appears to be calculated by h(x)=bias-R_sensor->navigation*(a_navigation – g_navigation).
Does anynone know why the actual implementation seems to be different to the documented equation?
Thanks in advance!I am currently working on building an Extended Kalman Filter with Accelerometer measurements and looked into the implementation of the h(x) measurement equation.
In the documentation and in the file this equation is, when estimating the acceleration in the state, h(x)=g_sensor+a_sensor+bias which is equal to h(x)=bias+R_sensor->navigation*(g_navigation+a_navigation). However, in the actual implementation of the measurement(sensor, filt) function h(x) appears to be calculated by h(x)=bias-R_sensor->navigation*(a_navigation – g_navigation).
Does anynone know why the actual implementation seems to be different to the documented equation?
Thanks in advance! I am currently working on building an Extended Kalman Filter with Accelerometer measurements and looked into the implementation of the h(x) measurement equation.
In the documentation and in the file this equation is, when estimating the acceleration in the state, h(x)=g_sensor+a_sensor+bias which is equal to h(x)=bias+R_sensor->navigation*(g_navigation+a_navigation). However, in the actual implementation of the measurement(sensor, filt) function h(x) appears to be calculated by h(x)=bias-R_sensor->navigation*(a_navigation – g_navigation).
Does anynone know why the actual implementation seems to be different to the documented equation?
Thanks in advance! insekf, insaccelerometer, sensor fusion MATLAB Answers — New Questions
Microsoft, NVIDIA and Anthropic announce strategic partnerships
Anthropic to scale Claude on Azure
Anthropic to adopt NVIDIA architecture
NVIDIA and Microsoft to invest in Anthropic
Today Microsoft, NVIDIA and Anthropic announced new strategic partnerships. Anthropic is scaling its rapidly-growing Claude AI model on Microsoft Azure, powered by NVIDIA, which will broaden access to Claude and provide Azure enterprise customers with expanded model choice and new capabilities. Anthropic has committed to purchase $30 billion of Azure compute capacity and to contract additional compute capacity up to one gigawatt.
For the first time, NVIDIA and Anthropic are establishing a deep technology partnership to support Anthropic’s future growth. Anthropic and NVIDIA will collaborate on design and engineering, with the goal of optimizing Anthropic models for the best possible performance, efficiency, and TCO, and optimizing future NVIDIA architectures for Anthropic workloads. Anthropic’s compute commitment will initially be up to one gigawatt of compute capacity with NVIDIA Grace Blackwell and Vera Rubin systems.
Microsoft and Anthropic are also expanding their existing partnership to provide broader access to Claude for businesses. Customers of Microsoft Foundry will be able to access Anthropic’s frontier Claude models including Claude Sonnet 4.5, Claude Opus 4.1, and Claude Haiku 4.5. This partnership will make Claude the only frontier model available on all three of the world’s most prominent cloud services. Azure customers will gain expanded choice in models and access to Claude-specific capabilities.
Microsoft has also committed to continuing access for Claude across Microsoft’s Copilot family, including GitHub Copilot, Microsoft 365 Copilot, and Copilot Studio.
As part of the partnership, NVIDIA and Microsoft are committing to invest up to $10 billion and up to $5 billion respectively in Anthropic.
Anthropic co-founder and CEO Dario Amodei, Microsoft Chairman and CEO Satya Nadella, and NVIDIA founder and CEO Jensen Huang gathered to discuss the new partnerships:
The post Microsoft, NVIDIA and Anthropic announce strategic partnerships appeared first on The Official Microsoft Blog.
Anthropic to scale Claude on Azure Anthropic to adopt NVIDIA architecture NVIDIA and Microsoft to invest in Anthropic Today Microsoft, NVIDIA and Anthropic announced new strategic partnerships. Anthropic is scaling its rapidly-growing Claude AI model on Microsoft Azure, powered by NVIDIA, which will broaden access to Claude and provide Azure enterprise customers with expanded model choice and new capabilities. Anthropic…
The post Microsoft, NVIDIA and Anthropic announce strategic partnerships appeared first on The Official Microsoft Blog.Read More
From idea to deployment: The complete lifecycle of AI on display at Ignite 2025
By now, most people would agree that AI is in the process of fundamentally changing how we work and solve problems. But this technology is still too often thought of as an addition to the work we do, rather than a fundamental part of it.
AI is not something that you can just plop on the end of a finished product, like a cherry on top of a sundae. Instead, using AI responsibly and wisely means thinking through how it can be used most effectively at every layer, from the datacenter that powers AI functionality to the people and organizations that are benefiting from its capabilities.
As we embark on another Microsoft Ignite, our company is empowering the complete lifecycle of AI, creating tools and solutions to drive the next generation of digital transformation for every organization and at every level of the work they do.
We envision a future where organizations become Frontier Firms by using AI for unlocking creativity and innovation, allowing the next great ideas to surface.
These are some of the major themes we are seeing with this year’s Ignite products and features:
AI in the flow of human ambition
At Microsoft, we believe that all great ideas start with human ambition, which can be accessed and unlocked using the capabilities in Microsoft 365 Copilot and an agent ecosystem.
Work IQ amplifies your IQ. It’s the intelligence layer that enables Microsoft 365 Copilot and agents to know how you work, with whom you work and the content you collaborate on. Built on your data, memory and inference, it connects to the rich company knowledge in your emails, files, meetings and chats, plus your preferences, habits, work patterns and relationships. It allows Copilot to make connections, unlock insights and predict the next best action based on native integrations, not a patchwork of third-party connectors. And now, you can tap into the expertise of Work IQ with APIs to build agents tuned to your unique workflows and business needs.
Work IQ also is powering many of the updates across Microsoft 365 Copilot announced at Ignite today.
Ubiquitous innovation and intelligence
In a Frontier Firm, there are makers in every room of the house. People on the frontlines are closest to the work problems that need to be solved. They can create agents to help them in their day-to-day work.
How do AI agents know what to do with your data? Foundry IQ and Fabric IQ help AI agents understand what users are doing, bridge the gap between raw data and real-world business meaning and find the context to make decisions.
Fabric IQ brings together analytical, time series and location-based data with your operational systems under one shared model tied to business meaning. This gives you a live, connected view of your business, so both people and AI can act in real time. If you are a customer who is already using Power BI for your business intelligence reporting, all of that pre-existing data modeling work will act as an immediate accelerant, giving your agents the unique context that defines how your business runs.
Foundry IQ takes this further with a fully managed knowledge system designed to ground AI agents over multiple data sources — including Microsoft 365 (Work IQ), Fabric IQ, custom applications and the web. This single endpoint for knowledge has routing and intelligence built in, enabling higher-quality reasoning, safer actions and more value for builders.
Microsoft Agent Factory is a program that brings these agent IQ layers together to help organizations build agents with confidence. With a single metered plan, customers can start building with IQ using Microsoft Foundry and Copilot Studio. They can deploy their agents anywhere, including Microsoft 365 Copilot, with no upfront licensing and provisioning required. Eligible organizations can also tap into hands-on support from top AI Forward Deployed Engineers and access tailored role-based training to boost AI fluency across teams.
Observability at every layer
By 2028, businesses are projected to have[1] 1.3 billion AI agents automating workflows. Most organizations don’t yet have a way to observe, secure or govern them — if not governed, AI agents are the new shadow IT.
Microsoft Agent 365 enables you to observe, manage and secure your AI agents, whether the agents are created with Microsoft platforms, open-source frameworks or third-party platforms.
It equips them with many of the same apps and protections as people, tailored to agent needs, saving IT time and effort on integrating agents into business processes. It includes the Microsoft security solutions Defender, Entra, Purview and Foundry Control Plane to protect and govern agents, productivity tools including Microsoft 365 apps and Work IQ to help people work more efficiently and Microsoft 365 admin center to manage agents.
This is only a small selection of the many exciting features and updates we will be announcing at Ignite. As a reminder, you can view keynote sessions from Microsoft executives, including Judson Althoff, Scott Guthrie, Charles Lamanna, Asha Sharma and Ryan Roslansky, live or on-demand.
Plus, you can get more on all these announcements by exploring the Book of News, the official compendium of all today’s news.
Frank X. Shaw is responsible for defining and managing communications strategies worldwide, company-wide storytelling, product PR, media and analyst relations, executive communications, employee communications, global agency management and military affairs.
Related:
Partners leading the AI transformation: Microsoft Ignite 2025 recap
[1] IDC Info Snapshot, sponsored by Microsoft, 1.3 Billion AI Agents by 2028, May 2025 #US53361825
The post From idea to deployment: The complete lifecycle of AI on display at Ignite 2025 appeared first on The Official Microsoft Blog.
By now, most people would agree that AI is in the process of fundamentally changing how we work and solve problems. But this technology is still too often thought of as an addition to the work we do, rather than a fundamental part of it. AI is not something that you can just plop on…
The post From idea to deployment: The complete lifecycle of AI on display at Ignite 2025 appeared first on The Official Microsoft Blog.Read More









