How to store data in a pre allocated array

5 Ansichten (letzte 30 Tage)
Alex
Alex am 14 Dez. 2022
Kommentiert: Jan am 14 Dez. 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

Akzeptierte Antwort

Jan
Jan am 14 Dez. 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;
  2 Kommentare
Alex
Alex am 14 Dez. 2022
Thank you very much!! That's what I was trying to do!
Jan
Jan am 14 Dez. 2022
Fine.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by