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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by