Not able to add 2d array to 3d array

I'm trying to add the 2d array cycle to a 3d array cycle_mat. i is a variable that changes after each loop iteration. I'm getting the following error:
Subscripted assignment dimension mismatch.
Error in The_Code (line 622) cycle_mat(:,:,i)=cycle;
if true
cycle_mat=zeros(50000,4,100);
loop starts
cycle_mat(:,:,i)=cycle;
loop ends
end

댓글 수: 5

Ameer Hamza
Ameer Hamza 2018년 6월 27일
What is the dimension of cycle. The error will be caused if the dimension of cycle is not equal to [50000 x 4].
Nagesh A P
Nagesh A P 2018년 6월 27일
Each loop iteration will produce a different cycle. The dimension will also be different each time, ranging between [18000x4] and [19000x4]
Ameer Hamza
Ameer Hamza 2018년 6월 27일
But on the left side of the assignment, there is a [50000 x 4] matrix. How do you want to assign a [18000x4] to a [50000x4] matrix?
Nagesh A P
Nagesh A P 2018년 6월 27일
Okay. I thought matlab would take care of that, like it does for 2d arrays when u preallocates a matrix .So here I have to change the dimesnsion of that 3d matrix for each loop iteration??
MATLAB does not do such thing even for a 2D matrix.
A = [1 2 3; 4 5 6; 7 8 9];
is a 3x3 matrix. Now if I try
A(2, :) = [1 2];
it will again throw an error.
The dimension of left and right side of an assignment must be same. Also In a MATLAB matrix, the length of all rows must be same. Similarly for columns and pages. If your matrix size is continually changing along the third dimension then consider using cell arrays.

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

답변 (1개)

Ameer Hamza
Ameer Hamza 2018년 6월 27일

0 개 추천

The error is probably caused because the dimension of cycle are not [50000 x 4]. Also, if cycle is has a constant value then you don't need to use for loop to assign to 3rd dimension of a matrix. MATLAB support auto array expansion feature. So for R201bb and later, the following will work
cycle_mat(:,:,i_vector) = cycle_mat(:,:,i_vector) + cycle;
i_vector is a vector of all indexes to which you want to add cycle.
For R2016a and earlier
cycle_mat(:,:,i_vector) = bsxfun(@plus, cycle_mat(:,:,i_vector), cycle);

댓글 수: 1

Nagesh A P
Nagesh A P 2018년 6월 27일
Hi ameer.Cycle is not a constant value. It changes in each loop iteration.

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

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품

질문:

2018년 6월 27일

댓글:

2018년 6월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by