saving a 3D array into a 2d array for each iteration in for loop

1 次查看(过去 30 天)
Suppose that I have generated a code to solve a nonlinear differential equation.My output in this equation is a 3D array.I want to store the third dimension of this 3D array(which is an n by 2 matrix itselft) into an n by 2 matrix in a for loop for each iteration.What should I do?.Note that my results is stored in 3D array matrix of X
function xDot = of(x,g,L,u)
xDot = zeros(2,1);
xDot(1) = x(2);
xDot(2) = ((g./L)*sin(x(1)))+u;
end
And the following is my main script:
clc;
clear;close all;
%% Solve The Nonlinear Equation
L = 1;
g = 9.81;
h = 0.25;
t = [0:h:4];
A = [0 1;(g/L) 0];
B =[0 1]';
Ics = [pi,0;pi/2 0;pi/5 0;0.001 0;pi 0.5;pi/2 0.5;pi/5 0.5;0.001 0.5];
Poles = eig(A); %Poles Of Closed LOop System
R = 0.001;
Q = eye(2);
K = lqr(A,B,Q,R);
u = @(x)-K*(x);
X = zeros(numel(t), size(Ics, 2), size(Ics, 1)); % initialize the 3D array
for i = 1:size(Ics,1)
[~, X(:, :, i)] = ode45(@(t, x)of(x, g, L, u(x)), t, Ics(i, :));
end

回答(1 个)

Deepak
Deepak 2024-8-9
To my understanding, you have generated a non-linear differential equation and stored the output in a 3D array. Now, you want to store the third dimension of the array (which is itself an n by 2 matrix) in a different variable in each iteration of a for loop.
To do this task, we can iterate over the third dimension of the 3D array with the help of a for loop. Then, we can fetch the third dimension from the array by doing array indexing with the help of the colon (:) operator. Finally, we can process the n-by-2 matrix as needed.
Here is the MATLAB code that addresses this task:
for i = 1:size(X, 3)
n_by_2_matrix = X(:, :, i);
% Process n_by_2_matrix as needed
disp(['Iteration ', num2str(i)]);
disp(n_by_2_matrix);
end
Attaching the documentation of Array indexing in MATLAB for reference:
I hope this helps to resolve your issue.

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by