How to store data in a pre allocated array
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
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;
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!