How to store data in a pre allocated array

5 views (last 30 days)
Alex
Alex on 14 Dec 2022
Commented: Jan on 14 Dec 2022
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

Accepted Answer

Jan
Jan on 14 Dec 2022
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;

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!