How to store data in a pre allocated array
조회 수: 5 (최근 30일)
이전 댓글 표시
I have a pre-allocated array. But I want to store in that array 2 values, but it gets overwritten and only stores the last value. How could I fix that?
Note: I'am comparing the values of the odd and even columns of a random matrix in a loop.
Matrix = randi([0, 1], [1000,1000]);
MatrixEven=Matrix(:,2:2:end);
MatrixOdd=Matrix(:,1:2:end);
[rows,columns]=size(MatrixEven);
[rows1,columns1]=size(Matrix);
Array_Result=NaN(rows1,columns1); %Same size as Matrix
for i=1:1:rows
for j=1:1:columns
if MatrixOdd(i,j)==MatrixEven(i,j)
Array_Result(i,j)=2; % If equal stores two '2'
Array_Result(i,j)=2;
else
Array_Result(i,j)=MatrixOdd(i,j); %If different, stores both values
Array_Result(i,j)=MatrixEven(i,j);
end
end
end
댓글 수: 0
채택된 답변
Jan
2022년 12월 14일
Of course you overwrite the values, see:
Array_Result(i,j)=2;
Array_Result(i,j)=2;
You cannot store two values in one element.
I guess you mean:
for i = 1:rows
for j = 1:columns
j2 = (j - 1)*2 + 1;
if MatrixOdd(i,j) == MatrixEven(i,j)
Array_Result(i, j2) = 2; % If equal stores two '2'
Array_Result(i, j2+1) = 2;
else
Array_Result(i, j2) = MatrixOdd(i,j); %If different, stores both values
Array_Result(i, j2+1) = MatrixEven(i,j);
end
end
end
A simpler code for the same result:
Result = Matrix;
Mask = MatrixEven == MatrixOdd;
Result(repelem(Mask, 1, 2)) = 2;
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!