For loop assignment error

조회 수: 1 (최근 30일)
Hugo Hernández Hernández
Hugo Hernández Hernández 2021년 5월 16일
답변: Rahul 2024년 8월 8일
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

답변 (1개)

Rahul
Rahul 2024년 8월 8일
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!

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by