Hi community,
I am runnig my code for Lorenz system but it gives error of plot3 command, kindly can someone error in this code
%%Code%%
% Initial conditions for Lorenz system
x0 = [-8; 27; 7];
sigma = 10;
rho = 28;
beta = 8/3;
trueModel = @(t, y) [sigma * (y(2) - y(1)); y(1) * (rho - y(3)) - y(2); y(1) * y(2) - beta * y(3)];
% Simulation parameters (same as before)
numTimeSteps = 2000;
T = 10;
odeOptions = odeset('RelTol', 1.e-7);
t = linspace(0, T, numTimeSteps);
[~, xTrain] = ode45(trueModel, t, x0, odeOptions);
xTrain = xTrain';
% True model visualization (updated for 3D Lorenz system)
figure
plot3(xTrain(1, :), xTrain(2, :), xTrain(3, :))
title("Ground Truth Dynamics")
xlabel("x(1)")
ylabel("x(2)")
zlabel("x(3)")
grid on
neuralOdeTimesteps = 100;
dt = t(2);
timesteps = (0:neuralOdeTimesteps)*dt;
neuralOdeParameters = struct;
stateSize = size(xTrain,1);
hiddenSize = 20;
neuralOdeParameters.fc1 = struct;
sz = [hiddenSize stateSize];
neuralOdeParameters.fc1.Weights = initializeGlorot(sz, hiddenSize, stateSize);
neuralOdeParameters.fc1.Bias = initializeZeros([hiddenSize 1]);
neuralOdeParameters.fc2 = struct;
sz = [stateSize hiddenSize];
neuralOdeParameters.fc2.Weights = initializeGlorot(sz, stateSize, hiddenSize);
neuralOdeParameters.fc2.Bias = initializeZeros([stateSize 1]);
neuralOdeParameters.fc1
ans = struct with fields:
Weights: [20×3 dlarray] Bias: [20×1 dlarray]
neuralOdeParameters.fc2
ans = struct with fields:
Weights: [3×20 dlarray] Bias: [3×1 dlarray]
gradDecay = 0.9;
sqGradDecay = 0.99;
learnRate = 0.9;
numIter = 100;
miniBatchSize = 200;
plotFrequency = 50;
f = figure;
f.Position(3) = 2*f.Position(3);
subplot(1,2,1)
C = colororder;
lineLossTrain = animatedline(Color=C(2,:));
ylim([0 inf])
xlabel("Iteration")
ylabel("Loss")
grid on
averageGrad = [];
averageSqGrad = [];
numTrainingTimesteps = numTimeSteps;
trainingTimesteps = 1:numTrainingTimesteps;
plottingTimesteps = 2:numTimeSteps;
start = tic;
for iter = 1:numIter
% Create batch
[X, targets] = createMiniBatch(numTrainingTimesteps, neuralOdeTimesteps, miniBatchSize, xTrain);
% Evaluate network and compute loss and gradients
[loss,gradients] = dlfeval(@modelLoss,timesteps,X,neuralOdeParameters,targets);
% Update network
[neuralOdeParameters,averageGrad,averageSqGrad] = adamupdate(neuralOdeParameters,gradients,averageGrad,averageSqGrad,iter,...
learnRate,gradDecay,sqGradDecay);
% Plot loss
subplot(1,2,1)
currentLoss = double(loss);
addpoints(lineLossTrain,iter,currentLoss);
D = duration(0,0,toc(start),Format="hh:mm:ss");
title("Elapsed: " + string(D))
drawnow
% Plot predicted vs. real dynamics
if mod(iter,plotFrequency) == 0 || iter == 1
subplot(1,2,2)
% Use ode45 to compute the solution
y = dlode45(@odeModel,t,dlarray(x0),neuralOdeParameters,DataFormat="CB");
size(y)
% y = squeeze(y)';
plot3(xTrain(1,plottingTimesteps),xTrain(2,plottingTimesteps),xTrain(3,plottingTimesteps),"r--")
hold on
plot3(y(1,:),y(2,:),y(3,:),'b-')
hold off
xlabel("x")
ylabel("y")
zlabel("z")
title("Predicted vs. Real Dynamics")
legend("Training Ground Truth", "Predicted")
drawnow
end
end
ans = 1×3
3 1 1999
Error using plot3
Data must be numeric, datetime, duration, categorical, or an array convertible to double.
% Prediction and visualization (updated for 3D Lorenz system)
tPred = t;
x0Pred1 = [0; 2; 2];
x0Pred2 = [-1; -1.5; 0];
x0Pred3 = [2; 1; 0];
x0Pred4 = [-2; 0; 1];
[~, xTrue1] = ode45(trueModel, tPred, x0Pred1, odeOptions);
[~, xTrue2] = ode45(trueModel, tPred, x0Pred2, odeOptions);
[~, xTrue3] = ode45(trueModel, tPred, x0Pred3, odeOptions);
[~, xTrue4] = ode45(trueModel, tPred, x0Pred4, odeOptions);
xPred1 = dlode45(@odeModel, tPred, dlarray(x0Pred1), neuralOdeParameters, 'DataFormat', "CB");
size(xPred1)
xPred2 = dlode45(@odeModel, tPred, dlarray(x0Pred2), neuralOdeParameters, 'DataFormat', "CB");
xPred3 = dlode45(@odeModel, tPred, dlarray(x0Pred3), neuralOdeParameters, 'DataFormat', "CB");
xPred4 = dlode45(@odeModel, tPred, dlarray(x0Pred4), neuralOdeParameters, 'DataFormat', "CB");
figure
subplot(2, 2, 1)
plotTrueAndPredictedSolutions(xTrue1, xPred1);
subplot(2, 2, 2)
plotTrueAndPredictedSolutions(xTrue2, xPred2);
subplot(2, 2, 3)
plotTrueAndPredictedSolutions(xTrue3, xPred3);
subplot(2, 2, 4)
plotTrueAndPredictedSolutions(xTrue4, xPred4);
% Visualization function (updated for 3D Lorenz system)
function plotTrueAndPredictedSolutions(xTrue, xPred)
xPred = squeeze(xPred)';
err = mean(abs(xTrue(2:end, :) - xPred), "all");
plot3(xTrue(:, 1), xTrue(:, 2), xTrue(:, 3), "r--", xPred(:, 1), xPred(:, 2), xPred(:, 3), "b-", 'LineWidth', 1)
title("Absolute Error = " + num2str(err, "%.4f"))
xlabel("x(1)")
ylabel("x(2)")
zlabel("x(3)")
legend("Ground Truth", "Predicted")
grid on
end
function X = model(tspan,X0,neuralOdeParameters)
X = dlode45(@odeModel,tspan,X0,neuralOdeParameters,DataFormat="CB");
end
function y = odeModel(~,y,theta)
y = tanh(theta.fc1.Weights*y + theta.fc1.Bias);
y = theta.fc2.Weights*y + theta.fc2.Bias;
end
function [loss,gradients] = modelLoss(tspan,X0,neuralOdeParameters,targets)
% Compute predictions.
X = model(tspan,X0,neuralOdeParameters);
% Compute L1 loss.
loss = l1loss(X,targets,NormalizationFactor="all-elements",DataFormat="CBT");
% Compute gradients.
gradients = dlgradient(loss,neuralOdeParameters);
end
function [x0, targets] = createMiniBatch(numTimesteps,numTimesPerObs,miniBatchSize,X)
% Create batches of trajectories.
s = randperm(numTimesteps - numTimesPerObs, miniBatchSize);
x0 = dlarray(X(:, s));
targets = zeros([size(X,1) miniBatchSize numTimesPerObs]);
for i = 1:miniBatchSize
targets(:, i, 1:numTimesPerObs) = X(:, s(i) + 1:(s(i) + numTimesPerObs));
end
end
function weights = initializeGlorot(sz,numOut,numIn,className)
arguments
sz
numOut
numIn
className = 'single'
end
Z = 2*rand(sz,className) - 1;
bound = sqrt(6 / (numIn + numOut));
weights = bound * Z;
weights = dlarray(weights);
end
function parameter = initializeZeros(sz,className)
arguments
sz
className = 'single'
end
parameter = zeros(sz,className);
parameter = dlarray(parameter);
end

댓글 수: 2

Adam Danz
Adam Danz 2023년 7월 20일
I've formatted and run your code to produce the error message.
Muhammad
Muhammad 2023년 7월 20일
thank you

댓글을 달려면 로그인하십시오.

 채택된 답변

Star Strider
Star Strider 2023년 7월 20일

1 개 추천

The problem is that ‘y’ is a dlarray (the first time I’ve encountered one so I need to start working with the Deep Learning Toolbox).
Replace Line 89 with these two lines:
ys = extractdata(y)
plot3(ys(1,:),ys(2,:),ys(3,:),'b-')
to convert the dlarray to a single array, and the plot3 result magically appears! (I decided on the new variable ‘ys’ here to avoid converting ‘y’ and causing problems with the rest of your code, since the extractdata extraction only needs to be done for the plot3 call in this instance.)

댓글 수: 2

Muhammad
Muhammad 2023년 7월 20일
thank you, problem solved
Star Strider
Star Strider 2023년 7월 20일
As always, my pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

질문:

2023년 7월 20일

댓글:

2023년 7월 20일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by