For loop assignment error

1 vue (au cours des 30 derniers jours)
Hugo Hernández Hernández
Réponse apportée : Rahul le 8 Août 2024
Hi all,
I have crated a set of equations assigned to a letter and contains a variable that goes until 14002, to fill a matrix with this computations I am trying the following:
Axz = zeros(14002,4);
for i=1:14002
Axz(:,i) = [dxx,dxx_,dxz,dxz_;dzx,dzx_,dzz,dzz_];
end
The problem comes with the followinf Error:
Unable to perform assignment because the size of the left side is 14002-by-1 and the size of the right side is 14002-by-4.
Error in Test (line 51)
Axz(:,i) = [dxx,dxx_,dxz,dxz_;dzx,dzx_,dzz,dzz_];
How can I set the left side to be 14002 by 4?
Thanks for you help!
Hugo

Réponses (1)

Rahul
Rahul le 8 Août 2024
Hi Hugo,
The issue seems be to be due to a mismatch in the dimensions of the following, while assigning values to the 2D matrix Axz inside the loop:
[dxx,dxx_,dxz,dxz_;dzx,dzx_,dzz,dzz_] % Size (2, 4)
Axz(i, :) % Size (1, 4)
I've solved it using two methods as decribed below:
Method 1: Pre-allocate additional rows
Size of the matrix Axz can be increased during pre-allocation, while keeping it as 2-dimensional, to accommodate twice as many rows as follows:
% Pre-Allocation of Axz
Axz = zeros(2 * 14002, 4);
for i = 1:2:2*14002
Axz([i i + 1],:) = [dxx, dxx_, dxz, dxz_;dzx, dzx_, dzz, dzz_];
end
This will assign every 2 consecutive rows of Axz, with the desired value, at each iteration.
Method 2: Convert to a 3D Matrix
Using zeros function, pre-allocation of Axz can be done to include an extra dimension as follows:
% Pre-Allocation of Axz
Axz = zeros(14002, 4, 2);
for i = 1:14002
Axz(i, :, 1) = [dxx, dxx_, dxz, dxz_];
Axz(i, :, 2) = [dzx, dzx_, dzz, dzz_];
end
For each row i, matrix Axz now contains two 4x1 vectors Axz(i, :, 1) and Axz(i, :, 2) which contain the desired value.
For further information regarding pre-allocation of matrices, you can refer to the documentation of zeros function:
Hope this helps!

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by