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!